diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 67962578f..781f7b24a 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -552,6 +552,53 @@ containing the new version number of the table *** +### delta() + +```ts +delta(fromVersion, toVersion?): Promise +``` + +Compare two persisted versions or same-branch tags on an Embedded table. + +`fromVersion` is exclusive and `toVersion` is inclusive. Omitting +`toVersion` uses the version currently visible through this handle, +including a checked-out version. The endpoints are fixed when the delta is +created. + +Row readers require stable row IDs at both endpoints. Create the table with +`storageOptions: { new_table_enable_stable_row_ids: "true" }` to enable +them. `listTransactions()` works without stable row IDs. + +Row readers reject ranges containing a Restore, or ranges whose transaction +history cannot prove they are restore-free. Recompute the checkpoint with a +full rescan and reinitialize it at the range end version. + +LanceDB Enterprise tables reject this operation. + +#### Parameters + +* **fromVersion**: [`DeltaVersion`](../type-aliases/DeltaVersion.md) + +* **toVersion?**: [`DeltaVersion`](../type-aliases/DeltaVersion.md) + +#### Returns + +`Promise`<[`TableDelta`](TableDelta.md)> + +#### Example + +```ts +const delta = await table.delta("baseline"); +const reader = delta.insertedRows(); +console.log((await reader.schema()).fields.map((field) => field.name)); +for await (const batch of reader) { + console.log(batch.getChild("id")?.toJSON()); +} +console.log(await delta.listTransactions()); +``` + +*** + ### disableRTE() ```ts diff --git a/docs/src/js/classes/TableDelta.md b/docs/src/js/classes/TableDelta.md new file mode 100644 index 000000000..9318c324b --- /dev/null +++ b/docs/src/js/classes/TableDelta.md @@ -0,0 +1,110 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / TableDelta + +# Class: TableDelta + +A handle for reading changes between two pinned table versions. + +Created by [Table.delta](Table.md#delta). Endpoints are fixed at creation; later writes +or tag moves do not change this delta. + +## Accessors + +### beginVersion + +```ts +get beginVersion(): bigint +``` + +The exclusive start version, as an exact u64 bigint. + +#### Returns + +`bigint` + +*** + +### endVersion + +```ts +get endVersion(): bigint +``` + +The inclusive end version, as an exact u64 bigint. + +#### Returns + +`bigint` + +## Methods + +### deletedRowIds() + +```ts +deletedRowIds(): TableDeltaReader +``` + +Stream deleted row IDs. Each batch has one `_rowid: uint64` column. + +#### Returns + +[`TableDeltaReader`](../interfaces/TableDeltaReader.md) + +*** + +### insertedRows() + +```ts +insertedRows(): TableDeltaReader +``` + +Stream rows inserted in `(beginVersion, endVersion]`. + +#### Returns + +[`TableDeltaReader`](../interfaces/TableDeltaReader.md) + +*** + +### listTransactions() + +```ts +listTransactions(): Promise +``` + +List readable transactions committed in `(beginVersion, endVersion]`. + +#### Returns + +`Promise`<[`TableDeltaTransaction`](../interfaces/TableDeltaTransaction.md)[]> + +*** + +### updatedRows() + +```ts +updatedRows(): TableDeltaReader +``` + +Stream rows updated in `(beginVersion, endVersion]`. + +#### Returns + +[`TableDeltaReader`](../interfaces/TableDeltaReader.md) + +*** + +### upsertedRows() + +```ts +upsertedRows(): TableDeltaReader +``` + +Stream inserted and updated rows in `(beginVersion, endVersion]`. + +#### Returns + +[`TableDeltaReader`](../interfaces/TableDeltaReader.md) diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 1769c6c1f..7f7518a27 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -49,6 +49,7 @@ - [Session](classes/Session.md) - [StaticHeaderProvider](classes/StaticHeaderProvider.md) - [Table](classes/Table.md) +- [TableDelta](classes/TableDelta.md) - [TagContents](classes/TagContents.md) - [Tags](classes/Tags.md) - [TakeQuery](classes/TakeQuery.md) @@ -158,6 +159,8 @@ - [SplitRandomOptions](interfaces/SplitRandomOptions.md) - [SplitSequentialOptions](interfaces/SplitSequentialOptions.md) - [SsTableStats](interfaces/SsTableStats.md) +- [TableDeltaReader](interfaces/TableDeltaReader.md) +- [TableDeltaTransaction](interfaces/TableDeltaTransaction.md) - [TableNamesOptions](interfaces/TableNamesOptions.md) - [TableShardStats](interfaces/TableShardStats.md) - [TableStatistics](interfaces/TableStatistics.md) @@ -189,6 +192,7 @@ - [Data](type-aliases/Data.md) - [DataLike](type-aliases/DataLike.md) - [DataTypeLike](type-aliases/DataTypeLike.md) +- [DeltaVersion](type-aliases/DeltaVersion.md) - [ExprLike](type-aliases/ExprLike.md) - [FieldLike](type-aliases/FieldLike.md) - [IntoSql](type-aliases/IntoSql.md) diff --git a/docs/src/js/interfaces/TableDeltaReader.md b/docs/src/js/interfaces/TableDeltaReader.md new file mode 100644 index 000000000..f05d56a37 --- /dev/null +++ b/docs/src/js/interfaces/TableDeltaReader.md @@ -0,0 +1,109 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / TableDeltaReader + +# Interface: TableDeltaReader + +A streaming table-delta reader. + +`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. + +## Extends + +- `AsyncIterable`<`RecordBatch`>.`AsyncIterator`<`RecordBatch`> + +## Methods + +### \[asyncIterator\]() + +```ts +asyncIterator: AsyncIterator, any, undefined> +``` + +#### Returns + +`AsyncIterator`<`RecordBatch`<`any`>, `any`, `undefined`> + +#### Inherited from + +`AsyncIterable.[asyncIterator]` + +*** + +### 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 +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/docs/src/js/interfaces/TableDeltaTransaction.md b/docs/src/js/interfaces/TableDeltaTransaction.md new file mode 100644 index 000000000..1c2bda71d --- /dev/null +++ b/docs/src/js/interfaces/TableDeltaTransaction.md @@ -0,0 +1,51 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / TableDeltaTransaction + +# Interface: TableDeltaTransaction + +A committed transaction in a table delta range. + +## Properties + +### operation + +```ts +operation: string; +``` + +*** + +### readVersion + +```ts +readVersion: bigint; +``` + +The version the transaction was based on. Exact u64 value. + +*** + +### tag? + +```ts +optional tag: string; +``` + +*** + +### transactionProperties? + +```ts +optional transactionProperties: Record; +``` + +*** + +### uuid + +```ts +uuid: string; +``` diff --git a/docs/src/js/type-aliases/DeltaVersion.md b/docs/src/js/type-aliases/DeltaVersion.md new file mode 100644 index 000000000..263b5614c --- /dev/null +++ b/docs/src/js/type-aliases/DeltaVersion.md @@ -0,0 +1,17 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / DeltaVersion + +# Type Alias: DeltaVersion + +```ts +type DeltaVersion: number | bigint | string; +``` + +One endpoint of a table delta: a positive version number/bigint or a tag on +the table handle's current branch. + +Use a `bigint` when the version may exceed `Number.MAX_SAFE_INTEGER`. +Strings are always tags. diff --git a/docs/web-tests/ts/table_delta_docs.ts b/docs/web-tests/ts/table_delta_docs.ts new file mode 100644 index 000000000..8182ca88e --- /dev/null +++ b/docs/web-tests/ts/table_delta_docs.ts @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import type { Connection } from "@lancedb/lancedb"; + +/** + * Draft checkpoint-delta example for the Versioning guide. + * + * This file is snippet source only. The published documentation test package is + * pinned to an older npm release, so it is not part of the Jest test glob. + */ +export async function versioningCheckpointDeltaExample( + db: Connection, +): Promise { + // --8<-- [start:versioning_checkpoint_delta] + const table = await db.createTable( + "checkpoint_delta_example", + [ + { id: 1, author: "Richard", quote: "Wubba Lubba Dub Dub!" }, + { id: 2, author: "Morty", quote: "Rick, what's going on?" }, + ], + { + mode: "overwrite", + storageOptions: { new_table_enable_stable_row_ids: "true" }, + }, + ); + const tags = await table.tags(); + await tags.create("baseline", await table.version()); + await table.add([ + { id: 3, author: "Summer", quote: "Whatever, Grandpa" }, + ]); + await table.update({ + where: "id = 2", + values: { quote: "Aww geez, Rick!" }, + }); + await table.delete("id = 1"); + + const delta = await table.delta("baseline"); + console.log(delta.beginVersion, delta.endVersion); + + const inserted = delta.insertedRows(); + console.log((await inserted.schema()).fields.map((field) => field.name)); + for await (const batch of inserted) { + console.log("inserted:", batch.getChild("id")?.toJSON()); + } + + const updated = delta.updatedRows(); + for await (const batch of updated) { + console.log("updated:", batch.getChild("id")?.toJSON()); + } + + const deleted = delta.deletedRowIds(); + for await (const batch of deleted) { + console.log("deleted row ids:", batch.getChild("_rowid")?.toJSON()); + } + + console.log( + "transactions:", + (await delta.listTransactions()).map( + (transaction) => transaction.operation, + ), + ); + // --8<-- [end:versioning_checkpoint_delta] +} diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index e09369dbd..0beb9836b 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -89,6 +89,7 @@ import { } from '/snippets/tables.mdx'; import { PyVersioningCheckpointDelta as VersioningCheckpointDelta, + TsVersioningCheckpointDelta as TsVersioningCheckpointDelta, RsVersioningCheckpointDelta as RsVersioningCheckpointDelta, } from '/snippets/table_delta_docs.mdx'; import { @@ -1786,10 +1787,11 @@ with stable row IDs enabled, as shown below. If a table does not have them, the row-level readers explain how to recreate it with the option. `list_transactions()` reports the transactions in the range and works without stable row IDs. -This preview supports Python and Rust for LanceDB Embedded. TypeScript support -is a follow-up. The API accepts versions and tags on the current branch only, -and rejects tags that belong to another branch. LanceDB Enterprise tables do -not support row-level deltas. +This preview supports Python, TypeScript, and Rust for LanceDB Embedded. The +API accepts versions and tags on the current branch only, and rejects tags that +belong to another branch. TypeScript exposes endpoint and transaction +`readVersion` values as `bigint`, and reader schemas are available before +streaming. LanceDB Enterprise tables do not support row-level deltas. A `Restore` can reintroduce rows with older row-version metadata that the delta readers do not report as changed. For that reason, the row-level readers reject @@ -1804,6 +1806,10 @@ range. Branch-vs-main summaries remain a separate `branches.diff()` API. {VersioningCheckpointDelta} + + {TsVersioningCheckpointDelta} + + {RsVersioningCheckpointDelta} diff --git a/docs/web/snippets/table_delta_docs.mdx b/docs/web/snippets/table_delta_docs.mdx index a1beb901b..89f5b8305 100644 --- a/docs/web/snippets/table_delta_docs.mdx +++ b/docs/web/snippets/table_delta_docs.mdx @@ -2,4 +2,6 @@ export const PyVersioningCheckpointDelta = "table = db.create_table(\n \"checkpoint_delta_example\",\n [\n {\"id\": 1, \"author\": \"Richard\", \"quote\": \"Wubba Lubba Dub Dub!\"},\n {\"id\": 2, \"author\": \"Morty\", \"quote\": \"Rick, what's going on?\"},\n ],\n storage_options={\"new_table_enable_stable_row_ids\": \"true\"},\n mode=\"overwrite\",\n)\ntable.tags.create(\"baseline\", table.version)\ntable.add([{\"id\": 3, \"author\": \"Summer\", \"quote\": \"Whatever, Grandpa\"}])\ntable.update(where=\"id = 2\", values={\"quote\": \"Aww geez, Rick!\"})\ntable.delete(\"id = 1\")\n\ndelta = table.delta(\"baseline\")\nprint(\"inserted:\", delta.inserted_rows().read_all()[\"id\"].to_pylist())\nprint(\"updated:\", delta.updated_rows().read_all()[\"id\"].to_pylist())\nprint(\"deleted:\", delta.deleted_row_ids().read_all()[\"_rowid\"].to_pylist())\nprint(\n \"transactions:\",\n [transaction[\"operation\"] for transaction in delta.list_transactions()],\n)\n"; +export const TsVersioningCheckpointDelta = "const table = await db.createTable(\n \"checkpoint_delta_example\",\n [\n { id: 1, author: \"Richard\", quote: \"Wubba Lubba Dub Dub!\" },\n { id: 2, author: \"Morty\", quote: \"Rick, what's going on?\" },\n ],\n {\n mode: \"overwrite\",\n storageOptions: { new_table_enable_stable_row_ids: \"true\" },\n },\n);\nconst tags = await table.tags();\nawait tags.create(\"baseline\", await table.version());\nawait table.add([\n { id: 3, author: \"Summer\", quote: \"Whatever, Grandpa\" },\n]);\nawait table.update({\n where: \"id = 2\",\n values: { quote: \"Aww geez, Rick!\" },\n});\nawait table.delete(\"id = 1\");\n\nconst delta = await table.delta(\"baseline\");\nconsole.log(delta.beginVersion, delta.endVersion);\n\nconst inserted = delta.insertedRows();\nconsole.log((await inserted.schema()).fields.map((field) => field.name));\nfor await (const batch of inserted) {\n console.log(\"inserted:\", batch.getChild(\"id\")?.toJSON());\n}\n\nconst updated = delta.updatedRows();\nfor await (const batch of updated) {\n console.log(\"updated:\", batch.getChild(\"id\")?.toJSON());\n}\n\nconst deleted = delta.deletedRowIds();\nfor await (const batch of deleted) {\n console.log(\"deleted row ids:\", batch.getChild(\"_rowid\")?.toJSON());\n}\n\nconsole.log(\n \"transactions:\",\n (await delta.listTransactions()).map(\n (transaction) => transaction.operation,\n ),\n);\n"; + export const RsVersioningCheckpointDelta = "use futures::TryStreamExt;\n\nlet table = db\n .create_table(\n \"checkpoint_delta_example\",\n make_quotes_reader(vec![\n (1, \"Richard\", \"Wubba Lubba Dub Dub!\"),\n (2, \"Morty\", \"Rick, what's going on?\"),\n ]),\n )\n .storage_option(\"new_table_enable_stable_row_ids\", \"true\")\n .execute()\n .await?;\n\nlet mut tags = table.tags().await?;\ntags.create(\"baseline\", table.version().await?).await?;\ntable\n .add(make_quotes_reader(vec![(3, \"Summer\", \"Whatever, Grandpa\")]))\n .execute()\n .await?;\ntable\n .update()\n .only_if(\"id = 2\")\n .column(\"quote\", \"'Aww geez, Rick!'\")\n .execute()\n .await?;\ntable.delete(\"id = 1\").await?;\n\nlet delta = table.delta(\"baseline\", None).await?;\nlet mut inserted = delta.inserted_rows().await?;\nwhile let Some(batch) = inserted.try_next().await? {\n println!(\"inserted: {:?}\", batch.column_by_name(\"id\"));\n}\nlet mut deleted = delta.deleted_row_ids().await?;\nwhile let Some(batch) = deleted.try_next().await? {\n println!(\"deleted row ids: {batch:?}\");\n}\nfor transaction in delta.list_transactions().await? {\n println!(\"{}\", transaction.operation.name());\n}\n"; diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index a77795a56..602239544 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -309,6 +309,9 @@ describe("remote connection", () => { }, async (db) => { const table = (await db.openTable("test")) as LocalTable; + await expect(table.delta(1)).rejects.toThrow( + "table.delta is only supported on LanceDB Embedded tables", + ); const cases: [() => Promise, string][] = [ [() => table.usesV2ManifestPaths(), "uses_v2_manifest_paths"], [() => table.migrateManifestPathsV2(), "migrate_manifest_paths_v2"], diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index a8bec5c98..970f2f7ca 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -17,6 +17,8 @@ import { PhraseQuery, Query, Table, + TableDelta, + TableDeltaReader, VectorQuery, blob, connect, @@ -4139,6 +4141,279 @@ describe("when dealing with branches", () => { }); }); +describe("when dealing with table delta", () => { + let tmpDir: tmp.DirResult; + // biome-ignore lint/style/useNamingConvention: storage option wire format + const stableRowIds = { new_table_enable_stable_row_ids: "true" }; + + beforeEach(() => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + }); + afterEach(() => { + tmpDir.removeCallback(); + }); + + async function readDelta( + reader: TableDeltaReader, + ): Promise { + const batches: arrow.RecordBatch[] = []; + for await (const batch of reader) { + batches.push(batch); + } + return batches; + } + + function deltaColumn(batches: arrow.RecordBatch[], name: string): unknown[] { + return batches.flatMap((batch) => batch.getChild(name)?.toJSON() ?? []); + } + + it("streams rows, transactions, and empty schemas", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable( + "delta_rows", + [ + { id: 1, value: 0 }, + { id: 2, value: 0 }, + ], + { mode: "overwrite", storageOptions: stableRowIds }, + ); + const tags = await table.tags(); + await tags.create("baseline", await table.version()); + await table.add([{ id: 3, value: 0 }]); + await table.update({ where: "id = 1", values: { value: 10 } }); + await table.delete("id = 2"); + + const delta = await table.delta("baseline", 4n); + expect(delta.beginVersion).toBe(1n); + expect(delta.endVersion).toBe(4n); + + const insertedReader = delta.insertedRows(); + expect( + (await insertedReader.schema()).fields.map((field) => field.name), + ).toEqual([ + "id", + "value", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + const inserted = await readDelta(insertedReader); + expect(deltaColumn(inserted, "id")).toEqual([3]); + + const updated = await readDelta(delta.updatedRows()); + expect(deltaColumn(updated, "id")).toEqual([1]); + const upserted = await readDelta(delta.upsertedRows()); + expect((deltaColumn(upserted, "id") as number[]).sort()).toEqual([1, 3]); + + const deleted = await readDelta(delta.deletedRowIds()); + expect(deleted).toHaveLength(1); + expect(deleted[0].schema.fields.map((field) => field.name)).toEqual([ + "_rowid", + ]); + const deletedIds = deltaColumn(deleted, "_rowid"); + expect(deletedIds).toHaveLength(1); + expect(typeof deletedIds[0]).toBe("bigint"); + + const transactions = await delta.listTransactions(); + expect(transactions.map((tx) => tx.operation)).toEqual([ + "Append", + "Update", + "Delete", + ]); + expect(transactions.map((tx) => tx.readVersion)).toEqual([1n, 2n, 3n]); + expect(transactions.every((tx) => typeof tx.readVersion === "bigint")).toBe( + true, + ); + + // Early drop after the first batch must not throw or force the rest of the + // stream to materialize. + let batchesSeen = 0; + for await (const _batch of delta.upsertedRows()) { + batchesSeen += 1; + break; + } + expect(batchesSeen).toBe(1); + + const equal = await table.delta(2, 2); + const equalReader = equal.insertedRows(); + expect( + (await equalReader.schema()).fields.map((field) => field.name), + ).toEqual([ + "id", + "value", + "_rowid", + "_row_created_at_version", + "_row_last_updated_at_version", + ]); + expect(await readDelta(equalReader)).toEqual([]); + expect( + (await equal.deletedRowIds().schema()).fields.map((field) => field.name), + ).toEqual(["_rowid"]); + expect(await equal.listTransactions()).toEqual([]); + }); + + it("pins the visible target without moving checkout state", async () => { + const conn = await connect(tmpDir.name); + const table = await conn.createTable("delta_pinned", [{ id: 1 }], { + storageOptions: stableRowIds, + }); + await table.add([{ id: 2 }]); + await table.update({ where: "id = 1", values: { id: 10 } }); + + await table.checkout(2); + const pinned = await table.delta(1n); + expect(pinned.beginVersion).toBe(1n); + expect(pinned.endVersion).toBe(2n); + expect(deltaColumn(await readDelta(pinned.insertedRows()), "id")).toEqual([ + 2, + ]); + expect(await table.version()).toBe(2); + + const explicit = await table.delta(1n, 3n); + expect(deltaColumn(await readDelta(explicit.updatedRows()), "id")).toEqual([ + 10, + ]); + expect(await table.version()).toBe(2); + 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("routes schema and Arrow decode failures through terminal cleanup", async () => { + let schemaOpens = 0; + const schemaFailure = new TableDelta({ + insertedRows: async () => { + schemaOpens += 1; + return { + schema: async () => { + throw new Error("schema export failed"); + }, + next: async () => { + throw new Error("reader must not poll after schema failure"); + }, + }; + }, + } as never); + + const schemaReader = schemaFailure.insertedRows(); + await expect(schemaReader.schema()).rejects.toThrow("schema export failed"); + await expect(schemaReader.next()).rejects.toThrow("schema export failed"); + expect(schemaOpens).toBe(1); + + const nextReader = schemaFailure.insertedRows(); + await expect(nextReader.next()).rejects.toThrow("schema export failed"); + expect(schemaOpens).toBe(2); + + let decodeOpens = 0; + const decodeFailure = new TableDelta({ + insertedRows: async () => { + decodeOpens += 1; + return { + schema: async () => Buffer.from("not an Arrow IPC schema"), + next: async () => { + throw new Error("reader must not poll after decode failure"); + }, + }; + }, + } as never); + + const decodeReader = decodeFailure.insertedRows(); + await expect(decodeReader.schema()).rejects.toThrow(); + await expect(decodeReader.next()).rejects.toThrow(); + expect(decodeOpens).toBe(1); + }); + + 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 }], { + storageOptions: stableRowIds, + }); + await table.add([{ id: 1 }]); + const forkVersion = await table.version(); + + await expect(table.delta(0)).rejects.toThrow(/positive/); + await expect(table.delta(0n)).rejects.toThrow(/positive u64/); + await expect(table.delta(1n << 64n)).rejects.toThrow(/u64 bigint/); + await expect(table.delta(-1)).rejects.toThrow(/positive/); + await expect(table.delta("")).rejects.toThrow(/non-empty/); + await expect(table.delta(1.5)).rejects.toThrow(/safe integer/); + await expect(table.delta(Number.MAX_SAFE_INTEGER + 1)).rejects.toThrow( + /safe integer/, + ); + await expect(table.delta(2, 1)).rejects.toThrow(/newer than/); + await expect(table.delta(999)).rejects.toThrow(/does not exist/); + await expect(table.delta("missing-tag")).rejects.toThrow(/does not exist/); + + const branch = await (await table.branches()).create("exp"); + await branch.add([{ id: 2 }]); + await table.add([{ id: 100 }]); + expect(await branch.version()).toBe(await table.version()); + await (await table.tags()).create("main-tag", await table.version()); + await (await branch.tags()).create("exp-tag", await branch.version()); + + const sameBranch = await branch.delta(BigInt(forkVersion), "exp-tag"); + expect(sameBranch.endVersion).toBe(3n); + expect( + deltaColumn(await readDelta(sameBranch.insertedRows()), "id"), + ).toEqual([2]); + await expect(branch.delta("main-tag")).rejects.toThrow(/branch/i); + await expect(table.delta("exp-tag")).rejects.toThrow(/branch/i); + }); +}); + /** Returns a Date strictly later than every instant observed before the call. */ async function nextMillisecond(): Promise { const start = Date.now(); @@ -6142,6 +6417,9 @@ describe("Enterprise table overrides", () => { class LegacyTable extends Table {} const table = new LegacyTable(); + await expect(table.delta(1)).rejects.toThrow( + "table.delta is only supported on LanceDB Embedded tables", + ); await expect(table.getTableOverrides()).rejects.toThrow( "getTableOverrides is not supported on this table type", ); diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index cbdfe2c18..516a3cd2d 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -164,6 +164,10 @@ export { export { Table, + TableDelta, + TableDeltaReader, + TableDeltaTransaction, + DeltaVersion, FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index e56711731..30fb60d23 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -24,6 +24,7 @@ import { Field, IntoVector, MultiVector, + RecordBatch, Schema, dataTypeToJson, fromDataToBuffer, @@ -57,7 +58,10 @@ import { IndexConfig, IndexStatistics, JobFailureInfo, + RecordBatchIterator as NativeBatchIterator, Branches as NativeBranches, + DeltaRef as NativeDeltaRef, + TableDelta as NativeTableDelta, OptimizeStats, RTEStats, RefreshColumnOptions, @@ -73,6 +77,7 @@ import { AutoQuery, FullTextQuery, Query, + RecordBatchIterator, TakeQuery, VectorQuery, createAutoQuery, @@ -253,6 +258,42 @@ export interface Version { metadata: Record; } +/** + * One endpoint of a table delta: a positive version number/bigint or a tag on + * the table handle's current branch. + * + * Use a `bigint` when the version may exceed `Number.MAX_SAFE_INTEGER`. + * Strings are always tags. + */ +export type DeltaVersion = number | bigint | string; + +/** A committed transaction in a table delta range. */ +export interface TableDeltaTransaction { + /** The version the transaction was based on. Exact u64 value. */ + readVersion: bigint; + uuid: string; + operation: string; + tag?: string; + transactionProperties?: Record; +} + +/** + * A streaming table-delta reader. + * + * `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, + AsyncIterator { + schema(): Promise; +} + /** Token produced by the tokenizer configured on a full-text search index. */ export interface FtsToken { /** Token text after tokenizer filters have been applied. */ @@ -1349,6 +1390,43 @@ export abstract class Table { * out state and the read_consistency_interval, if any, will apply. */ abstract restore(): Promise; + + /** + * Compare two persisted versions or same-branch tags on an Embedded table. + * + * `fromVersion` is exclusive and `toVersion` is inclusive. Omitting + * `toVersion` uses the version currently visible through this handle, + * including a checked-out version. The endpoints are fixed when the delta is + * created. + * + * Row readers require stable row IDs at both endpoints. Create the table with + * `storageOptions: { new_table_enable_stable_row_ids: "true" }` to enable + * them. `listTransactions()` works without stable row IDs. + * + * Row readers reject ranges containing a Restore, or ranges whose transaction + * history cannot prove they are restore-free. Recompute the checkpoint with a + * full rescan and reinitialize it at the range end version. + * + * LanceDB Enterprise tables reject this operation. + * + * @example + * const delta = await table.delta("baseline"); + * const reader = delta.insertedRows(); + * console.log((await reader.schema()).fields.map((field) => field.name)); + * for await (const batch of reader) { + * console.log(batch.getChild("id")?.toJSON()); + * } + * console.log(await delta.listTransactions()); + */ + async delta( + // biome-ignore lint/correctness/noUnusedVariables: retain the public parameter name in generated docs + fromVersion: DeltaVersion, + // biome-ignore lint/correctness/noUnusedVariables: retain the public parameter name in generated docs + toVersion?: DeltaVersion, + ): Promise { + throw new Error("table.delta is only supported on LanceDB Embedded tables"); + } + /** * Submit durable remote cleanup through SQL VACUUM and return after acceptance. * Requires table Ownership and parent Usage. Retention inherits from the table @@ -2087,6 +2165,18 @@ export class LocalTable extends Table { await this.inner.checkoutLatest(); } + async delta( + fromVersion: DeltaVersion, + toVersion?: DeltaVersion, + ): Promise { + return new TableDelta( + await this.inner.delta( + toNativeDeltaRef(fromVersion), + toVersion === undefined ? undefined : toNativeDeltaRef(toVersion), + ), + ); + } + async listVersions(): Promise { return (await this.inner.listVersions()).map((version) => ({ version: version.version, @@ -2353,6 +2443,240 @@ export interface CreateBranchOptions { fromTag: string; } +/** + * A handle for reading changes between two pinned table versions. + * + * Created by {@link Table.delta}. Endpoints are fixed at creation; later writes + * or tag moves do not change this delta. + */ +export class TableDelta { + readonly #inner: NativeTableDelta; + + /** + * Construct a table-delta handle. Internal use only. + * @hidden + */ + constructor(inner: NativeTableDelta) { + this.#inner = inner; + } + + /** The exclusive start version, as an exact u64 bigint. */ + get beginVersion(): bigint { + return this.#inner.beginVersion(); + } + + /** The inclusive end version, as an exact u64 bigint. */ + get endVersion(): bigint { + return this.#inner.endVersion(); + } + + /** Stream rows inserted in `(beginVersion, endVersion]`. */ + insertedRows(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.insertedRows()); + } + + /** Stream rows updated in `(beginVersion, endVersion]`. */ + updatedRows(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.updatedRows()); + } + + /** Stream inserted and updated rows in `(beginVersion, endVersion]`. */ + upsertedRows(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.upsertedRows()); + } + + /** Stream deleted row IDs. Each batch has one `_rowid: uint64` column. */ + deletedRowIds(): TableDeltaReader { + return tableDeltaReader(() => this.#inner.deletedRowIds()); + } + + /** List readable transactions committed in `(beginVersion, endVersion]`. */ + async listTransactions(): Promise { + const transactions = await this.#inner.listTransactions(); + return transactions.map((transaction) => ({ + readVersion: transaction.readVersion, + uuid: transaction.uuid, + operation: transaction.operation, + tag: transaction.tag ?? undefined, + transactionProperties: transaction.transactionProperties ?? undefined, + })); + } +} + +function toNativeDeltaRef(value: DeltaVersion): NativeDeltaRef { + if (typeof value === "string") { + if (value.length === 0) { + throw new Error("delta tag must be a non-empty string"); + } + return { tag: value }; + } + if (typeof value === "bigint") { + if (value <= 0n) { + throw new Error("delta version must be a positive u64 bigint"); + } + return { version: value }; + } + if (!Number.isSafeInteger(value) || value <= 0) { + throw new Error( + "delta version must be a positive safe integer; use bigint for larger versions", + ); + } + return { version: BigInt(value) }; +} + +function tableDeltaReader( + open: () => Promise, +): TableDeltaReader { + 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 = this.#loadSchema(); + } + return this.#schemaSetup; + } + + async #loadSchema(): Promise { + try { + const native = await this.#getNative(); + const schema = tableFromIPC(await native.schema()).schema; + this.#schema = schema; + return schema; + } catch (error) { + return this.#fail(error); + } + } + + 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 { + if (this.#error === undefined) { + this.#done = true; + this.#error = error; + await this.#release(); + } + throw this.#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; + } +} + /** * Branch manager for a {@link Table}. * diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 3075a7696..728240cf8 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -2,17 +2,18 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use std::collections::HashMap; +use std::sync::Arc; use chrono::{DateTime, Utc}; use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema}; use lancedb::table::{ - AddDataMode, ColumnAlteration as LanceColumnAlteration, + AddDataMode, ColumnAlteration as LanceColumnAlteration, DeltaRef as LanceDbDeltaRef, FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig as LanceFunctionRefreshPlanningConfig, FunctionRefreshPodResources as LanceFunctionRefreshPodResources, FunctionWorkerResourceBudget as LanceFunctionWorkerResourceBudget, NewColumnTransform, Ref, - Table as LanceDbTable, + Table as LanceDbTable, TableDelta as LanceDbTableDelta, }; use napi::Env; use napi::bindgen_prelude::*; @@ -22,6 +23,7 @@ use napi_derive::napi; use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable}; use crate::error::{NapiErrorExt, convert_error}; use crate::index::Index; +use crate::iterator::RecordBatchIterator; use crate::job::JobFailureInfo; use crate::merge::NativeMergeInsertBuilder; use crate::query::{Query, TakeQuery, VectorQuery}; @@ -126,6 +128,57 @@ impl CompactionOptions { } } +/// One endpoint of a table delta: a positive version or a same-branch tag. +#[napi(object)] +pub struct DeltaRef { + /// A persisted version, expressed as a positive lossless u64 bigint. + pub version: Option, + /// A tag on the table handle's current branch. + pub tag: Option, +} + +impl DeltaRef { + fn into_delta_ref(self) -> napi::Result { + match (self.version, self.tag) { + (Some(version), None) => { + let (negative, value, lossless) = version.get_u64(); + if negative || !lossless { + return Err(napi::Error::from_reason( + "delta version must be a positive lossless u64 bigint", + )); + } + if value == 0 { + return Err(napi::Error::from_reason( + "delta version must be greater than zero", + )); + } + Ok(LanceDbDeltaRef::Version(value)) + } + (None, Some(tag)) => { + if tag.is_empty() { + return Err(napi::Error::from_reason( + "delta tag must be a non-empty string", + )); + } + Ok(LanceDbDeltaRef::Tag(tag)) + } + _ => Err(napi::Error::from_reason( + "delta reference must contain exactly one of version or tag", + )), + } + } +} + +/// A committed transaction in a table delta range. +#[napi(object)] +pub struct TableDeltaTransaction { + pub read_version: BigInt, + pub uuid: String, + pub operation: String, + pub tag: Option, + pub transaction_properties: Option>, +} + #[napi] pub struct Table { // We keep a duplicate of the table name so we can use it for error @@ -955,6 +1008,19 @@ impl Table { self.inner_ref()?.checkout_latest().await.default_error() } + /// Compare two persisted versions or same-branch tags. + #[napi(catch_unwind)] + pub async fn delta( + &self, + from_version: DeltaRef, + to_version: Option, + ) -> napi::Result { + let from = from_version.into_delta_ref()?; + let to = to_version.map(DeltaRef::into_delta_ref).transpose()?; + let delta = self.inner_ref()?.delta(from, to).await.default_error()?; + Ok(TableDelta::new(delta)) + } + #[napi(catch_unwind)] pub async fn list_versions(&self) -> napi::Result> { self.inner_ref()? @@ -2434,6 +2500,75 @@ fn from_tag_hint(name: &str, tag: &str) -> String { ) } +/// A pinned version range with streaming row changes. +#[napi] +pub struct TableDelta { + inner: Arc, +} + +impl TableDelta { + fn new(inner: LanceDbTableDelta) -> Self { + Self { + inner: Arc::new(inner), + } + } +} + +#[napi] +impl TableDelta { + #[napi] + pub fn begin_version(&self) -> BigInt { + BigInt::from(self.inner.begin_version()) + } + + #[napi] + pub fn end_version(&self) -> BigInt { + BigInt::from(self.inner.end_version()) + } + + #[napi(catch_unwind)] + pub async fn inserted_rows(&self) -> napi::Result { + let stream = self.inner.inserted_rows().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn updated_rows(&self) -> napi::Result { + let stream = self.inner.updated_rows().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn upserted_rows(&self) -> napi::Result { + let stream = self.inner.upserted_rows().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn deleted_row_ids(&self) -> napi::Result { + let stream = self.inner.deleted_row_ids().await.default_error()?; + Ok(RecordBatchIterator::new(stream.into())) + } + + #[napi(catch_unwind)] + pub async fn list_transactions(&self) -> napi::Result> { + let transactions = self.inner.list_transactions().await.default_error()?; + Ok(transactions + .into_iter() + .map(|transaction| TableDeltaTransaction { + read_version: BigInt::from(transaction.read_version), + uuid: transaction.uuid, + operation: transaction.operation.name().to_string(), + tag: transaction.tag, + transaction_properties: transaction + .transaction_properties + .as_ref() + .map(|properties| (**properties).clone()), + }) + .collect()) + } +} + /// Tags label table versions with human-readable names. #[napi] pub struct Tags {