diff --git a/docs/api/index.md b/docs/api/index.md index b0cea70..2e2dc20 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -48,6 +48,7 @@ Encode an Arrow table into Arrow IPC binary format and return the result as a `U * *options* (`object`): Encoding options object. * *format* (`string`): Arrow `'stream'` (the default) or `'file'` (a.k.a. [Feather V2](https://arrow.apache.org/docs/python/feather.html)) format. * *codec* (`number`): The compression codec type to apply. By default no compression is applied. If specified, this option must be one of the `CompressionType` values, and a corresponding codec plugin must already be registered using the [`setCompressionCodec`](#setCompressionCodec) method. + * *batchMetadata* (`(Map | null)[]`): Custom metadata for each record batch, indexed by batch. Entry *i* is written to the *i*-th record batch message; `null` or `undefined` entries write no metadata. It is an error to provide more entries than the table has record batches. Defaults to the table's [`batchMetadata`](table#batchMetadata) property. ```js import { tableToIPC } from '@uwdata/flechette'; diff --git a/docs/api/table.md b/docs/api/table.md index f7c68fa..b9a4069 100644 --- a/docs/api/table.md +++ b/docs/api/table.md @@ -12,6 +12,7 @@ A table consists of named data [columns](#column) (or 'children'). To extract ta * [constructor](#constructor) * [numCols](#numCols) * [numRows](#numRows) +* [batchMetadata](#batchMetadata) * [getChildAt](#getChildAt) * [getChild](#getChild) * [selectAt](#selectAt) @@ -41,6 +42,11 @@ Table.numRows The number of rows in the table. +
# +Table.batchMetadata + +Custom metadata for each record batch, as an array of `Map` instances indexed by batch, with `null` entries for batches without metadata. The value is `null` if the table has no record batch metadata. [`tableFromIPC`](/flechette/api/#tableFromIPC) sets this property when decoded record batch messages carry custom metadata, and [`tableToIPC`](/flechette/api/#tableToIPC) writes it by default. Record batches correspond to the batches of the table's columns. +
# Table.getChildAt(index) diff --git a/src/decode/message.js b/src/decode/message.js index 3ab5450..796a757 100644 --- a/src/decode/message.js +++ b/src/decode/message.js @@ -5,6 +5,7 @@ import { MessageHeader, Version } from '../constants.js'; import { keyFor } from '../util/objects.js'; import { SIZEOF_INT, readInt16, readInt32, readInt64, readObject, readOffset, readUint8 } from '../util/read.js'; import { decodeDictionaryBatch } from './dictionary-batch.js'; +import { decodeMetadata } from './metadata.js'; import { decodeRecordBatch } from './record-batch.js'; import { decodeSchema } from './schema.js'; @@ -49,6 +50,7 @@ export function decodeMessage(buf, index) { // 6: headerType // 8: headerIndex // 10: bodyLength + // 12: custom_metadata const get = readObject(head, 0); const version = /** @type {Version_} */ (get(4, readInt16, Version.V1)); @@ -66,6 +68,11 @@ export function decodeMessage(buf, index) { : null; if (!decoder) throw new Error(invalidMessageType(type)); content = decoder(head, offset, version); + const metadata = type === MessageHeader.RecordBatch ? get(12, decodeMetadata) : null; + if (metadata) { + // @ts-ignore + content.metadata = metadata; + } // extract message body if (bodyLength > 0) { diff --git a/src/decode/table-from-ipc.js b/src/decode/table-from-ipc.js index d11bc0c..b7eb16e 100644 --- a/src/decode/table-from-ipc.js +++ b/src/decode/table-from-ipc.js @@ -118,7 +118,11 @@ export function createTable(data, options = {}) { processDict(dictionaries[dictIdx++]); } - return new Table(schema, cols.map(c => c.done()), options.useProxy); + const table = new Table(schema, cols.map(c => c.done()), options.useProxy); + if (records.some(r => r.metadata)) { + table.batchMetadata = records.map(r => r.metadata ?? null); + } + return table; } /** diff --git a/src/encode/encode-ipc.js b/src/encode/encode-ipc.js index c41d77c..66a9c62 100644 --- a/src/encode/encode-ipc.js +++ b/src/encode/encode-ipc.js @@ -6,6 +6,7 @@ import { BodyCompressionMethod, EOS, MAGIC, MessageHeader } from '../constants.j import { Builder } from './builder.js'; import { encodeDictionaryBatch } from './dictionary-batch.js'; import { writeFooter } from './footer.js'; +import { encodeMetadata } from './metadata.js'; import { encodeRecordBatch } from './record-batch.js'; import { encodeSchema } from './schema.js'; import { writeMessage } from './message.js'; @@ -65,12 +66,14 @@ export function encodeIPC(data, { sink, format = STREAM, codec } = {}) { // write record batch messages for (const batch of records) { + const metadataOffset = encodeMetadata(builder, batch.metadata); writeMessage( builder, MessageHeader.RecordBatch, encodeRecordBatch(builder, batch, compression), batch.byteLength, - recordBlocks + recordBlocks, + metadataOffset ); writeBuffers(builder, batch.buffers); } diff --git a/src/encode/message.js b/src/encode/message.js index 1705d02..b5d8e3b 100644 --- a/src/encode/message.js +++ b/src/encode/message.js @@ -11,15 +11,17 @@ import { MessageHeader, Version } from '../constants.js'; * @param {number} headerOffset * @param {number} bodyLength * @param {Block[]} [blocks] + * @param {number} [metadataOffset] Offset of encoded custom metadata, or 0 + * for none. */ -export function writeMessage(builder, headerType, headerOffset, bodyLength, blocks) { +export function writeMessage(builder, headerType, headerOffset, bodyLength, blocks, metadataOffset = 0) { builder.finish( builder.addObject(5, b => { b.addInt16(0, Version.V5, Version.V1); b.addInt8(1, headerType, MessageHeader.NONE); b.addOffset(2, headerOffset, 0); b.addInt64(3, bodyLength, 0); - // NOT SUPPORTED: 4, message-level metadata + b.addOffset(4, metadataOffset, 0); }) ); diff --git a/src/encode/table-to-ipc.js b/src/encode/table-to-ipc.js index f33e9ac..863f709 100644 --- a/src/encode/table-to-ipc.js +++ b/src/encode/table-to-ipc.js @@ -2,7 +2,7 @@ * @import { Batch, DictionaryBatch } from '../batch.js'; * @import { Column } from '../column.js'; * @import { Table } from '../table.js'; - * @import { Codec, CompressionType_, DataType, RecordBatch, Schema, TypedArray } from '../types.js'; + * @import { Codec, CompressionType_, DataType, Metadata, RecordBatch, Schema, TypedArray } from '../types.js'; * @import { Sink } from './sink.js'; */ import { compressBuffer, getCompressionCodec, missingCodec } from '../compression.js'; @@ -17,6 +17,9 @@ import { encodeIPC } from './encode-ipc.js'; * @param {Sink} [options.sink] IPC byte consumer. * @param {'stream' | 'file'} [options.format] Arrow stream or file format. * @param {CompressionType_ | null} [options.codec] Compression codec to apply. + * @param {(Metadata | null | undefined)[] | null} [options.batchMetadata] + * Custom metadata for each record batch, indexed by batch. Defaults to the + * table's batchMetadata property. * @returns {Uint8Array | null} The generated bytes (for an in-memory sink) * or null (if using a sink that writes bytes elsewhere). */ @@ -36,11 +39,22 @@ export function tableToIPC(table, options) { const { dictionaries, idMap } = assembleDictionaryBatches(columns, codec); const records = assembleRecordBatches(columns, codec); + const batchMetadata = options?.batchMetadata ?? table.batchMetadata; + if (batchMetadata) { + if (batchMetadata.length > records.length) { + throw new Error(invalidBatchMetadata(batchMetadata.length, records.length)); + } + batchMetadata.forEach((metadata, i) => records[i].metadata = metadata); + } const schema = assembleSchema(table.schema, idMap); const data = { schema, dictionaries, records }; return encodeIPC(data, { ...options, codec: id }).finish(); } +function invalidBatchMetadata(count, batches) { + return `Batch metadata has ${count} entries, but the table has ${batches} record batches.`; +} + function checkBatchLengths(columns) { const n = columns[0]?.data.map(d => d.length); columns.forEach(({ data }) => { diff --git a/src/table.js b/src/table.js index 6f5e9e3..6ab1356 100644 --- a/src/table.js +++ b/src/table.js @@ -1,6 +1,6 @@ /** * @import { Column } from './column.js' - * @import { Schema, StructFactory, TypeMap, ValueArray } from './types.js' + * @import { Metadata, Schema, StructFactory, TypeMap, ValueArray } from './types.js' */ import { bisect } from './util/arrays.js'; import { objectFactory, proxyFactory } from './util/struct.js'; @@ -44,6 +44,13 @@ export class Table { * @readonly */ this.factory = useProxy ? proxyFactory : objectFactory; + /** + * Custom metadata for each record batch, indexed by batch. An entry is + * null if the corresponding batch has no metadata. Null if the table + * has no record batch metadata. + * @type {(Metadata | null)[] | null} + */ + this.batchMetadata = null; // lazily created row object generators const gen = []; @@ -114,7 +121,7 @@ export class Table { selectAt(indices, as = []) { const { children, factory, schema } = this; const { fields } = schema; - return new Table( + const table = new Table( { ...schema, fields: indices.map((i, j) => renameField(fields[i], as[j])) @@ -122,6 +129,9 @@ export class Table { indices.map(i => children[i]), factory === proxyFactory ); + // selected columns share this table's record batches + table.batchMetadata = this.batchMetadata; + return table; } /** diff --git a/src/types.ts b/src/types.ts index f0e4165..6cff8e9 100644 --- a/src/types.ts +++ b/src/types.ts @@ -262,6 +262,8 @@ export interface RecordBatch { body?: Uint8Array; buffers?: Uint8Array[]; byteLength?: number; + /** Custom metadata for this record batch. */ + metadata?: Metadata | null; } /** diff --git a/test/batch-metadata.test.js b/test/batch-metadata.test.js new file mode 100644 index 0000000..a0ae3f4 --- /dev/null +++ b/test/batch-metadata.test.js @@ -0,0 +1,81 @@ +import { describe, it, expect } from 'vitest'; +import { RecordBatch, Table, tableFromArrays as arrowTableFromArrays, tableFromIPC as arrowTableFromIPC, tableToIPC as arrowTableToIPC } from 'apache-arrow'; +import { columnFromArray, dictionary, int32, tableFromColumns, tableFromIPC, tableToIPC, utf8 } from '../src/index.js'; + +const md1 = new Map([['status', 'ok'], ['request_id', 'a1']]); +const md3 = new Map([['status', 'done']]); + +// Build a three-batch table: x = int32, s = dictionary-encoded strings. +function flechetteTable() { + const opt = { maxBatchRows: 2 }; + return tableFromColumns({ + x: columnFromArray([1, 2, 3, 4, 5], int32(), opt), + s: columnFromArray(['a', 'b', 'a', 'c', 'b'], dictionary(utf8()), opt) + }); +} + +// Arrow JS reference data with metadata on the first and last batches. +function arrowBytes(format) { + const batches = [[1, 2], [3, 4], [5]].map((x, i) => { + const batch = arrowTableFromArrays({ x: Int32Array.from(x) }).batches[0]; + const metadata = [md1, null, md3][i]; + return metadata ? new RecordBatch(batch.schema, batch.data, metadata) : batch; + }); + return arrowTableToIPC(new Table(batches), format); +} + +describe('record batch custom metadata', () => { + for (const format of ['stream', 'file']) { + it(`decodes metadata written by Arrow JS (${format})`, () => { + const table = tableFromIPC(arrowBytes(format)); + expect(table.batchMetadata).toStrictEqual([md1, null, md3]); + expect(table.toColumns().x).toStrictEqual(Int32Array.of(1, 2, 3, 4, 5)); + }); + + it(`encodes metadata readable by Arrow JS (${format})`, () => { + const bytes = tableToIPC(flechetteTable(), { + format, batchMetadata: [md1, undefined, md3] + }); + const arrow = arrowTableFromIPC(bytes); + expect(arrow.batches.map(b => b.metadata)).toStrictEqual([md1, new Map, md3]); + expect(arrow.getChild('s').toArray()).toStrictEqual(['a', 'b', 'a', 'c', 'b']); + }); + + it(`round-trips table batch metadata by default (${format})`, () => { + const table = tableFromIPC(arrowBytes(format)); + const decoded = tableFromIPC(tableToIPC(table, { format })); + expect(decoded.batchMetadata).toStrictEqual([md1, null, md3]); + }); + } + + it('leaves batch metadata null when absent', () => { + const table = flechetteTable(); + expect(table.batchMetadata).toBe(null); + const decoded = tableFromIPC(tableToIPC(table)); + expect(decoded.batchMetadata).toBe(null); + }); + + it('writes the batchMetadata property of constructed tables', () => { + const table = flechetteTable(); + table.batchMetadata = [null, md1]; + const decoded = tableFromIPC(tableToIPC(table)); + expect(decoded.batchMetadata).toStrictEqual([null, md1, null]); + }); + + it('prefers the batchMetadata option over the table property', () => { + const table = flechetteTable(); + table.batchMetadata = [md1]; + const decoded = tableFromIPC(tableToIPC(table, { batchMetadata: [null, null, md3] })); + expect(decoded.batchMetadata).toStrictEqual([null, null, md3]); + }); + + it('preserves batch metadata when selecting columns', () => { + const table = tableFromIPC(arrowBytes('stream')); + expect(table.select(['x'], ['y']).batchMetadata).toStrictEqual([md1, null, md3]); + }); + + it('rejects more metadata entries than record batches', () => { + expect(() => tableToIPC(flechetteTable(), { batchMetadata: [md1, md1, md1, md1] })) + .toThrow('Batch metadata has 4 entries, but the table has 3 record batches.'); + }); +});