mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat: add resumable staged table writes (#5358)
A coordinator can publish batches staged by multiple ingest workers in a single table version. This adds staged append and overwrite in LanceDB Embedded and Enterprise across Rust, synchronous and asynchronous Python, and TypeScript. Ordinary `table.add()` continues to commit immediately. A coordinator selects the mode with `begin_write(mode)` (`beginWrite` in TypeScript) and shares the opaque write ID. Workers open the same writable table and branch and resume with `open_write(id)` (`openWrite` in TypeScript). They can retry the same input with the same idempotency key. Staging returns no version. Explicit `commit()` publishes one version and returns `AddResult`. Explicit `abort()` discards the staged write and can be repeated. Dropping a handle performs no I/O. Enterprise uses the existing multipart endpoints on servers with multipart write support. A non-empty staged overwrite input carrying top-level Arrow schema metadata fails before the SDK sends any part insert. The SDK enforces this in Rust `StagedWrite::add(...).execute()`, Python `StagedWrite.add` and `AsyncStagedWrite.add`, and TypeScript `StagedWrite.add` on every supported Enterprise server version. Empty input is a no-op. Staged append and overwrite with an empty top-level map are supported, including field and nested field metadata on overwrite. [OSS-2859](https://linear.app/lancedb/issue/OSS-2859) · [Distributed reads in OSS-441](https://linear.app/lancedb/issue/OSS-441) The separate Sophon fix preserves top-level schema metadata in the server’s multipart overwrite path. The SDK follow-up verifies a route that sends every part, retry, and completion to fixed instances before lifting the guard. [ENT-4970](https://linear.app/lancedb/issue/ENT-4970/multipart-overwrite-drops-top-level-schema-metadata-in-sophon) · [Sophon #11472](https://github.com/lancedb/sophon/pull/11472) · [OSS-3312](https://linear.app/lancedb/issue/OSS-3312/enable-schema-metadata-in-enterprise-staged-overwrite-after-verifying) Embedded staged overwrites keep top-level, field, and nested-field metadata from the replacement schema. Commit rejects overwrite parts whose restored schemas differ. The Insert data guide shows staged writes in Python, TypeScript, and Rust. The Distributed Write guide describes both SDK-coordinated staging and server-coordinated CTAS. ## Validation Final head `cf6737cece7b17f33a13556ba13f1460a0d4cfc8` adds the guard in `a02beb97084cb9d5d70b0bfdbbf31ce7bb4b1067` and a documentation-only commit. - **Rust.** All 14 `--lib staged_write` tests and all 15 `--lib multipart_write` tests passed with the locked `ci` profile and Enterprise support. `explicit_enterprise_overwrite_rejects_schema_metadata_before_upload` covers rejection before insert, known and streaming empty inputs, and a subsequent field-metadata part in the same session. - **Python and Sophon 1.16.0.** The Python extension was rebuilt with the final Rust inputs. The staged-write and permutation suites passed 133 tests with 2 skipped. On the isolated released-service fixture, sync and async staged overwrite rejected top-level metadata with zero insert requests. A materialized zero-row table and a streaming zero-row batch both succeeded without an insert. A fresh read verified the original version, row, and schema. Two independent workers then staged parts with field and nested field metadata, and an independent coordinator published one version with exactly the replacement rows. The reopened SDK table and Lance manifest preserved that metadata. Ordinary overwrite and staged append also succeeded. - **TypeScript and docs.** TypeScript compilation, lint, TypeDoc, strict MkDocs, and Vale passed. The final TypeScript changes are documentation. The earlier Node native build and staged-write test below cover the binding. The Rust tests and rebuilt Python extension exercised the final shared guard. At `ab9f49fba5055a5f731fe013a820515aa5cfa12c`, all 11 Rust staged-write integration tests and 13 staged-write unit tests passed. The new tests exercise independent reopen, reject differences at each metadata level, and verify one publication with the complete schema after replacing the mismatched part. Rust formatting and Vale passed for the follow-up. On the initial validation head `68e950d24a1418890f80eb04102de49388012318`: - Rust passed the library check with Enterprise support and 15 existing multipart tests. - Python passed both staged-write tests covering synchronous multiprocessing and asynchronous overwrite and abort. The separate fail-loud fragment constraint regression passed all 39 cases. [#5120](https://github.com/lancedb/lancedb/pull/5120) - Node.js passed the native build, TypeScript compilation, lint, and the staged-write Jest test. TypeDoc generation and strict MkDocs also passed. The initial Python and Node.js native extensions were built at `47ea43533f103744e84a7cdbe83d8e4a8ddf093e` with the repository’s `ci` profile, the default SDK features, and locked Lance 16.0.0-beta.7 and `object_store` 0.14.2. The initial validation head differs from that build commit only in two generated TypeDoc pages. The Python and Node.js tests ran again at that head using the same native artifacts. The candidate Python SDK passed multipart create, cross-process staging, commit, and abort against released LanceDB Enterprise (Sophon) 1.16.0 on an isolated loopback gateway and S3-compatible store. After an ordinary append published version 2, a separate coordinator committed the staged batches once to version 3, with exactly the three expected rows. The probe also verified overwrite conflict handling, schema refresh after a successful overwrite, and branch and pinned-handle behavior. Both abort modes removed the upload marker and staged transaction records, rejected subsequent staging and commit, and left the table at version 3 with the same rows. Append abort removed its staged payload. Overwrite abort left one unreferenced data file in object storage for storage cleanup. A separate Sophon 1.16.0 probe confirmed that multipart overwrite loses top-level schema metadata, including `embedding_functions` and `lancedb::column_definitions`. Field and nested-field metadata survived, and a single-request overwrite preserved the full metadata on the same input. ## Local security comparison Compared head `ab9f49fba5055a5f731fe013a820515aa5cfa12c` with its merge base `c85647526c90647d9b5d6a701afeacca3f47b34d`. - **Dependencies.** OSV-Scanner 2.7.1 used one offline crates.io advisory snapshot for both Cargo locks. Each scan read 1,098 package entries and reported the same 48 advisory matches across 24 package versions. The change makes the already-locked `prost` 0.14.4 a direct dependency for Embedded, where Lance already pulls it in. OSV and the GitHub Advisory Database returned no advisory for that version. The Cargo, Python, and Node lockfiles are byte-identical. The latter two therefore did not require a dependency audit. - **Source.** Semgrep Community Edition 1.187.0 ran 658 security and secret rules on 16 baseline files and 24 candidate files across Rust, Python, and TypeScript. Both results contained the same 31 matches on unchanged code, with zero skipped targets or parse errors. These were existing Rust `unsafe` blocks in tests and N-API branch metadata, a Python serialization check, and a TypeScript iterator call through `Symbol.asyncIterator`. [Rule snapshot](https://github.com/semgrep/semgrep-rules/tree/a5ad1714f00c9f7fde980cab0ea1d6dc6d414fd2) The OSV results cover lockfile package versions in the local database. Semgrep covers the changed source files with file-local analysis. Rule-level Aikido results were unavailable for comparison.
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import { tableFromArrays } from "apache-arrow";
|
||||
import * as tmp from "tmp";
|
||||
import { StagedWrite, connect } from "../lancedb";
|
||||
|
||||
test("staged write reopens across table handles and keeps the overwrite schema", async () => {
|
||||
const dir = tmp.dirSync({ unsafeCleanup: true });
|
||||
try {
|
||||
const db = await connect(dir.name);
|
||||
const table = await db.createTable("items", [{ id: 1 }]);
|
||||
const write = await table.beginWrite("overwrite");
|
||||
expect(write).toBeInstanceOf(StagedWrite);
|
||||
expect(typeof write.id).toBe("string");
|
||||
|
||||
const workerDb = await connect(dir.name);
|
||||
const workerTable = await workerDb.openTable("items");
|
||||
const worker = await workerTable.openWrite(write.id);
|
||||
await expect(worker.add([])).resolves.toBeUndefined();
|
||||
await expect(write.commit()).rejects.toThrow("no staged rows");
|
||||
const rows = tableFromArrays({ value: ["staged"] });
|
||||
await expect(worker.add(rows, { idempotencyKey: "" })).rejects.toThrow(
|
||||
"nonempty",
|
||||
);
|
||||
await expect(
|
||||
worker.add(rows, { idempotencyKey: "worker" }),
|
||||
).resolves.toBeUndefined();
|
||||
await worker.add(rows, { idempotencyKey: "worker" });
|
||||
expect(await table.version()).toBe(1);
|
||||
expect((await table.schema()).fields.map((field) => field.name)).toEqual([
|
||||
"id",
|
||||
]);
|
||||
|
||||
const committerDb = await connect(dir.name);
|
||||
const committer = await committerDb.openTable("items");
|
||||
const result = await (await committer.openWrite(write.id)).commit();
|
||||
expect(result.version).toBe(2);
|
||||
expect((await committer.query().toArray()).map((row) => row.value)).toEqual(
|
||||
["staged"],
|
||||
);
|
||||
|
||||
const discarded = await committer.beginWrite();
|
||||
await discarded.add(rows);
|
||||
await expect(discarded.abort()).resolves.toBeUndefined();
|
||||
await expect(discarded.abort()).resolves.toBeUndefined();
|
||||
expect(await committer.version()).toBe(2);
|
||||
} finally {
|
||||
dir.removeCallback();
|
||||
}
|
||||
});
|
||||
@@ -197,6 +197,7 @@ export {
|
||||
|
||||
export {
|
||||
Table,
|
||||
StagedWrite,
|
||||
TableDelta,
|
||||
TableDeltaReader,
|
||||
TableDeltaTransaction,
|
||||
|
||||
+104
-6
@@ -77,6 +77,7 @@ import {
|
||||
BranchContents as NativeBranchContents,
|
||||
Branches as NativeBranches,
|
||||
DeltaRef as NativeDeltaRef,
|
||||
StagedWrite as NativeStagedWrite,
|
||||
TableDelta as NativeTableDelta,
|
||||
OptimizeStats,
|
||||
RTEStats,
|
||||
@@ -559,6 +560,30 @@ export abstract class Table {
|
||||
data: Data,
|
||||
options?: Partial<AddDataOptions>,
|
||||
): Promise<AddResult>;
|
||||
|
||||
/**
|
||||
* Start a staged append or overwrite on this writable table and branch.
|
||||
* Share the write ID with workers and commit once after their adds finish.
|
||||
* Enterprise requires a server with multipart write support.
|
||||
* @example
|
||||
* ```ts
|
||||
* const write = await table.beginWrite("append");
|
||||
* const worker = await workerTable.openWrite(write.id);
|
||||
* await worker.add([{ id: 42 }], { idempotencyKey: "task-1" });
|
||||
* const { version } = await write.commit();
|
||||
* ```
|
||||
*/
|
||||
async beginWrite(
|
||||
_mode: AddDataOptions["mode"] = "append",
|
||||
): Promise<StagedWrite> {
|
||||
throw new Error("Staged writes are unavailable for this table type");
|
||||
}
|
||||
|
||||
/** Reopen a staged write on its original writable table and branch. */
|
||||
async openWrite(_writeId: string): Promise<StagedWrite> {
|
||||
throw new Error("Staged writes are unavailable for this table type");
|
||||
}
|
||||
|
||||
/**
|
||||
* Update existing records in the Table
|
||||
* @param opts.values The values to update. The keys are the column names and the values
|
||||
@@ -1844,12 +1869,7 @@ export class LocalTable extends Table {
|
||||
throw new Error("retries must be an integer between 0 and 255");
|
||||
}
|
||||
const mode = options?.mode ?? "append";
|
||||
const schema =
|
||||
mode === "overwrite" && isArrowTable(data)
|
||||
? sanitizeSchema(data.schema)
|
||||
: await this.schema();
|
||||
|
||||
const buffer = await fromDataToBuffer(data, undefined, schema);
|
||||
const buffer = await addDataToBuffer(data, mode, () => this.schema());
|
||||
// Wrap the user callback so a thrown error doesn't surface as an
|
||||
// unhandled exception (the callback fires from a napi threadsafe
|
||||
// function — exceptions there crash the process).
|
||||
@@ -1878,6 +1898,16 @@ export class LocalTable extends Table {
|
||||
);
|
||||
}
|
||||
|
||||
async beginWrite(
|
||||
mode: AddDataOptions["mode"] = "append",
|
||||
): Promise<StagedWrite> {
|
||||
return new StagedWrite(await this.inner.beginWrite(mode));
|
||||
}
|
||||
|
||||
async openWrite(writeId: string): Promise<StagedWrite> {
|
||||
return new StagedWrite(await this.inner.openWrite(writeId));
|
||||
}
|
||||
|
||||
async update(
|
||||
optsOrUpdates:
|
||||
| (Map<string, string> | Record<string, string>)
|
||||
@@ -2738,6 +2768,74 @@ export interface CreateBranchOptions {
|
||||
fromTag: string;
|
||||
}
|
||||
|
||||
async function addDataToBuffer(
|
||||
data: Data,
|
||||
mode: AddDataOptions["mode"],
|
||||
inputSchema: () => Promise<Schema>,
|
||||
): Promise<Buffer> {
|
||||
const schema =
|
||||
mode === "overwrite" && isArrowTable(data)
|
||||
? sanitizeSchema(data.schema)
|
||||
: await inputSchema();
|
||||
return fromDataToBuffer(data, undefined, schema);
|
||||
}
|
||||
|
||||
/**
|
||||
* A resumable append or overwrite created by {@link Table.beginWrite}.
|
||||
* Share the ID with workers that can reopen the same table and branch.
|
||||
* Dropping a handle leaves the write available to other processes.
|
||||
*/
|
||||
export class StagedWrite {
|
||||
readonly #inner: NativeStagedWrite;
|
||||
|
||||
/** @hidden */
|
||||
constructor(inner: NativeStagedWrite) {
|
||||
this.#inner = bindErrorTranslator(inner);
|
||||
}
|
||||
|
||||
/** The opaque identifier to pass to {@link Table.openWrite}. */
|
||||
get id(): string {
|
||||
return this.#inner.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage rows without publishing a version. Empty input is a no-op.
|
||||
* Use a nonempty idempotency key for each task and reuse it for the same
|
||||
* data, order, and batching on retry. Enterprise uses byte-based chunking
|
||||
* with the configured byte limit. If changed input produces fewer parts,
|
||||
* the original trailing parts remain staged.
|
||||
*
|
||||
* On LanceDB Enterprise, this method rejects non-empty overwrite input
|
||||
* with top-level schema metadata before uploading any parts. Field and
|
||||
* nested field metadata are supported.
|
||||
*/
|
||||
async add(data: Data, options?: { idempotencyKey?: string }): Promise<void> {
|
||||
const buffer = await addDataToBuffer(data, this.#inner.mode, async () => {
|
||||
return tableFromIPC(await this.#inner.inputSchema()).schema;
|
||||
});
|
||||
await this.#inner.add(buffer, options?.idempotencyKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish one version and return its number in an AddResult.
|
||||
* A write with no staged rows fails. Inspect the table if a completion
|
||||
* error reports an unknown outcome. On Embedded, a retry of a confirmed
|
||||
* commit returns the published version and resumes cleanup.
|
||||
*/
|
||||
async commit(): Promise<AddResult> {
|
||||
return this.#inner.commit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Discard the staged write. Repeating an abort is safe. Current Enterprise
|
||||
* servers leave the unreferenced data files of aborted overwrites for storage
|
||||
* cleanup.
|
||||
*/
|
||||
async abort(): Promise<void> {
|
||||
await this.#inner.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A handle for reading changes between two pinned table versions.
|
||||
*
|
||||
|
||||
+78
-8
@@ -12,7 +12,7 @@ use lancedb::table::{
|
||||
FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken,
|
||||
FunctionRefreshPlanningConfig as LanceFunctionRefreshPlanningConfig,
|
||||
FunctionRefreshPodResources as LanceFunctionRefreshPodResources, NewColumnTransform, Ref,
|
||||
Table as LanceDbTable, TableDelta as LanceDbTableDelta,
|
||||
StagedWrite as LanceDbStagedWrite, Table as LanceDbTable, TableDelta as LanceDbTableDelta,
|
||||
};
|
||||
use napi::Env;
|
||||
use napi::bindgen_prelude::*;
|
||||
@@ -181,6 +181,65 @@ pub struct TableDeltaTransaction {
|
||||
pub transaction_properties: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
fn parse_add_mode(mode: &str) -> napi::Result<AddDataMode> {
|
||||
match mode {
|
||||
"append" => Ok(AddDataMode::Append),
|
||||
"overwrite" => Ok(AddDataMode::Overwrite),
|
||||
_ => Err(napi::Error::from_reason(format!("Invalid mode: {mode}"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub struct StagedWrite {
|
||||
inner: LanceDbStagedWrite,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl StagedWrite {
|
||||
#[napi(getter)]
|
||||
pub fn id(&self) -> String {
|
||||
self.inner.id().to_owned()
|
||||
}
|
||||
|
||||
#[napi(getter, ts_return_type = "'append' | 'overwrite'")]
|
||||
pub fn mode(&self) -> &'static str {
|
||||
match self.inner.mode() {
|
||||
AddDataMode::Append => "append",
|
||||
AddDataMode::Overwrite => "overwrite",
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn input_schema(&self) -> napi::Result<Buffer> {
|
||||
let schema = self.inner.input_schema().await.default_error()?;
|
||||
schema_to_buffer(&schema)
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn add(&self, buf: Buffer, idempotency_key: Option<String>) -> napi::Result<()> {
|
||||
let reader = ipc_file_to_batches(buf.to_vec()).default_error()?;
|
||||
let mut add = self.inner.add(reader);
|
||||
if let Some(key) = idempotency_key {
|
||||
add = add.idempotency_key(key);
|
||||
}
|
||||
add.execute().await.default_error()
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn commit(&self) -> napi::Result<AddResult> {
|
||||
self.inner
|
||||
.commit()
|
||||
.await
|
||||
.map(AddResult::from)
|
||||
.default_error()
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn abort(&self) -> napi::Result<()> {
|
||||
self.inner.abort().await.default_error()
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub struct Table {
|
||||
// We keep a duplicate of the table name so we can use it for error
|
||||
@@ -224,6 +283,23 @@ impl Table {
|
||||
self.inner.take();
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn begin_write(&self, mode: String) -> napi::Result<StagedWrite> {
|
||||
let mode = parse_add_mode(&mode)?;
|
||||
let inner = self.inner_ref()?.begin_write(mode).await.default_error()?;
|
||||
Ok(StagedWrite { inner })
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn open_write(&self, write_id: String) -> napi::Result<StagedWrite> {
|
||||
let inner = self
|
||||
.inner_ref()?
|
||||
.open_write(write_id)
|
||||
.await
|
||||
.default_error()?;
|
||||
Ok(StagedWrite { inner })
|
||||
}
|
||||
|
||||
/// Return Schema as empty Arrow IPC file.
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn schema(&self) -> napi::Result<Buffer> {
|
||||
@@ -263,13 +339,7 @@ impl Table {
|
||||
op = op.retries(retries);
|
||||
}
|
||||
|
||||
op = if mode == "append" {
|
||||
op.mode(AddDataMode::Append)
|
||||
} else if mode == "overwrite" {
|
||||
op.mode(AddDataMode::Overwrite)
|
||||
} else {
|
||||
return Err(napi::Error::from_reason(format!("Invalid mode: {}", mode)));
|
||||
};
|
||||
op = op.mode(parse_add_mode(&mode)?);
|
||||
|
||||
op = op
|
||||
.allow_external_blob_outside_bases(allow_external_blob_outside_bases.unwrap_or(false));
|
||||
|
||||
Reference in New Issue
Block a user