mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-29 22:13:58 +00:00
feat(nodejs): add table delta streams (#5149)
Adds the Embedded `Table.delta` API to the Node.js bindings, matching the Rust/Python contract from #5135. `Table.delta(fromVersion, toVersion?)` accepts a positive safe-integer number, a positive lossless u64 `bigint`, or a same-branch tag string. `TableDelta` exposes `beginVersion`/`endVersion` as `bigint`, streaming `insertedRows()`, `updatedRows()`, `upsertedRows()`, `deletedRowIds()`, and `listTransactions()` with `readVersion` as `bigint`. Readers reuse the existing native Arrow IPC iterator adapter. They are lazy, single-use, serialize pulls, capture/cache the schema before polling, and release the native stream on completion, break, or error. Row readers retain the Rust contract: equal endpoints return empty streams with schemas, invalid/reversed/missing endpoints and cross-branch tags are rejected, and Restore or incomplete transaction history fail closed with full-rescan and range-end checkpoint guidance. Enterprise tables remain unsupported through the native Rust default. The abstract `Table` keeps a concrete unsupported `delta` default for custom subclasses; `LocalTable` overrides it. TypeDoc API docs and focused Node tests cover pinned targets, typed bigint values, transaction listing, lazy rejected readers, schema/decode failures, aliasing, and early drop. Refs OSS-2860
This commit is contained in:
@@ -164,6 +164,10 @@ export {
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableDelta,
|
||||
TableDeltaReader,
|
||||
TableDeltaTransaction,
|
||||
DeltaVersion,
|
||||
FunctionColumnAutoRefreshStatus,
|
||||
FunctionColumnLastRefreshJob,
|
||||
FunctionColumnStatus,
|
||||
|
||||
@@ -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<string, 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.
|
||||
*/
|
||||
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<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<RecordBatch>,
|
||||
AsyncIterator<RecordBatch> {
|
||||
schema(): Promise<Schema>;
|
||||
}
|
||||
|
||||
/** 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<void>;
|
||||
|
||||
/**
|
||||
* 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<TableDelta> {
|
||||
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<TableDelta> {
|
||||
return new TableDelta(
|
||||
await this.inner.delta(
|
||||
toNativeDeltaRef(fromVersion),
|
||||
toVersion === undefined ? undefined : toNativeDeltaRef(toVersion),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async listVersions(): Promise<Version[]> {
|
||||
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<TableDeltaTransaction[]> {
|
||||
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<NativeBatchIterator>,
|
||||
): TableDeltaReader {
|
||||
return new TableDeltaReaderImpl(open);
|
||||
}
|
||||
|
||||
class TableDeltaReaderImpl implements TableDeltaReader {
|
||||
readonly #open: () => Promise<NativeBatchIterator>;
|
||||
#setup?: Promise<NativeBatchIterator>;
|
||||
#schema?: Schema;
|
||||
#schemaSetup?: Promise<Schema>;
|
||||
#iterator?: AsyncIterator<RecordBatch>;
|
||||
#error?: unknown;
|
||||
#done = false;
|
||||
#pullQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
constructor(open: () => Promise<NativeBatchIterator>) {
|
||||
this.#open = open;
|
||||
}
|
||||
|
||||
[Symbol.asyncIterator](): AsyncIterator<RecordBatch> {
|
||||
return this;
|
||||
}
|
||||
|
||||
async schema(): Promise<Schema> {
|
||||
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<Schema> {
|
||||
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<IteratorResult<RecordBatch>> {
|
||||
return this.#serialize(() => this.#pull());
|
||||
}
|
||||
|
||||
async return(): Promise<IteratorResult<RecordBatch>> {
|
||||
await this.#serialize(async () => {
|
||||
this.#done = true;
|
||||
await this.#release();
|
||||
});
|
||||
return { done: true, value: undefined };
|
||||
}
|
||||
|
||||
async throw(error?: unknown): Promise<IteratorResult<RecordBatch>> {
|
||||
await this.#serialize(async () => {
|
||||
this.#done = true;
|
||||
await this.#release();
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
|
||||
async #pull(): Promise<IteratorResult<RecordBatch>> {
|
||||
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<RecordBatch> {
|
||||
if (this.#iterator === undefined) {
|
||||
this.#iterator = RecordBatchIterator(this.#getNative())[
|
||||
Symbol.asyncIterator
|
||||
]();
|
||||
}
|
||||
return this.#iterator;
|
||||
}
|
||||
|
||||
async #getNative(): Promise<NativeBatchIterator> {
|
||||
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<never> {
|
||||
if (this.#error === undefined) {
|
||||
this.#done = true;
|
||||
this.#error = error;
|
||||
await this.#release();
|
||||
}
|
||||
throw this.#error;
|
||||
}
|
||||
|
||||
async #release(): Promise<void> {
|
||||
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<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const next = this.#pullQueue.then(operation, operation);
|
||||
this.#pullQueue = next.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Branch manager for a {@link Table}.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user