diff --git a/docs/src/js/interfaces/TableDeltaReader.md b/docs/src/js/interfaces/TableDeltaReader.md index f96cee4a8..f05d56a37 100644 --- a/docs/src/js/interfaces/TableDeltaReader.md +++ b/docs/src/js/interfaces/TableDeltaReader.md @@ -12,9 +12,13 @@ A streaming table-delta reader. range is empty. The stream yields Arrow record batches without materializing the full result. +A reader owns one native cursor. It is single-use: +`[Symbol.asyncIterator]()` returns the same iterator, concurrent pulls are +serialized, and `return()` releases the native stream on early drop. + ## Extends -- `AsyncIterable`<`RecordBatch`> +- `AsyncIterable`<`RecordBatch`>.`AsyncIterator`<`RecordBatch`> ## Methods @@ -34,6 +38,46 @@ asyncIterator: AsyncIterator, any, undefined> *** +### next() + +```ts +next(...args): Promise, any>> +``` + +#### Parameters + +* ...**args**: [] \| [`undefined`] + +#### Returns + +`Promise`<`IteratorResult`<`RecordBatch`<`any`>, `any`>> + +#### Inherited from + +`AsyncIterator.next` + +*** + +### return()? + +```ts +optional return(value?): Promise, any>> +``` + +#### Parameters + +* **value?**: `any` + +#### Returns + +`Promise`<`IteratorResult`<`RecordBatch`<`any`>, `any`>> + +#### Inherited from + +`AsyncIterator.return` + +*** + ### schema() ```ts @@ -43,3 +87,23 @@ schema(): Promise> #### Returns `Promise`<`Schema`<`any`>> + +*** + +### throw()? + +```ts +optional throw(e?): Promise, any>> +``` + +#### Parameters + +* **e?**: `any` + +#### Returns + +`Promise`<`IteratorResult`<`RecordBatch`<`any`>, `any`>> + +#### Inherited from + +`AsyncIterator.throw` diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index f7bfbac16..fc68920ae 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4276,6 +4276,61 @@ describe("when dealing with table delta", () => { await table.checkoutLatest(); }); + it("does not start a rejected reader until it is used", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("delta_lazy", [{ id: 1 }]); + await table.add([{ id: 2 }]); + + const delta = await table.delta(1); + const reader = delta.insertedRows(); + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", onUnhandled); + try { + await new Promise((resolve) => setTimeout(resolve, 25)); + expect(unhandled).toEqual([]); + await expect(reader.schema()).rejects.toThrow(/stable row ids/); + await expect(reader.next()).rejects.toThrow(/stable row ids/); + } finally { + process.off("unhandledRejection", onUnhandled); + } + }); + + it("uses one reader cursor and releases it on early drop", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("delta_reader", [{ id: 1 }], { + storageOptions: stableRowIds, + }); + await table.add([{ id: 2 }]); + const delta = await table.delta(1); + + const reader = delta.insertedRows(); + expect(reader[Symbol.asyncIterator]()).toBe(reader); + const first = await reader.next(); + expect(first.done).toBe(false); + const [second, third] = await Promise.all([reader.next(), reader.next()]); + expect(second.done).toBe(true); + expect(third.done).toBe(true); + expect((await reader.schema()).fields.map((field) => field.name)).toEqual([ + "id", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + + const dropped = delta.insertedRows(); + for await (const _batch of dropped) { + break; + } + expect(await dropped.next()).toEqual({ done: true, value: undefined }); + expect((await dropped.schema()).fields.map((field) => field.name)).toEqual([ + "id", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + }); + it("rejects invalid endpoints and cross-branch tags", async () => { const conn = await connect(tmpDir.name, { readConsistencyInterval: 0 }); const table = await conn.createTable("delta_errors", [{ id: 0 }], { diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index ec75e0149..6c98c779a 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -283,8 +283,14 @@ export interface TableDeltaTransaction { * `schema()` is available before consuming the stream, including when the * range is empty. The stream yields Arrow record batches without * materializing the full result. + * + * A reader owns one native cursor. It is single-use: + * `[Symbol.asyncIterator]()` returns the same iterator, concurrent pulls are + * serialized, and `return()` releases the native stream on early drop. */ -export interface TableDeltaReader extends AsyncIterable { +export interface TableDeltaReader + extends AsyncIterable, + AsyncIterator { schema(): Promise; } @@ -2457,22 +2463,22 @@ export class TableDelta { /** Stream rows inserted in `(beginVersion, endVersion]`. */ insertedRows(): TableDeltaReader { - return tableDeltaReader(this.#inner.insertedRows()); + return tableDeltaReader(() => this.#inner.insertedRows()); } /** Stream rows updated in `(beginVersion, endVersion]`. */ updatedRows(): TableDeltaReader { - return tableDeltaReader(this.#inner.updatedRows()); + return tableDeltaReader(() => this.#inner.updatedRows()); } /** Stream inserted and updated rows in `(beginVersion, endVersion]`. */ upsertedRows(): TableDeltaReader { - return tableDeltaReader(this.#inner.upsertedRows()); + return tableDeltaReader(() => this.#inner.upsertedRows()); } /** Stream deleted row IDs. Each batch has one `_rowid: uint64` column. */ deletedRowIds(): TableDeltaReader { - return tableDeltaReader(this.#inner.deletedRowIds()); + return tableDeltaReader(() => this.#inner.deletedRowIds()); } /** List readable transactions committed in `(beginVersion, endVersion]`. */ @@ -2510,14 +2516,148 @@ function toNativeDeltaRef(value: DeltaVersion): NativeDeltaRef { } function tableDeltaReader( - promisedInner: Promise, + open: () => Promise, ): TableDeltaReader { - return { - schema: async () => tableFromIPC((await promisedInner).schema()).schema, - [Symbol.asyncIterator](): AsyncIterator { - return RecordBatchIterator(promisedInner); - }, - }; + return new TableDeltaReaderImpl(open); +} + +class TableDeltaReaderImpl implements TableDeltaReader { + readonly #open: () => Promise; + #setup?: Promise; + #schema?: Schema; + #schemaSetup?: Promise; + #iterator?: AsyncIterator; + #error?: unknown; + #done = false; + #pullQueue: Promise = Promise.resolve(); + + constructor(open: () => Promise) { + this.#open = open; + } + + [Symbol.asyncIterator](): AsyncIterator { + return this; + } + + async schema(): Promise { + if (this.#schema !== undefined) { + return this.#schema; + } + if (this.#error !== undefined) { + throw this.#error; + } + if (this.#schemaSetup === undefined) { + this.#schemaSetup = (async () => { + const native = await this.#getNative(); + const schema = tableFromIPC(await native.schema()).schema; + this.#schema = schema; + return schema; + })(); + } + return this.#schemaSetup; + } + + next(): Promise> { + return this.#serialize(() => this.#pull()); + } + + async return(): Promise> { + await this.#serialize(async () => { + this.#done = true; + await this.#release(); + }); + return { done: true, value: undefined }; + } + + async throw(error?: unknown): Promise> { + await this.#serialize(async () => { + this.#done = true; + await this.#release(); + }); + throw error; + } + + async #pull(): Promise> { + if (this.#error !== undefined) { + throw this.#error; + } + if (this.#done) { + return { done: true, value: undefined }; + } + + // Capture the schema before polling the reader's shared native iterator. + await this.schema(); + try { + const result = await this.#getIterator().next(); + if (result.done) { + this.#done = true; + await this.#release(); + } + return result; + } catch (error) { + return this.#fail(error); + } + } + + #getIterator(): AsyncIterator { + if (this.#iterator === undefined) { + this.#iterator = RecordBatchIterator(this.#getNative())[ + Symbol.asyncIterator + ](); + } + return this.#iterator; + } + + async #getNative(): Promise { + if (this.#error !== undefined) { + throw this.#error; + } + if (this.#done) { + throw new Error("table delta reader is already consumed"); + } + if (this.#setup === undefined) { + try { + this.#setup = this.#open(); + } catch (error) { + return this.#fail(error); + } + } + try { + return await this.#setup; + } catch (error) { + return this.#fail(error); + } + } + + async #fail(error: unknown): Promise { + this.#done = true; + this.#error = error; + await this.#release(); + throw error; + } + + async #release(): Promise { + const iterator = this.#iterator; + this.#iterator = undefined; + this.#setup = undefined; + if (iterator?.return !== undefined) { + try { + await iterator.return(); + } catch { + // The native stream already failed or completed; releasing the + // reference is enough. + } + } + } + + #serialize(operation: () => Promise): Promise { + const next = this.#pullQueue.then(operation, operation); + this.#pullQueue = next.then( + () => undefined, + () => undefined, + ); + return next; + } } /**