Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> | 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';
Expand Down
6 changes: 6 additions & 0 deletions docs/api/table.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -41,6 +42,11 @@ Table.<b>numRows</b>

The number of rows in the table.

<hr/><a id="batchMetadata" href="#batchMetadata">#</a>
Table.<b>batchMetadata</b>

Custom metadata for each record batch, as an array of `Map<string, string>` 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.

<hr/><a id="getChildAt" href="#getChildAt">#</a>
Table.<b>getChildAt</b>(<i>index</i>)

Expand Down
7 changes: 7 additions & 0 deletions src/decode/message.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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));
Expand All @@ -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) {
Expand Down
6 changes: 5 additions & 1 deletion src/decode/table-from-ipc.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
5 changes: 4 additions & 1 deletion src/encode/encode-ipc.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
}
Expand Down
6 changes: 4 additions & 2 deletions src/encode/message.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
})
);

Expand Down
16 changes: 15 additions & 1 deletion src/encode/table-to-ipc.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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).
*/
Expand All @@ -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 }) => {
Expand Down
14 changes: 12 additions & 2 deletions src/table.js
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 = [];
Expand Down Expand Up @@ -114,14 +121,17 @@ 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]))
},
indices.map(i => children[i]),
factory === proxyFactory
);
// selected columns share this table's record batches
table.batchMetadata = this.batchMetadata;
return table;
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,8 @@ export interface RecordBatch {
body?: Uint8Array;
buffers?: Uint8Array[];
byteLength?: number;
/** Custom metadata for this record batch. */
metadata?: Metadata | null;
}

/**
Expand Down
81 changes: 81 additions & 0 deletions test/batch-metadata.test.js
Original file line number Diff line number Diff line change
@@ -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.');
});
});
Loading