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,88 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / StagedWrite
|
||||
|
||||
# Class: StagedWrite
|
||||
|
||||
A resumable append or overwrite created by [Table.beginWrite](Table.md#beginwrite).
|
||||
Share the ID with workers that can reopen the same table and branch.
|
||||
Dropping a handle leaves the write available to other processes.
|
||||
|
||||
## Accessors
|
||||
|
||||
### id
|
||||
|
||||
```ts
|
||||
get id(): string
|
||||
```
|
||||
|
||||
The opaque identifier to pass to [Table.openWrite](Table.md#openwrite).
|
||||
|
||||
#### Returns
|
||||
|
||||
`string`
|
||||
|
||||
## Methods
|
||||
|
||||
### abort()
|
||||
|
||||
```ts
|
||||
abort(): Promise<void>
|
||||
```
|
||||
|
||||
Discard the staged write. Repeating an abort is safe. Current Enterprise
|
||||
servers leave the unreferenced data files of aborted overwrites for storage
|
||||
cleanup.
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`void`>
|
||||
|
||||
***
|
||||
|
||||
### add()
|
||||
|
||||
```ts
|
||||
add(data, options?): Promise<void>
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **data**: [`Data`](../type-aliases/Data.md)
|
||||
|
||||
* **options?**
|
||||
|
||||
* **options.idempotencyKey?**: `string`
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<`void`>
|
||||
|
||||
***
|
||||
|
||||
### commit()
|
||||
|
||||
```ts
|
||||
commit(): Promise<AddResult>
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`AddResult`](../interfaces/AddResult.md)>
|
||||
@@ -144,6 +144,35 @@ containing the new version number of the table after altering the columns.
|
||||
|
||||
***
|
||||
|
||||
### beginWrite()
|
||||
|
||||
```ts
|
||||
beginWrite(_mode): Promise<StagedWrite>
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **\_mode**: `"append"` \| `"overwrite"` = `"append"`
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`StagedWrite`](StagedWrite.md)>
|
||||
|
||||
#### 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();
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### blobColumns()
|
||||
|
||||
```ts
|
||||
@@ -1299,6 +1328,24 @@ after use.
|
||||
|
||||
***
|
||||
|
||||
### openWrite()
|
||||
|
||||
```ts
|
||||
openWrite(_writeId): Promise<StagedWrite>
|
||||
```
|
||||
|
||||
Reopen a staged write on its original writable table and branch.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **\_writeId**: `string`
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`StagedWrite`](StagedWrite.md)>
|
||||
|
||||
***
|
||||
|
||||
### optimize()
|
||||
|
||||
```ts
|
||||
|
||||
@@ -77,6 +77,7 @@
|
||||
- [SchemaError](classes/SchemaError.md)
|
||||
- [Session](classes/Session.md)
|
||||
- [SqlError](classes/SqlError.md)
|
||||
- [StagedWrite](classes/StagedWrite.md)
|
||||
- [StaticHeaderProvider](classes/StaticHeaderProvider.md)
|
||||
- [Table](classes/Table.md)
|
||||
- [TableAlreadyExistsError](classes/TableAlreadyExistsError.md)
|
||||
|
||||
@@ -437,6 +437,8 @@ code that used the former LanceDB Enterprise-only argument order.
|
||||
|
||||
::: lancedb.table.Table
|
||||
|
||||
::: lancedb.table.StagedWrite
|
||||
|
||||
::: lancedb.table.CompactionOptions
|
||||
|
||||
::: lancedb.table.FragmentStatistics
|
||||
@@ -453,6 +455,56 @@ code that used the former LanceDB Enterprise-only argument order.
|
||||
|
||||
::: lancedb.RTEWriteSpec
|
||||
|
||||
### Stage writes across processes
|
||||
|
||||
A staged write groups the output of multiple workers into one table version.
|
||||
Create the table with a schema first if it is new. Pass the opaque write ID to
|
||||
workers that can open the same writable table and branch. Wait for workers to
|
||||
finish before committing or aborting from the coordinator.
|
||||
|
||||
```python
|
||||
# Coordinator
|
||||
write = table.begin_write(mode="append")
|
||||
write_id = write.id
|
||||
|
||||
# Worker with its own connection, using a retry key unique to the task
|
||||
worker = worker_db.open_table("items").open_write(write_id)
|
||||
worker.add(batch, idempotency_key="partition-7")
|
||||
|
||||
# Coordinator, possibly in a new process with its own connection
|
||||
result = table.open_write(write_id).commit()
|
||||
print(result.version)
|
||||
```
|
||||
|
||||
Use `mode="overwrite"` to replace the table with the staged rows. Every
|
||||
worker must use the same output schema. An intervening table version causes
|
||||
an overwrite to fail. An append can rebase over concurrent appends. Calls to
|
||||
`table.add()` continue to publish immediately.
|
||||
|
||||
An empty worker input stages zero rows. An empty session fails to commit.
|
||||
Call `abort()` to discard the staged write if the coordinator decides to
|
||||
stop. Dropping a coordinator or worker handle leaves the write open. If
|
||||
completion reports an unknown outcome, inspect the table before any retry
|
||||
or cleanup.
|
||||
|
||||
- **Embedded.** The write uses the base version captured at `begin_write()`.
|
||||
Keep that version and its staged files available until finalization. Schedule
|
||||
cleanup of unverified files after staged writes finish. A backend must
|
||||
support atomic object creation and consistent metadata reads and listings.
|
||||
Retrying a worker with the same key replaces its previous staged part.
|
||||
After a confirmed commit, calling `commit()` again returns the same version
|
||||
and retries cleanup. Retain the committed version until cleanup finishes.
|
||||
The table keeps one terminal record per finalized write to protect against
|
||||
delayed worker and coordinator requests. A submission with no durable
|
||||
outcome stays fenced until Lance history can confirm publication. This
|
||||
includes a rejection whose receipt could not be written during a storage
|
||||
outage.
|
||||
- **Enterprise.** Requires a server with multipart write support. A worker
|
||||
retry needs the same data, ordering, batching, and request byte limit.
|
||||
If changed input produces fewer chunks, the original trailing chunks remain
|
||||
staged. Current servers discard an aborted overwrite session and leave its
|
||||
unreferenced data files for storage cleanup.
|
||||
|
||||
### Registering a table with DataFusion
|
||||
|
||||
With DataFusion Python 55.x installed, register a LanceDB Embedded `Table` or
|
||||
@@ -1459,6 +1511,18 @@ Table hold your actual data as a collection of records / rows.
|
||||
|
||||
::: lancedb.table.AsyncTable
|
||||
|
||||
::: lancedb.table.AsyncStagedWrite
|
||||
|
||||
Staging works with separate async table handles as well:
|
||||
|
||||
```python
|
||||
write = await table.begin_write(mode="overwrite")
|
||||
worker_table = await worker_db.open_table("items")
|
||||
worker = await worker_table.open_write(write.id)
|
||||
await worker.add(batch, idempotency_key="partition-7")
|
||||
result = await write.commit()
|
||||
```
|
||||
|
||||
::: lancedb.table.AsyncTags
|
||||
|
||||
::: lancedb.table.AsyncBranches
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
---
|
||||
title: "Distributed Write"
|
||||
sidebarTitle: "Distributed Write"
|
||||
description: "How LanceDB Enterprise distributes a CTAS import's writes across plan executors."
|
||||
description: "How LanceDB Enterprise distributes CTAS imports and how SDK callers coordinate staged ingestion."
|
||||
icon: upload
|
||||
availability:
|
||||
embedded: unavailable
|
||||
enterprise: available
|
||||
---
|
||||
|
||||
Distributed write applies specifically to importing data with `CREATE
|
||||
TABLE ... AS SELECT`: the query node that planned the statement partitions
|
||||
the source -- Parquet files from a HuggingFace dataset, or row-group
|
||||
ranges of an existing Lance dataset in object storage -- across plan
|
||||
executors, each of which writes its own uncommitted Lance data files and
|
||||
reports back. The query node collects those results and commits them
|
||||
together as the new table's first version; no separate coordinator
|
||||
service is involved. See [Architecture](/index#architecture).
|
||||
## Server-coordinated CTAS imports {#ctas}
|
||||
|
||||
For `CREATE TABLE ... AS SELECT`, the query node partitions the source across
|
||||
executors. The source can be Parquet files from a HuggingFace dataset or
|
||||
row-group ranges of an existing Lance dataset in object storage. Each executor
|
||||
writes uncommitted Lance data files and reports back. The query node collects
|
||||
those results and commits them together as the new table's first version.
|
||||
See [Architecture](/index#architecture).
|
||||
|
||||
<div className="hidden dark:block">
|
||||
|
||||
@@ -75,16 +75,26 @@ flowchart LR
|
||||
|
||||
</div>
|
||||
|
||||
An ordinary `INSERT` or `merge_insert`, from SQL or the SDK, does not
|
||||
distribute this way -- it runs as a single write, on whichever node or
|
||||
process executes it. Only a CTAS import fans the write itself out across
|
||||
machines.
|
||||
Ordinary `INSERT` and `merge_insert` run on the node or process that executes
|
||||
them. The CTAS import is the server-coordinated path that assigns writes to
|
||||
multiple executors.
|
||||
|
||||
## SDK-coordinated staged writes {#sdk-staged-writes}
|
||||
|
||||
For an existing table, an application can divide its input among workers and
|
||||
share one staged write ID. Each worker opens the same table and branch and
|
||||
stages its batch through the SDK. The application's coordinator calls `commit()`
|
||||
to publish one version or `abort()` to discard the upload. Enterprise uses its
|
||||
multipart write endpoints for staging and completion.
|
||||
|
||||
For a staged overwrite, the SDK rejects non-empty input with top-level schema
|
||||
metadata before uploading any parts. Field and nested field metadata are
|
||||
supported. See the [staged write examples](/ingestion/insert#staged-writes).
|
||||
|
||||
## Write interfaces {#write-interfaces}
|
||||
|
||||
- [Import Datasets](/ingestion/import) for the CTAS syntax this
|
||||
distributes.
|
||||
- [Insert data](/ingestion/insert) and [Merge](/ingestion/merge-insert)
|
||||
for the ordinary, non-distributed write paths.
|
||||
- [Import Datasets](/ingestion/import) for distributed CTAS imports.
|
||||
- [Insert data](/ingestion/insert) for ordinary `add()` and explicit staged
|
||||
writes, and [Merge](/ingestion/merge-insert) for upserts.
|
||||
- [Storage Integration](/sql/ddl/storage-integration) for configuring
|
||||
the source a CTAS import reads from.
|
||||
|
||||
+100
-10
@@ -121,6 +121,92 @@ increase memory use. TypeScript does not expose that manual option.
|
||||
Measure with realistic row sizes and storage. Avoid one write per row when a
|
||||
batch will do, and avoid a large worker count for a small input.
|
||||
|
||||
## Stage a write across processes {#staged-writes}
|
||||
|
||||
Use a staged write when several workers need to publish their batches as one
|
||||
table version. A coordinator opens the write in `append` or `overwrite` mode
|
||||
and shares its opaque ID. Workers connect to the same writable table and
|
||||
branch, reopen the write by ID, and stage their batches. `add()` on a staged
|
||||
write returns no version. Once all workers finish, a coordinator reopens the
|
||||
write and calls `commit()` to publish one version and receive its number.
|
||||
|
||||
The examples assume that the coordinator and worker have separate connections
|
||||
to the same database and that the `items` table has an integer `id` column.
|
||||
Pass the ID and a task-specific key to each worker through your job runner.
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
# Coordinator
|
||||
items = coordinator_db.open_table("items")
|
||||
write_id = items.begin_write(mode="append").id
|
||||
|
||||
# Worker
|
||||
worker = worker_db.open_table("items").open_write(write_id)
|
||||
worker.add([{"id": 42}], idempotency_key="batch-1")
|
||||
|
||||
# Coordinator, after every worker finishes
|
||||
result = items.open_write(write_id).commit()
|
||||
print(result.version)
|
||||
```
|
||||
|
||||
```typescript TypeScript icon="square-js"
|
||||
// Coordinator
|
||||
const items = await coordinatorDb.openTable("items");
|
||||
const { id: writeId } = await items.beginWrite("append");
|
||||
|
||||
// Worker
|
||||
const workerTable = await workerDb.openTable("items");
|
||||
const worker = await workerTable.openWrite(writeId);
|
||||
await worker.add([{ id: 42 }], { idempotencyKey: "batch-1" });
|
||||
|
||||
// Coordinator, after every worker finishes
|
||||
const write = await items.openWrite(writeId);
|
||||
const { version } = await write.commit();
|
||||
console.log(version);
|
||||
```
|
||||
|
||||
```rust Rust icon="rust"
|
||||
use lancedb::table::AddDataMode;
|
||||
|
||||
// Coordinator
|
||||
let items = coordinator_db.open_table("items").execute().await?;
|
||||
let write_id = items.begin_write(AddDataMode::Append).await?.id().to_owned();
|
||||
|
||||
// Worker
|
||||
let worker_table = worker_db.open_table("items").execute().await?;
|
||||
let worker = worker_table.open_write(&write_id).await?;
|
||||
let batch = arrow_array::record_batch!(("id", Int32, [42]))?;
|
||||
worker.add(batch).idempotency_key("batch-1").execute().await?;
|
||||
|
||||
// Coordinator, after every worker finishes
|
||||
let result = items.open_write(&write_id).await?.commit().await?;
|
||||
println!("{}", result.version);
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Reuse a task's idempotency key with the same data, order, and batching when
|
||||
retrying. Use a different key for each task. Enterprise stages parts by byte
|
||||
size, so keep the [request byte limit](#bulk-ingests-into-a-remote-table)
|
||||
consistent across workers. If changed input produces fewer parts under the same
|
||||
key, the original trailing parts remain staged.
|
||||
|
||||
Empty batches have no effect. If every worker produces zero rows, `commit()`
|
||||
returns an error. To discard a write, reopen it by ID and call `abort()`.
|
||||
Repeating `abort()` is safe. Dropping a handle leaves the session open.
|
||||
|
||||
Keep the write's base version and staged data available until you commit or
|
||||
abort. Append can rebase over concurrent appends. An overwrite requires
|
||||
matching replacement schemas and fails if another write advances the table.
|
||||
Embedded compares schema and field metadata across overwrite parts. On
|
||||
Enterprise, a non-empty overwrite input must have an empty top-level schema
|
||||
metadata map. The SDK rejects input with top-level schema metadata before
|
||||
uploading any parts. Field and nested field metadata are supported.
|
||||
|
||||
If a completion error reports an unknown outcome, inspect the table before
|
||||
retrying or aborting. Enterprise staging requires server and catalog support
|
||||
for [multipart writes](#bulk-ingests-into-a-remote-table). Enterprise can retain
|
||||
unreferenced data files after an overwrite abort for storage cleanup.
|
||||
|
||||
## Track completion and progress {#tracking-ingestion-progress}
|
||||
|
||||
Python, TypeScript and Rust support progress callbacks when adding data.
|
||||
@@ -234,12 +320,15 @@ status, the client retries the part with the same upload ID, part ID, and IPC
|
||||
bytes. `RetryConfig.statuses` controls status retries. An empty list disables
|
||||
them. The default includes `500`, `502`, `503`, and `504`.
|
||||
The server replaces that part's staged transaction, so losing
|
||||
its response does not append the rows twice. Exhausting the part retry budget
|
||||
aborts the uncommitted session; it does not restart the entire upload.
|
||||
A complete request rejected with a transaction conflict (`409`) or rate limit
|
||||
(`429`) also triggers best-effort cleanup. Cleanup uses the call's retry budget;
|
||||
its failure does not replace the original error. Ambiguous completion outcomes
|
||||
never trigger cleanup or replay.
|
||||
its response does not append the rows twice.
|
||||
|
||||
For multipart uploads managed by an ordinary table `add()`, exhausting the part
|
||||
retry budget aborts the uncommitted upload. A complete request rejected with a
|
||||
transaction conflict (`409`) or rate limit (`429`) also triggers best-effort
|
||||
cleanup. Cleanup uses the call's retry budget and preserves the original error.
|
||||
With [explicit staging](#staged-writes), the coordinator controls abort and a
|
||||
failed worker can retry its own part. Ambiguous completion outcomes never
|
||||
trigger cleanup or replay.
|
||||
|
||||
Part size still affects memory and HTTP timeouts. A single blob row cannot be
|
||||
split across Arrow batches; a very large row may require a larger timeout and
|
||||
@@ -253,10 +342,11 @@ Two environment variables control how a multipart write's parts are cut. Both ar
|
||||
| `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` | 64 MiB | Target LZ4-compressed IPC bytes per replayable part. A single indivisible row and its IPC schema may exceed the target. `0` disables byte-based cuts and can require buffering a whole partition. |
|
||||
| `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Time spent filling a replayable payload, in whole seconds. `0` disables time-based cuts. HTTP deadlines are configured separately in `timeout_config`. |
|
||||
|
||||
A part is cut after an encoding slice reaches either limit. Input batches are
|
||||
sliced to approximately 8 MiB before encoding, preserving row order. Peak
|
||||
additional memory scales with active writers and the part budget. Lower
|
||||
`write_parallelism` or the byte budget to reduce memory use.
|
||||
For ordinary table `add()`, a part is cut after an encoding slice reaches either
|
||||
limit. Explicit staged writes use the byte limit. Input batches are sliced to
|
||||
approximately 8 MiB before encoding, preserving row order. Peak additional
|
||||
memory scales with active writers and the part budget. Lower `write_parallelism`
|
||||
or the byte budget to reduce memory use.
|
||||
|
||||
<CodeGroup>
|
||||
```bash Bash icon="terminal"
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -78,7 +78,7 @@ from .materialized_view import (
|
||||
)
|
||||
from .view import ViewDescription as ViewDescription
|
||||
from .graph import PropertyGraph, PropertyGraphDescription
|
||||
from .table import AsyncTable, CompactionOptions, Table
|
||||
from .table import AsyncStagedWrite, AsyncTable, CompactionOptions, StagedWrite, Table
|
||||
from .query import ColumnOrdering as ColumnOrdering
|
||||
from .types import BaseTokenizerType
|
||||
from ._lancedb import Session
|
||||
@@ -677,6 +677,8 @@ __all__ = [
|
||||
"AsyncSqlQuery",
|
||||
"AsyncLanceNamespaceDBConnection",
|
||||
"AsyncTable",
|
||||
"AsyncStagedWrite",
|
||||
"StagedWrite",
|
||||
"CompactionOptions",
|
||||
"FtsToken",
|
||||
"FunctionColumnAutoRefreshStatus",
|
||||
|
||||
@@ -39,6 +39,7 @@ from lance_namespace import (
|
||||
DescribeNamespaceResponse,
|
||||
)
|
||||
from .remote import ClientConfig
|
||||
from .scannable import Scannable
|
||||
from .types import BaseTokenizerType
|
||||
|
||||
__version__: str
|
||||
@@ -652,6 +653,10 @@ class Table:
|
||||
def close(self) -> None: ...
|
||||
async def schema(self) -> pa.Schema: ...
|
||||
def schema_sync(self) -> pa.Schema: ...
|
||||
async def begin_write(
|
||||
self, mode: Literal["append", "overwrite"]
|
||||
) -> StagedWrite: ...
|
||||
async def open_write(self, write_id: str) -> StagedWrite: ...
|
||||
async def add(
|
||||
self,
|
||||
data: pa.RecordBatchReader,
|
||||
@@ -1078,6 +1083,16 @@ class ColumnOrdering(TypedDict):
|
||||
ascending: bool
|
||||
nulls_first: bool
|
||||
|
||||
class StagedWrite:
|
||||
def id(self) -> str: ...
|
||||
def mode(self) -> Literal["append", "overwrite"]: ...
|
||||
async def input_schema(self) -> pa.Schema: ...
|
||||
async def add(
|
||||
self, data: Scannable, idempotency_key: Optional[str] = None
|
||||
) -> None: ...
|
||||
async def commit(self) -> AddResult: ...
|
||||
async def abort(self) -> None: ...
|
||||
|
||||
class TableDelta:
|
||||
def begin_version(self) -> int: ...
|
||||
def end_version(self) -> int: ...
|
||||
|
||||
@@ -85,11 +85,12 @@ from ..table import (
|
||||
CompactionResult,
|
||||
IndexStatistics,
|
||||
Query,
|
||||
StagedWrite,
|
||||
Table,
|
||||
TableDelta,
|
||||
Tags,
|
||||
)
|
||||
from ..types import BaseTokenizerType, ScalarIndexType
|
||||
from ..types import AddMode, BaseTokenizerType, ScalarIndexType
|
||||
from ..util import infer_vector_column_name
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -827,6 +828,12 @@ class RemoteTable(Table):
|
||||
if owns:
|
||||
progress.close()
|
||||
|
||||
def begin_write(self, mode: AddMode = "append") -> StagedWrite:
|
||||
return StagedWrite(LOOP.run(self._table.begin_write(mode)))
|
||||
|
||||
def open_write(self, write_id: str) -> StagedWrite:
|
||||
return StagedWrite(LOOP.run(self._table.open_write(write_id)))
|
||||
|
||||
def search(
|
||||
self,
|
||||
query: Union[VEC, str, os.PathLike[str]] = None,
|
||||
|
||||
+222
-45
@@ -34,7 +34,12 @@ from typing import (
|
||||
)
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable
|
||||
from lancedb.scannable import (
|
||||
Scannable,
|
||||
_hf_batches,
|
||||
_register_optional_converters,
|
||||
to_scannable,
|
||||
)
|
||||
|
||||
from . import __version__
|
||||
from ._lancedb import FunctionColumnStatus, _parse_field_path, _uses_sql_subquery_filter
|
||||
@@ -333,6 +338,7 @@ if TYPE_CHECKING:
|
||||
from .db import DBConnection, LanceDBConnection
|
||||
from ._lancedb import (
|
||||
Table as LanceDBTable,
|
||||
StagedWrite as NativeStagedWrite,
|
||||
OptimizeStats,
|
||||
CleanupStats,
|
||||
CompactionStats,
|
||||
@@ -702,6 +708,59 @@ def _iterator_to_reader(
|
||||
return pa.RecordBatchReader.from_batches(schema, gen())
|
||||
|
||||
|
||||
async def _prepare_add_data(
|
||||
data: DATA,
|
||||
schema: pa.Schema,
|
||||
mode: AddMode,
|
||||
on_bad_vectors: Optional[OnBadVectorsType],
|
||||
fill_value: Optional[float],
|
||||
) -> Scannable:
|
||||
data = _serialize_json_values(data, schema)
|
||||
blob_table = _blob_input_to_arrow(data, schema)
|
||||
if blob_table is not None:
|
||||
data = blob_table
|
||||
if on_bad_vectors is None:
|
||||
on_bad_vectors = "error"
|
||||
if fill_value is None:
|
||||
fill_value = 0.0
|
||||
|
||||
# _sanitize_data is an old code path, but we will use it until the
|
||||
# new code path is ready.
|
||||
if mode == "overwrite":
|
||||
# For overwrite, apply the same preprocessing as create_table
|
||||
# so vector columns are inferred as FixedSizeList.
|
||||
data, _ = await asyncio.to_thread(
|
||||
sanitize_create_table,
|
||||
data,
|
||||
None,
|
||||
on_bad_vectors=on_bad_vectors,
|
||||
fill_value=fill_value,
|
||||
overwrite_schema=schema,
|
||||
)
|
||||
if blob_v2_column_paths(schema):
|
||||
# Plain bytes cannot be inferred as blob v2. Keep matching blob
|
||||
# fields while allowing other columns to use the inferred schema.
|
||||
target_schema = _preserve_blob_v2_fields(data.schema, schema)
|
||||
data = _cast_to_target_schema(data, target_schema)
|
||||
elif on_bad_vectors != "error" or (
|
||||
schema.metadata is not None and b"embedding_functions" in schema.metadata
|
||||
):
|
||||
data = await asyncio.to_thread(
|
||||
_sanitize_data,
|
||||
data,
|
||||
schema,
|
||||
metadata=schema.metadata,
|
||||
on_bad_vectors=on_bad_vectors,
|
||||
fill_value=fill_value,
|
||||
allow_subschema=True,
|
||||
)
|
||||
_register_optional_converters()
|
||||
# Converting an iterator peeks at its first item. A synchronous query in
|
||||
# that iterator schedules work on LOOP, so peeking on LOOP's own thread
|
||||
# would deadlock waiting for itself.
|
||||
return await asyncio.to_thread(to_scannable, data)
|
||||
|
||||
|
||||
def _sanitize_data(
|
||||
data: "DATA",
|
||||
target_schema: Optional[pa.Schema] = None,
|
||||
@@ -2685,6 +2744,20 @@ class Table(ABC):
|
||||
"""
|
||||
raise NotImplementedError("add is not supported for this table type")
|
||||
|
||||
def begin_write(self, mode: AddMode = "append") -> StagedWrite:
|
||||
"""Start a staged append or overwrite on this writable table and branch.
|
||||
|
||||
Share the handle's [id][lancedb.table.StagedWrite.id] with worker
|
||||
processes. They can reopen the same table and branch and stage their
|
||||
inputs. After all worker calls finish, commit once to publish a version.
|
||||
Enterprise requires a server with multipart write support.
|
||||
"""
|
||||
raise NotImplementedError("staged writes are not supported for this table type")
|
||||
|
||||
def open_write(self, write_id: str) -> StagedWrite:
|
||||
"""Reopen a staged write on its original writable table and branch."""
|
||||
raise NotImplementedError("staged writes are not supported for this table type")
|
||||
|
||||
def merge_insert(self, on: Union[str, Iterable[str]]) -> LanceMergeInsertBuilder:
|
||||
"""
|
||||
Returns a [`LanceMergeInsertBuilder`][lancedb.merge.LanceMergeInsertBuilder]
|
||||
@@ -6051,6 +6124,12 @@ class LanceTable(Table):
|
||||
if owns:
|
||||
progress.close()
|
||||
|
||||
def begin_write(self, mode: AddMode = "append") -> StagedWrite:
|
||||
return StagedWrite(LOOP.run(self._table.begin_write(mode)))
|
||||
|
||||
def open_write(self, write_id: str) -> StagedWrite:
|
||||
return StagedWrite(LOOP.run(self._table.open_write(write_id)))
|
||||
|
||||
def merge(
|
||||
self,
|
||||
other_table: Union[LanceTable, DATA],
|
||||
@@ -8678,50 +8757,9 @@ class AsyncTable:
|
||||
|
||||
"""
|
||||
schema = await self.schema()
|
||||
data = _serialize_json_values(data, schema)
|
||||
blob_table = _blob_input_to_arrow(data, schema)
|
||||
if blob_table is not None:
|
||||
data = blob_table
|
||||
if on_bad_vectors is None:
|
||||
on_bad_vectors = "error"
|
||||
if fill_value is None:
|
||||
fill_value = 0.0
|
||||
|
||||
# _sanitize_data is an old code path, but we will use it until the
|
||||
# new code path is ready.
|
||||
if mode == "overwrite":
|
||||
# For overwrite, apply the same preprocessing as create_table
|
||||
# so vector columns are inferred as FixedSizeList.
|
||||
data, _ = await asyncio.to_thread(
|
||||
sanitize_create_table,
|
||||
data,
|
||||
None,
|
||||
on_bad_vectors=on_bad_vectors,
|
||||
fill_value=fill_value,
|
||||
overwrite_schema=schema,
|
||||
)
|
||||
if blob_v2_column_paths(schema):
|
||||
# Plain bytes cannot be inferred as blob v2. Keep matching blob
|
||||
# fields while allowing other columns to use the inferred schema.
|
||||
target_schema = _preserve_blob_v2_fields(data.schema, schema)
|
||||
data = _cast_to_target_schema(data, target_schema)
|
||||
elif on_bad_vectors != "error" or (
|
||||
schema.metadata is not None and b"embedding_functions" in schema.metadata
|
||||
):
|
||||
data = await asyncio.to_thread(
|
||||
_sanitize_data,
|
||||
data,
|
||||
schema,
|
||||
metadata=schema.metadata,
|
||||
on_bad_vectors=on_bad_vectors,
|
||||
fill_value=fill_value,
|
||||
allow_subschema=True,
|
||||
)
|
||||
_register_optional_converters()
|
||||
# Converting an iterator peeks at its first item. A synchronous query in
|
||||
# that iterator schedules work on LOOP, so peeking on LOOP's own thread
|
||||
# would deadlock waiting for itself.
|
||||
data = await asyncio.to_thread(to_scannable, data)
|
||||
data = await _prepare_add_data(
|
||||
data, schema, mode or "append", on_bad_vectors, fill_value
|
||||
)
|
||||
progress, owns = _normalize_progress(progress)
|
||||
try:
|
||||
return await self._inner.add(
|
||||
@@ -8743,6 +8781,17 @@ class AsyncTable:
|
||||
if owns:
|
||||
progress.close()
|
||||
|
||||
async def begin_write(self, mode: AddMode = "append") -> AsyncStagedWrite:
|
||||
"""Start a staged append or overwrite.
|
||||
|
||||
See [Table.begin_write][lancedb.table.Table.begin_write].
|
||||
"""
|
||||
return AsyncStagedWrite(await self._inner.begin_write(mode))
|
||||
|
||||
async def open_write(self, write_id: str) -> AsyncStagedWrite:
|
||||
"""Reopen a staged write on its original writable table and branch."""
|
||||
return AsyncStagedWrite(await self._inner.open_write(write_id))
|
||||
|
||||
def merge_insert(self, on: Union[str, Iterable[str]]) -> LanceMergeInsertBuilder:
|
||||
"""
|
||||
Returns a [`LanceMergeInsertBuilder`][lancedb.merge.LanceMergeInsertBuilder]
|
||||
@@ -11243,6 +11292,134 @@ class Branches:
|
||||
return self._parent._wrap_branch_handle(async_table, version)
|
||||
|
||||
|
||||
class StagedWrite:
|
||||
"""A resumable append or overwrite.
|
||||
|
||||
Created by [Table.begin_write][lancedb.table.Table.begin_write].
|
||||
Share the ID with workers that can reopen the same table and branch.
|
||||
Call [commit][lancedb.table.StagedWrite.commit] once the workers finish.
|
||||
Dropping any handle leaves the write available to other processes.
|
||||
"""
|
||||
|
||||
def __init__(self, inner: AsyncStagedWrite):
|
||||
self._async = inner
|
||||
|
||||
@property
|
||||
def id(self) -> str:
|
||||
"""The ID to pass to [Table.open_write][lancedb.table.Table.open_write]."""
|
||||
return self._async.id
|
||||
|
||||
def add(
|
||||
self,
|
||||
data: DATA,
|
||||
*,
|
||||
idempotency_key: Optional[str] = None,
|
||||
on_bad_vectors: OnBadVectorsType = "error",
|
||||
fill_value: float = 0.0,
|
||||
) -> None:
|
||||
"""Stage rows without publishing a version. Empty input is a no-op.
|
||||
|
||||
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.
|
||||
|
||||
Use a nonempty key for each worker task and reuse it for the same
|
||||
data on retry. See [AsyncStagedWrite.add][lancedb.table.AsyncStagedWrite.add]
|
||||
for Enterprise limits.
|
||||
"""
|
||||
LOOP.run(
|
||||
self._async.add(
|
||||
data,
|
||||
idempotency_key=idempotency_key,
|
||||
on_bad_vectors=on_bad_vectors,
|
||||
fill_value=fill_value,
|
||||
)
|
||||
)
|
||||
|
||||
def commit(self) -> AddResult:
|
||||
"""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.
|
||||
"""
|
||||
return LOOP.run(self._async.commit())
|
||||
|
||||
def abort(self) -> None:
|
||||
"""Discard the staged write. Repeating an abort is safe."""
|
||||
LOOP.run(self._async.abort())
|
||||
|
||||
|
||||
class AsyncStagedWrite:
|
||||
"""Async staged write.
|
||||
|
||||
Created by [AsyncTable.begin_write][lancedb.table.AsyncTable.begin_write].
|
||||
"""
|
||||
|
||||
def __init__(self, inner: NativeStagedWrite):
|
||||
self._inner = inner
|
||||
|
||||
@property
|
||||
def id(self) -> str:
|
||||
"""The opaque write ID.
|
||||
|
||||
Pass it to [AsyncTable.open_write][lancedb.table.AsyncTable.open_write].
|
||||
"""
|
||||
return self._inner.id()
|
||||
|
||||
async def add(
|
||||
self,
|
||||
data: DATA,
|
||||
*,
|
||||
idempotency_key: Optional[str] = None,
|
||||
on_bad_vectors: OnBadVectorsType = "error",
|
||||
fill_value: float = 0.0,
|
||||
) -> None:
|
||||
"""Stage rows without publishing a version.
|
||||
|
||||
Uses the preprocessing in [AsyncTable.add][lancedb.table.AsyncTable.add].
|
||||
Empty input is a no-op. A nonempty idempotency key lets you retry
|
||||
one task with the same data, order, and batching. Enterprise also
|
||||
requires consistent request byte limits across workers. If changed
|
||||
input produces fewer Enterprise 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.
|
||||
"""
|
||||
schema = await self._inner.input_schema()
|
||||
if isinstance(data, (list, tuple)) and not data:
|
||||
data = pa.Table.from_batches([], schema=schema)
|
||||
elif isinstance(data, Iterator) and not isinstance(data, pa.RecordBatchReader):
|
||||
end = object()
|
||||
first = await asyncio.to_thread(next, data, end)
|
||||
data = (
|
||||
pa.Table.from_batches([], schema=schema)
|
||||
if first is end
|
||||
else chain((first,), data)
|
||||
)
|
||||
prepared = await _prepare_add_data(
|
||||
data, schema, self._inner.mode(), on_bad_vectors, fill_value
|
||||
)
|
||||
try:
|
||||
await self._inner.add(prepared, idempotency_key)
|
||||
except RuntimeError as e:
|
||||
if "Cast error" in str(e) or "Vector column contains NaN" in str(e):
|
||||
raise ValueError(e)
|
||||
raise
|
||||
|
||||
async def commit(self) -> AddResult:
|
||||
"""Publish the staged data as one table version.
|
||||
|
||||
See [StagedWrite.commit][lancedb.table.StagedWrite.commit].
|
||||
"""
|
||||
return await self._inner.commit()
|
||||
|
||||
async def abort(self) -> None:
|
||||
"""Discard the staged write. Repeating an abort is safe."""
|
||||
await self._inner.abort()
|
||||
|
||||
|
||||
class TableDelta:
|
||||
"""Streaming row changes between two table versions.
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import multiprocessing
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
|
||||
|
||||
def _stage(uri, write_id, row_id):
|
||||
worker = lancedb.connect(uri).open_table("items").open_write(write_id)
|
||||
return worker.add([{"id": row_id}], idempotency_key=f"task-{row_id}")
|
||||
|
||||
|
||||
def _commit(uri, write_id):
|
||||
table = lancedb.connect(uri).open_table("items")
|
||||
return table.open_write(write_id).commit().version
|
||||
|
||||
|
||||
def test_staged_write_resumes_in_spawned_processes(tmp_path):
|
||||
uri = str(tmp_path)
|
||||
table = lancedb.connect(uri).create_table(
|
||||
"items", schema=pa.schema([("id", pa.int64())])
|
||||
)
|
||||
write = table.begin_write()
|
||||
assert isinstance(write, lancedb.StagedWrite)
|
||||
write_id = write.id
|
||||
assert isinstance(write_id, str)
|
||||
del write
|
||||
|
||||
context = multiprocessing.get_context("spawn")
|
||||
with ProcessPoolExecutor(max_workers=2, mp_context=context) as workers:
|
||||
chunks = [workers.submit(_stage, uri, write_id, row_id) for row_id in (1, 2)]
|
||||
assert [chunk.result(timeout=60) for chunk in chunks] == [None, None]
|
||||
assert workers.submit(_stage, uri, write_id, 2).result(timeout=60) is None
|
||||
reader = lancedb.connect(uri).open_table("items")
|
||||
assert reader.version == 1
|
||||
assert reader.count_rows() == 0
|
||||
with ProcessPoolExecutor(max_workers=1, mp_context=context) as coordinator:
|
||||
assert coordinator.submit(_commit, uri, write_id).result(timeout=60) == 2
|
||||
reader.checkout_latest()
|
||||
assert reader.version == 2
|
||||
assert sorted(reader.to_arrow()["id"].to_pylist()) == [1, 2]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_staged_overwrite_uses_add_preprocessing(tmp_path):
|
||||
con = await lancedb.connect_async(tmp_path)
|
||||
table = await con.create_table("items", [{"id": 1}])
|
||||
with pytest.raises(ValueError, match="Invalid mode"):
|
||||
await table.begin_write("replace")
|
||||
write = await table.begin_write(mode="overwrite")
|
||||
assert isinstance(write, lancedb.AsyncStagedWrite)
|
||||
worker = await (await con.open_table("items")).open_write(write.id)
|
||||
|
||||
assert await worker.add([]) is None
|
||||
assert await worker.add(iter([])) is None
|
||||
assert (
|
||||
await worker.add(pa.RecordBatchReader.from_batches(await table.schema(), []))
|
||||
is None
|
||||
)
|
||||
with pytest.raises(ValueError, match="no staged rows"):
|
||||
await write.commit()
|
||||
with pytest.raises(ValueError, match="idempotency_key must be nonempty"):
|
||||
await worker.add([{"vector": [1.0, 2.0]}], idempotency_key="")
|
||||
|
||||
assert (
|
||||
await worker.add([{"vector": [1.0, 2.0]}], idempotency_key="worker-a") is None
|
||||
)
|
||||
assert (await table.schema()).names == ["id"]
|
||||
result = await write.commit()
|
||||
assert result.version == 2
|
||||
assert (await table.schema()).field("vector").type == pa.list_(pa.float32(), 2)
|
||||
assert (await table.query().to_arrow())["vector"].to_pylist() == [[1.0, 2.0]]
|
||||
|
||||
discarded = await table.begin_write()
|
||||
await discarded.add([{"vector": [3.0, 4.0]}])
|
||||
await discarded.abort()
|
||||
assert await discarded.abort() is None
|
||||
assert await table.version() == 2
|
||||
@@ -104,6 +104,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(catalog::connect_catalog, m)?)?;
|
||||
m.add_class::<Session>()?;
|
||||
m.add_class::<Table>()?;
|
||||
m.add_class::<table::StagedWrite>()?;
|
||||
m.add_class::<table::TableDelta>()?;
|
||||
m.add_class::<crate::oauth::PyOAuthSession>()?;
|
||||
m.add_class::<crate::oauth::PySessionStatus>()?;
|
||||
|
||||
+79
-8
@@ -32,7 +32,7 @@ use lancedb::table::{
|
||||
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, DeltaRef, Duration,
|
||||
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig,
|
||||
FunctionRefreshPodResources, IndexRemapMode, NewColumnTransform, Ref, RefreshColumnOptions,
|
||||
Table as LanceDbTable, TableDelta as LanceDbTableDelta,
|
||||
StagedWrite as LanceDbStagedWrite, Table as LanceDbTable, TableDelta as LanceDbTableDelta,
|
||||
};
|
||||
use lancedb::tokenize as lancedb_tokenize;
|
||||
use pyo3::{
|
||||
@@ -1607,6 +1607,23 @@ impl Table {
|
||||
datafusion::table_provider(py, self.inner_ref()?, session)
|
||||
}
|
||||
|
||||
pub fn begin_write<'py>(self_: PyRef<'py, Self>, mode: &str) -> PyResult<Bound<'py, PyAny>> {
|
||||
let table = self_.inner_ref()?.clone();
|
||||
let mode = parse_add_mode(mode)?;
|
||||
future_into_py(self_.py(), async move {
|
||||
let inner = table.begin_write(mode).await.infer_error()?;
|
||||
Ok(StagedWrite { inner })
|
||||
})
|
||||
}
|
||||
|
||||
pub fn open_write(self_: PyRef<'_, Self>, write_id: String) -> PyResult<Bound<'_, PyAny>> {
|
||||
let table = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let inner = table.open_write(write_id).await.infer_error()?;
|
||||
Ok(StagedWrite { inner })
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))]
|
||||
pub fn add<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
@@ -1621,13 +1638,7 @@ impl Table {
|
||||
.inner_ref()?
|
||||
.add(data)
|
||||
.allow_external_blob_outside_bases(allow_external_blob_outside_bases);
|
||||
if mode == "append" {
|
||||
op = op.mode(AddDataMode::Append);
|
||||
} else if mode == "overwrite" {
|
||||
op = op.mode(AddDataMode::Overwrite);
|
||||
} else {
|
||||
return Err(PyValueError::new_err(format!("Invalid mode: {}", mode)));
|
||||
}
|
||||
op = op.mode(parse_add_mode(&mode)?);
|
||||
if let Some(retries) = retries {
|
||||
op = op.retries(retries);
|
||||
}
|
||||
@@ -3388,6 +3399,66 @@ impl From<LanceVersion> for DeltaRef {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_add_mode(mode: &str) -> PyResult<AddDataMode> {
|
||||
match mode {
|
||||
"append" => Ok(AddDataMode::Append),
|
||||
"overwrite" => Ok(AddDataMode::Overwrite),
|
||||
_ => Err(PyValueError::new_err(format!("Invalid mode: {mode}"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[pyclass]
|
||||
pub struct StagedWrite {
|
||||
inner: LanceDbStagedWrite,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl StagedWrite {
|
||||
fn id(&self) -> &str {
|
||||
self.inner.id()
|
||||
}
|
||||
|
||||
fn mode(&self) -> &str {
|
||||
match self.inner.mode() {
|
||||
AddDataMode::Append => "append",
|
||||
AddDataMode::Overwrite => "overwrite",
|
||||
}
|
||||
}
|
||||
|
||||
fn input_schema(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let schema = inner.input_schema().await.infer_error()?;
|
||||
Python::attach(|py| schema.to_pyarrow(py).map(|obj| obj.unbind()))
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (data, idempotency_key=None))]
|
||||
fn add<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
data: PyScannable,
|
||||
idempotency_key: Option<String>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let mut add = self_.inner.add(data);
|
||||
if let Some(key) = idempotency_key {
|
||||
add = add.idempotency_key(key);
|
||||
}
|
||||
future_into_py(self_.py(), async move { add.execute().await.infer_error() })
|
||||
}
|
||||
|
||||
fn commit(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
Ok(AddResult::from(inner.commit().await.infer_error()?))
|
||||
})
|
||||
}
|
||||
|
||||
fn abort(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move { inner.abort().await.infer_error() })
|
||||
}
|
||||
}
|
||||
|
||||
/// Streaming row changes between two table versions.
|
||||
#[pyclass]
|
||||
pub struct TableDelta {
|
||||
|
||||
@@ -23,7 +23,7 @@ arrow-ord = { workspace = true }
|
||||
arrow-cast = { workspace = true }
|
||||
arrow-ipc.workspace = true
|
||||
arrow-flight = { workspace = true, optional = true }
|
||||
prost = { workspace = true, optional = true }
|
||||
prost = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
datafusion-catalog.workspace = true
|
||||
datafusion-common.workspace = true
|
||||
@@ -178,7 +178,6 @@ huggingface = [
|
||||
dynamodb = ["lance/dynamodb", "aws"]
|
||||
remote = [
|
||||
"dep:arrow-flight",
|
||||
"dep:prost",
|
||||
"dep:reqwest",
|
||||
"dep:http",
|
||||
"dep:hyper",
|
||||
|
||||
@@ -38,7 +38,19 @@ trait PrimaryOnly {
|
||||
|
||||
impl PrimaryOnly for Path {
|
||||
fn primary_only(&self) -> bool {
|
||||
self.filename().unwrap_or("") == "_latest.manifest"
|
||||
if self.filename() == Some("_latest.manifest") {
|
||||
return true;
|
||||
}
|
||||
// Staged write state uses conditional creation. A write or failure on
|
||||
// the secondary must not affect ownership of an authoritative slot.
|
||||
let path = self.as_ref();
|
||||
let staged = path
|
||||
.rsplit_once("/data/_transactions/")
|
||||
.map(|(_, staged)| staged)
|
||||
.or_else(|| path.strip_prefix("data/_transactions/"));
|
||||
staged
|
||||
.and_then(|staged| staged.split_once('/'))
|
||||
.is_some_and(|(upload, _)| uuid::Uuid::parse_str(upload).is_ok())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -252,7 +252,7 @@ pub use materialized_view::{
|
||||
/// a built-in pull-based adapter.
|
||||
#[cfg(feature = "metrics")]
|
||||
pub use metrics;
|
||||
pub use table::{FtsToken, Table};
|
||||
pub use table::{FtsToken, StagedAddBuilder, StagedWrite, Table};
|
||||
|
||||
/// Gate local execution without hiding client types or metadata protections.
|
||||
pub(crate) fn require_experimental_functions() -> Result<()> {
|
||||
|
||||
@@ -367,6 +367,7 @@ pub struct RestfulLanceDbClient<S: HttpSend = Sender> {
|
||||
/// never reach object storage.
|
||||
object_store_client: reqwest::Client,
|
||||
host: String,
|
||||
pub(crate) database_prefix: Option<String>,
|
||||
pub(crate) retry_config: ResolvedRetryConfig,
|
||||
pub(crate) blob_request_semaphore: Arc<Semaphore>,
|
||||
pub(crate) object_store_read_parallelism: usize,
|
||||
@@ -655,6 +656,10 @@ impl RestfulLanceDbClient<Sender> {
|
||||
client_builder.danger_accept_invalid_hostnames(!tls_config.assert_hostname);
|
||||
}
|
||||
|
||||
let database_prefix = default_headers
|
||||
.get("x-lancedb-database-prefix")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_owned);
|
||||
let client = client_builder
|
||||
.default_headers(default_headers)
|
||||
.user_agent(client_config.user_agent.clone())
|
||||
@@ -699,6 +704,7 @@ impl RestfulLanceDbClient<Sender> {
|
||||
client,
|
||||
object_store_client,
|
||||
host,
|
||||
database_prefix,
|
||||
retry_config,
|
||||
blob_request_semaphore: Arc::new(Semaphore::new(blob_request_concurrency)),
|
||||
object_store_read_parallelism: std::env::var("LANCE_IO_THREADS")
|
||||
@@ -1370,6 +1376,7 @@ pub mod test_utils {
|
||||
client: reqwest::Client::new(),
|
||||
object_store_client: reqwest::Client::new(),
|
||||
host: "http://localhost".to_string(),
|
||||
database_prefix: None,
|
||||
retry_config: RetryConfig::default().try_into().unwrap(),
|
||||
blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)),
|
||||
object_store_read_parallelism: DEFAULT_BLOB_REQUEST_CONCURRENCY,
|
||||
@@ -1401,6 +1408,7 @@ pub mod test_utils {
|
||||
client: reqwest::Client::new(),
|
||||
object_store_client: reqwest::Client::new(),
|
||||
host: "http://localhost".to_string(),
|
||||
database_prefix: None,
|
||||
retry_config: config.retry_config.try_into().unwrap(),
|
||||
blob_request_semaphore: Arc::new(Semaphore::new(
|
||||
config
|
||||
@@ -2358,6 +2366,7 @@ mod tests {
|
||||
client: reqwest::Client::new(),
|
||||
object_store_client: reqwest::Client::new(),
|
||||
host: "https://example.com".to_string(),
|
||||
database_prefix: None,
|
||||
retry_config: RetryConfig::default().try_into().unwrap(),
|
||||
blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)),
|
||||
object_store_read_parallelism: DEFAULT_BLOB_REQUEST_CONCURRENCY,
|
||||
@@ -2401,6 +2410,7 @@ mod tests {
|
||||
client: reqwest::Client::new(),
|
||||
object_store_client: reqwest::Client::new(),
|
||||
host: "https://example.com".to_string(),
|
||||
database_prefix: None,
|
||||
retry_config: RetryConfig::default().try_into().unwrap(),
|
||||
blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)),
|
||||
object_store_read_parallelism: DEFAULT_BLOB_REQUEST_CONCURRENCY,
|
||||
@@ -2470,6 +2480,7 @@ mod tests {
|
||||
client: reqwest::Client::new(),
|
||||
object_store_client: reqwest::Client::new(),
|
||||
host: "https://example.com".to_string(),
|
||||
database_prefix: None,
|
||||
retry_config: RetryConfig::default().try_into().unwrap(),
|
||||
blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)),
|
||||
object_store_read_parallelism: DEFAULT_BLOB_REQUEST_CONCURRENCY,
|
||||
|
||||
@@ -11,6 +11,8 @@ mod prewarm;
|
||||
mod profile_tests;
|
||||
mod receipt;
|
||||
#[cfg(test)]
|
||||
mod staged_write_tests;
|
||||
#[cfg(test)]
|
||||
mod write_tests;
|
||||
|
||||
use self::insert::{RemoteWriteExec, WriteOp};
|
||||
@@ -64,8 +66,8 @@ use crate::{
|
||||
index::{AutoIndex, Index, IndexBuilder, IndexConfig},
|
||||
query::{AnalyzePlanDistributedMetrics, QueryExecutionOptions},
|
||||
table::{
|
||||
AddDataBuilder, BaseTable, OptimizeAction, OptimizeStats, TableDefinition, UpdateBuilder,
|
||||
merge::MergeInsertBuilder,
|
||||
AddDataBuilder, AddDataMode, BaseTable, OptimizeAction, OptimizeStats, StagedWriteId,
|
||||
TableDefinition, UpdateBuilder, merge::MergeInsertBuilder,
|
||||
},
|
||||
};
|
||||
use arrow_array::{LargeBinaryArray, RecordBatch, RecordBatchReader};
|
||||
@@ -1816,6 +1818,29 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
Ok(bodies)
|
||||
}
|
||||
|
||||
async fn check_staged_write_available(&self) -> Result<()> {
|
||||
self.check_mutable().await?;
|
||||
if !self.server_version.support_multipart_write() {
|
||||
return Err(Error::NotSupported {
|
||||
message: "staged writes require multipart write support on LanceDB Enterprise"
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn staged_write_scope(&self) -> uuid::Uuid {
|
||||
let address = serde_json::json!([
|
||||
self.client.host(),
|
||||
self.db_name,
|
||||
self.client.database_prefix,
|
||||
self.namespace,
|
||||
self.name,
|
||||
self.branch,
|
||||
]);
|
||||
uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, address.to_string().as_bytes())
|
||||
}
|
||||
|
||||
async fn create_multipart_write(&self, retries: Option<u8>) -> Result<String> {
|
||||
let request = self.apply_branch_query(self.client.post(&format!(
|
||||
"/v1/table/{}/multipart_write/create",
|
||||
@@ -2492,6 +2517,36 @@ impl std::error::Error for UnknownWriteOutcome {
|
||||
}
|
||||
}
|
||||
|
||||
fn multipart_outcome_error(upload_id: &str, err: Error) -> Error {
|
||||
let (request_id, status_code) = match &err {
|
||||
Error::Http {
|
||||
request_id,
|
||||
status_code,
|
||||
..
|
||||
}
|
||||
| Error::Retry {
|
||||
request_id,
|
||||
status_code,
|
||||
..
|
||||
} => (request_id.clone(), *status_code),
|
||||
_ => return err,
|
||||
};
|
||||
if status_code.is_some_and(|status| !status.is_server_error()) {
|
||||
return err;
|
||||
}
|
||||
log::warn!(
|
||||
"Multipart write {upload_id} completion failed; commit outcome may be unknown: {err}. Check the table before retrying."
|
||||
);
|
||||
Error::Http {
|
||||
request_id,
|
||||
status_code,
|
||||
source: Box::new(UnknownWriteOutcome {
|
||||
upload_id: upload_id.to_owned(),
|
||||
source: err,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: HttpSend + 'static> RemoteTable<S> {
|
||||
fn is_retryable_write_error(&self, err: &Error) -> bool {
|
||||
// Transaction conflicts and explicit rate limits reject the write.
|
||||
@@ -2633,17 +2688,10 @@ impl<S: HttpSend + 'static> RemoteTable<S> {
|
||||
let result = match self.complete_multipart_write(&upload_id).await {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
let (request_id, status_code) = match &err {
|
||||
Error::Http {
|
||||
request_id,
|
||||
status_code,
|
||||
..
|
||||
let status_code = match &err {
|
||||
Error::Http { status_code, .. } | Error::Retry { status_code, .. } => {
|
||||
*status_code
|
||||
}
|
||||
| Error::Retry {
|
||||
request_id,
|
||||
status_code,
|
||||
..
|
||||
} => (request_id.clone(), *status_code),
|
||||
_ => return Err(err),
|
||||
};
|
||||
// These responses positively reject the commit. Cleanup remains
|
||||
@@ -2663,22 +2711,7 @@ impl<S: HttpSend + 'static> RemoteTable<S> {
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
if status_code.is_some_and(|status| !status.is_server_error()) {
|
||||
return Err(err);
|
||||
}
|
||||
log::warn!(
|
||||
"Multipart write {} completion failed; commit outcome may be unknown: {}. Check the table before retrying.",
|
||||
upload_id,
|
||||
err
|
||||
);
|
||||
return Err(Error::Http {
|
||||
request_id,
|
||||
status_code,
|
||||
source: Box::new(UnknownWriteOutcome {
|
||||
upload_id,
|
||||
source: err,
|
||||
}),
|
||||
});
|
||||
return Err(multipart_outcome_error(&upload_id, err));
|
||||
}
|
||||
};
|
||||
if output.overwrite {
|
||||
@@ -3697,6 +3730,78 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
status_code: None,
|
||||
})
|
||||
}
|
||||
async fn begin_staged_write(&self, mode: AddDataMode) -> Result<StagedWriteId> {
|
||||
self.check_staged_write_available().await?;
|
||||
let upload = self.create_multipart_write(None).await?;
|
||||
let upload = uuid::Uuid::parse_str(&upload).map_err(|error| Error::Runtime {
|
||||
message: format!("invalid upload ID returned by LanceDB Enterprise: {error}"),
|
||||
})?;
|
||||
Ok(StagedWriteId {
|
||||
upload,
|
||||
mode,
|
||||
enterprise_scope: Some(self.staged_write_scope()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn open_staged_write(&self, id: &StagedWriteId) -> Result<()> {
|
||||
self.check_staged_write_available().await?;
|
||||
id.validate_scope(Some(self.staged_write_scope()))
|
||||
}
|
||||
|
||||
async fn staged_write_schema(&self, id: &StagedWriteId) -> Result<SchemaRef> {
|
||||
self.open_staged_write(id).await?;
|
||||
self.schema().await
|
||||
}
|
||||
|
||||
async fn stage_add(
|
||||
&self,
|
||||
id: &StagedWriteId,
|
||||
add: AddDataBuilder,
|
||||
key: uuid::Uuid,
|
||||
) -> Result<()> {
|
||||
self.open_staged_write(id).await?;
|
||||
if add.data.num_rows() == Some(0) {
|
||||
return Ok(());
|
||||
}
|
||||
let table_schema = self.schema().await?;
|
||||
crate::table::computed_columns::ensure_supported_function_metadata(&table_schema)?;
|
||||
let table_def = TableDefinition::try_from_rich_schema(table_schema.clone())?;
|
||||
let output = add.into_plan(&table_schema, &table_def)?;
|
||||
let result = self.send_staged_parts(id.upload, output, key).await;
|
||||
if let Err(error) = &result {
|
||||
self.handle_error_invalidation(error);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn commit_staged_write(&self, id: &StagedWriteId) -> Result<AddResult> {
|
||||
self.open_staged_write(id).await?;
|
||||
let upload_id = id.upload.to_string();
|
||||
let freshness = self.snapshot_freshness_headers();
|
||||
// Completion is sent once. In particular, a timeout or 5xx can occur
|
||||
// after the manifest was published. Only the caller can reconcile it.
|
||||
let result = self
|
||||
.complete_multipart_write(&upload_id)
|
||||
.await
|
||||
.map_err(|error| multipart_outcome_error(&upload_id, error));
|
||||
if matches!(id.mode, AddDataMode::Overwrite)
|
||||
&& (result.is_ok()
|
||||
|| matches!(&result, Err(Error::Http { source, .. })
|
||||
if source.downcast_ref::<UnknownWriteOutcome>().is_some()))
|
||||
{
|
||||
self.invalidate_schema_cache();
|
||||
}
|
||||
let result = result?;
|
||||
self.track_write_version(freshness, result.version);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn abort_staged_write(&self, id: &StagedWriteId) -> Result<()> {
|
||||
self.open_staged_write(id).await?;
|
||||
self.abort_multipart_write(&id.upload.to_string(), None)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn add(&self, mut add: AddDataBuilder) -> Result<AddResult> {
|
||||
self.check_mutable().await?;
|
||||
ensure_remote_add_supports_write_params(add.write_options.lance_write_params.as_ref())?;
|
||||
|
||||
@@ -17,9 +17,10 @@ use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
|
||||
use datafusion_physical_plan::{
|
||||
DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties,
|
||||
};
|
||||
use futures::StreamExt;
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
use http::header::CONTENT_TYPE;
|
||||
use lance::io::exec::utils::InstrumentedRecordBatchStreamAdapter;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::Error;
|
||||
use crate::remote::ARROW_STREAM_CONTENT_TYPE;
|
||||
@@ -30,7 +31,7 @@ use crate::remote::table::{
|
||||
};
|
||||
use crate::table::datafusion::insert::COUNT_SCHEMA;
|
||||
use crate::table::write_progress::WriteProgressTracker;
|
||||
use crate::table::{AddResult, MergeResult};
|
||||
use crate::table::{AddResult, MergeResult, PreprocessingOutput};
|
||||
|
||||
/// The write operation a [`RemoteWriteExec`] performs. Both variants share the
|
||||
/// same Arrow-IPC streaming body and error side-channel; only the target
|
||||
@@ -351,6 +352,59 @@ struct PartRequestCtx<'a, S: HttpSend> {
|
||||
upload_id: &'a str,
|
||||
branch: Option<&'a str>,
|
||||
overwrite: bool,
|
||||
part_namespace: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl<S: HttpSend> RemoteTable<S> {
|
||||
pub(super) async fn send_staged_parts(
|
||||
&self,
|
||||
upload: Uuid,
|
||||
output: PreprocessingOutput,
|
||||
part_namespace: Uuid,
|
||||
) -> crate::Result<()> {
|
||||
let input =
|
||||
datafusion_physical_plan::execute_stream(output.plan.clone(), Default::default())?;
|
||||
let schema = input.schema();
|
||||
let mut nonempty = input.try_filter(|batch| futures::future::ready(batch.num_rows() != 0));
|
||||
// Enterprise multipart overwrite drops the top-level metadata map.
|
||||
// Check for rows first to preserve the no-op for an empty worker stream.
|
||||
if output.overwrite && !schema.metadata().is_empty() {
|
||||
return match nonempty.try_next().await? {
|
||||
Some(_) => Err(Error::NotSupported {
|
||||
message: "staged overwrites on LanceDB Enterprise require an empty top-level schema metadata map".into(),
|
||||
}),
|
||||
None => Ok(()),
|
||||
};
|
||||
}
|
||||
let input = Box::pin(RecordBatchStreamAdapter::new(schema, nonempty));
|
||||
let client = self.client.with_retries(output.retries);
|
||||
let freshness = WriteFreshness {
|
||||
state: Some(self.freshness.clone()),
|
||||
read_consistency_interval: self.client.read_consistency_interval,
|
||||
};
|
||||
let upload_id = upload.to_string();
|
||||
let context = PartRequestCtx {
|
||||
client: &client,
|
||||
freshness: &freshness,
|
||||
identifier: &self.identifier,
|
||||
table_name: &self.name,
|
||||
upload_id: &upload_id,
|
||||
branch: self.branch.as_deref(),
|
||||
overwrite: output.overwrite,
|
||||
part_namespace: Some(part_namespace),
|
||||
};
|
||||
// The preprocessing plan has one partition. Use bytes alone to cut
|
||||
// parts so a worker retry chooses the same parts regardless of timing.
|
||||
context
|
||||
.send_multipart_chunked(
|
||||
client.max_bytes_per_request().unwrap_or(u64::MAX),
|
||||
None,
|
||||
input,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: HttpSend + 'static> PartRequestCtx<'_, S> {
|
||||
@@ -386,19 +440,23 @@ impl<S: HttpSend + 'static> PartRequestCtx<'_, S> {
|
||||
Box::pin(RecordBatchStreamAdapter::new(schema.clone(), stream));
|
||||
|
||||
let mut pending = std::collections::VecDeque::new();
|
||||
let mut chunk = 0_u64;
|
||||
loop {
|
||||
let first = match pending.pop_front() {
|
||||
Some(batch) => batch,
|
||||
None => match input.next().await {
|
||||
Some(batch) => batch?,
|
||||
if pending.is_empty() {
|
||||
match input.next().await {
|
||||
Some(batch) => pending.push_front(batch?),
|
||||
None => break,
|
||||
},
|
||||
}
|
||||
}
|
||||
let part_id = match self.part_namespace {
|
||||
Some(namespace) => Uuid::new_v5(&namespace, &chunk.to_be_bytes()),
|
||||
None => Uuid::new_v4(),
|
||||
};
|
||||
if self
|
||||
.send_one_part(
|
||||
max_bytes,
|
||||
max_duration,
|
||||
first,
|
||||
part_id.to_string(),
|
||||
&mut input,
|
||||
&mut pending,
|
||||
&tracker,
|
||||
@@ -407,6 +465,7 @@ impl<S: HttpSend + 'static> PartRequestCtx<'_, S> {
|
||||
{
|
||||
break;
|
||||
}
|
||||
chunk += 1;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -464,7 +523,7 @@ impl<S: HttpSend + 'static> PartRequestCtx<'_, S> {
|
||||
&self,
|
||||
max_bytes: u64,
|
||||
max_duration: Option<Duration>,
|
||||
first: RecordBatch,
|
||||
part_id: String,
|
||||
input: &mut SendableRecordBatchStream,
|
||||
queued: &mut std::collections::VecDeque<RecordBatch>,
|
||||
tracker: &Option<Arc<WriteProgressTracker>>,
|
||||
@@ -478,12 +537,11 @@ impl<S: HttpSend + 'static> PartRequestCtx<'_, S> {
|
||||
options.clone(),
|
||||
)?;
|
||||
let started = Instant::now();
|
||||
let mut pending = Some(first);
|
||||
let mut has_batch = false;
|
||||
let mut part_rows = 0;
|
||||
let mut input_ended = false;
|
||||
loop {
|
||||
let batch = match pending.take().or_else(|| queued.pop_front()) {
|
||||
let batch = match queued.pop_front() {
|
||||
Some(batch) => batch,
|
||||
None => match input.next().await {
|
||||
Some(batch) => batch?,
|
||||
@@ -508,7 +566,7 @@ impl<S: HttpSend + 'static> PartRequestCtx<'_, S> {
|
||||
queued.push_front(crate::remote::util::compact_batch_dictionaries(
|
||||
batch.slice(middle, batch.num_rows() - middle),
|
||||
)?);
|
||||
pending = Some(crate::remote::util::compact_batch_dictionaries(
|
||||
queued.push_front(crate::remote::util::compact_batch_dictionaries(
|
||||
batch.slice(0, middle),
|
||||
)?);
|
||||
writer = arrow_ipc::writer::StreamWriter::try_new_with_options(
|
||||
@@ -530,7 +588,6 @@ impl<S: HttpSend + 'static> PartRequestCtx<'_, S> {
|
||||
}
|
||||
writer.finish()?;
|
||||
let body = bytes::Bytes::from(writer.into_inner()?);
|
||||
let part_id = uuid::Uuid::new_v4().to_string();
|
||||
let mut retries =
|
||||
crate::remote::retry::RetryCounter::new(&self.client.retry_config, part_id.clone());
|
||||
loop {
|
||||
@@ -717,6 +774,7 @@ impl<S: HttpSend + 'static> ExecutionPlan for RemoteWriteExec<S> {
|
||||
upload_id,
|
||||
branch: branch.as_deref(),
|
||||
overwrite,
|
||||
part_namespace: None,
|
||||
};
|
||||
ctx.send_multipart_chunked(max_bytes, max_request_duration, input_stream, tracker)
|
||||
.await?;
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::Cursor;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use arrow_array::{RecordBatch, record_batch};
|
||||
use arrow_ipc::reader::StreamReader;
|
||||
use arrow_schema::Schema;
|
||||
use futures::stream;
|
||||
use lance::dataset::refs::Ref;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::arrow::{SendableRecordBatchStream, SimpleRecordBatchStream};
|
||||
use crate::remote::ClientConfig;
|
||||
use crate::table::AddDataMode;
|
||||
use crate::{Error, Table};
|
||||
|
||||
use super::UnknownWriteOutcome;
|
||||
|
||||
const UPLOAD: &str = "21889f67-0b51-47a4-973e-c051957ac650";
|
||||
|
||||
fn response(status: u16, body: impl Into<String>) -> http::Response<String> {
|
||||
http::Response::builder()
|
||||
.status(status)
|
||||
.body(body.into())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn describe() -> http::Response<String> {
|
||||
response(
|
||||
200,
|
||||
r#"{"version":1,"schema":{"fields":[{"name":"id","type":{"type":"int32"},"nullable":true}]}}"#,
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Upload {
|
||||
creates: usize,
|
||||
completes: usize,
|
||||
aborts: usize,
|
||||
fail_worker: bool,
|
||||
requests: Vec<(Uuid, Vec<u8>)>,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_staging_reuses_enterprise_multipart_and_replays_only_matching_parts() {
|
||||
let upload = Arc::new(Mutex::new(Upload::default()));
|
||||
let server = upload.clone();
|
||||
let handler = move |request: reqwest::Request| {
|
||||
let params: HashMap<_, _> = request.url().query_pairs().into_owned().collect();
|
||||
let mut upload = server.lock().unwrap();
|
||||
match request.url().path() {
|
||||
"/v1/table/items/branches/create/" => response(200, "{}"),
|
||||
"/v1/table/items/branches/list/" => response(
|
||||
200,
|
||||
r#"{"branches":{"dev":{"parentBranch":null,"parentVersion":1,"createAt":1,"manifestSize":1}}}"#,
|
||||
),
|
||||
"/v1/table/items/describe/" => describe(),
|
||||
"/v1/table/items/multipart_write/create" => {
|
||||
assert_eq!(params["branch"], "dev");
|
||||
assert!(!params.contains_key("mode"));
|
||||
upload.creates += 1;
|
||||
response(200, format!(r#"{{"upload_id":"{UPLOAD}"}}"#))
|
||||
}
|
||||
"/v1/table/items/insert/" => {
|
||||
assert_eq!(params["branch"], "dev");
|
||||
assert_eq!(params["upload_id"], UPLOAD);
|
||||
assert_eq!(params["mode"], "overwrite");
|
||||
assert_eq!(
|
||||
request.headers()["content-type"],
|
||||
crate::remote::ARROW_STREAM_CONTENT_TYPE
|
||||
);
|
||||
if upload.fail_worker {
|
||||
return response(400, "worker rejected");
|
||||
}
|
||||
let part = params["upload_part_id"].parse::<Uuid>().unwrap();
|
||||
let body = request.body().unwrap().as_bytes().unwrap().to_vec();
|
||||
upload.requests.push((part, body));
|
||||
response(200, "{}")
|
||||
}
|
||||
"/v1/table/items/multipart_write/complete" => {
|
||||
assert_eq!(params["branch"], "dev");
|
||||
assert_eq!(params["upload_id"], UPLOAD);
|
||||
upload.completes += 1;
|
||||
response(200, r#"{"version":17}"#)
|
||||
}
|
||||
"/v1/table/items/multipart_write/abort" => {
|
||||
assert_eq!(params["branch"], "dev");
|
||||
assert_eq!(params["upload_id"], UPLOAD);
|
||||
upload.aborts += 1;
|
||||
response(200, "")
|
||||
}
|
||||
path => panic!("unexpected staged write request: {path}"),
|
||||
}
|
||||
};
|
||||
let table = Table::new_with_handler_version_and_config(
|
||||
"items",
|
||||
semver::Version::new(0, 4, 0),
|
||||
handler,
|
||||
ClientConfig {
|
||||
max_bytes_per_request: Some(2048),
|
||||
max_request_duration: Some(Duration::from_nanos(1)),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let branch = table
|
||||
.create_branch("dev", Ref::Version(None, None))
|
||||
.await
|
||||
.unwrap();
|
||||
let write = branch.begin_write(AddDataMode::Overwrite).await.unwrap();
|
||||
assert!(
|
||||
table
|
||||
.open_write(write.id())
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("different table or branch")
|
||||
);
|
||||
assert!(branch.open_write("not-an-id").await.is_err());
|
||||
let worker_table = table.checkout_branch("dev", None).await.unwrap();
|
||||
let worker = worker_table.open_write(write.id()).await.unwrap();
|
||||
let batch = record_batch!(("id", Int32, [1, 2, 3])).unwrap();
|
||||
worker
|
||||
.add(RecordBatch::new_empty(batch.schema()))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
worker
|
||||
.add(vec![batch.clone(), batch.clone()])
|
||||
.idempotency_key("small")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let small = std::mem::take(&mut upload.lock().unwrap().requests);
|
||||
// Both batches fit, regardless of the client's one-nanosecond time limit.
|
||||
assert_eq!(small.len(), 1);
|
||||
let reader = StreamReader::try_new(Cursor::new(&small[0].1), None).unwrap();
|
||||
assert_eq!(
|
||||
reader.map(|batch| batch.unwrap().num_rows()).sum::<usize>(),
|
||||
6
|
||||
);
|
||||
|
||||
let batch = record_batch!(("id", Int32, (0..4096).collect::<Vec<_>>())).unwrap();
|
||||
worker
|
||||
.add(batch.clone())
|
||||
.idempotency_key("large")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let attempt = std::mem::take(&mut upload.lock().unwrap().requests);
|
||||
assert!(attempt.len() > 1);
|
||||
for (index, (id, _)) in attempt.iter().enumerate() {
|
||||
let upload = Uuid::parse_str(UPLOAD).unwrap();
|
||||
let task = Uuid::new_v5(&upload, b"large");
|
||||
assert_eq!(*id, Uuid::new_v5(&task, &(index as u64).to_be_bytes()));
|
||||
}
|
||||
let retry = branch.open_write(write.id()).await.unwrap();
|
||||
retry
|
||||
.add(batch.clone())
|
||||
.idempotency_key("large")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(upload.lock().unwrap().requests, attempt);
|
||||
|
||||
upload.lock().unwrap().fail_worker = true;
|
||||
let error = worker
|
||||
.add(batch)
|
||||
.idempotency_key("failed")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("worker rejected"), "{error}");
|
||||
{
|
||||
let upload = upload.lock().unwrap();
|
||||
assert_eq!((upload.creates, upload.completes, upload.aborts), (1, 0, 0));
|
||||
}
|
||||
assert_eq!(retry.commit().await.unwrap().version, 17);
|
||||
let discarded = branch.begin_write(AddDataMode::Append).await.unwrap();
|
||||
discarded.abort().await.unwrap();
|
||||
discarded.abort().await.unwrap();
|
||||
let upload = upload.lock().unwrap();
|
||||
assert_eq!((upload.creates, upload.completes, upload.aborts), (2, 1, 2));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_enterprise_overwrite_rejects_schema_metadata_before_upload() {
|
||||
let inserts = Arc::new(Mutex::new(Vec::new()));
|
||||
let server = inserts.clone();
|
||||
let table =
|
||||
Table::new_with_handler_version("items", semver::Version::new(0, 4, 0), move |request| {
|
||||
match request.url().path() {
|
||||
"/v1/table/items/describe/" => describe(),
|
||||
"/v1/table/items/multipart_write/create" => {
|
||||
response(200, format!(r#"{{"upload_id":"{UPLOAD}"}}"#))
|
||||
}
|
||||
"/v1/table/items/insert/" => {
|
||||
let body = request.body().unwrap().as_bytes().unwrap();
|
||||
let reader = StreamReader::try_new(Cursor::new(body), None).unwrap();
|
||||
server.lock().unwrap().push(reader.schema());
|
||||
response(200, "{}")
|
||||
}
|
||||
path => panic!("unexpected staged write request: {path}"),
|
||||
}
|
||||
});
|
||||
let write = table.begin_write(AddDataMode::Overwrite).await.unwrap();
|
||||
let row = record_batch!(("id", Int32, [1])).unwrap();
|
||||
let field = row
|
||||
.schema()
|
||||
.field(0)
|
||||
.clone()
|
||||
.with_metadata(HashMap::from([("label".into(), "retained".into())]));
|
||||
let field_only = Arc::new(Schema::new(vec![field]));
|
||||
let annotated = Arc::new(
|
||||
field_only
|
||||
.as_ref()
|
||||
.clone()
|
||||
.with_metadata(HashMap::from([("application".into(), "keep-me".into())])),
|
||||
);
|
||||
let empty = RecordBatch::new_empty(annotated.clone());
|
||||
write.add(empty.clone()).execute().await.unwrap();
|
||||
let empty_stream: SendableRecordBatchStream = Box::pin(SimpleRecordBatchStream::new(
|
||||
stream::iter([Ok(empty.clone())]),
|
||||
annotated.clone(),
|
||||
));
|
||||
write.add(empty_stream).execute().await.unwrap();
|
||||
|
||||
let annotated_row = RecordBatch::try_new(annotated.clone(), row.columns().to_vec()).unwrap();
|
||||
let nonempty_stream: SendableRecordBatchStream = Box::pin(SimpleRecordBatchStream::new(
|
||||
stream::iter([Ok(empty), Ok(annotated_row)]),
|
||||
annotated,
|
||||
));
|
||||
let error = write.add(nonempty_stream).execute().await.unwrap_err();
|
||||
assert!(matches!(&error, Error::NotSupported { .. }), "{error}");
|
||||
assert!(
|
||||
error.to_string().contains("top-level schema metadata"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(inserts.lock().unwrap().is_empty());
|
||||
|
||||
let acceptable = RecordBatch::try_new(field_only.clone(), row.columns().to_vec()).unwrap();
|
||||
write.add(acceptable).execute().await.unwrap();
|
||||
assert_eq!(inserts.lock().unwrap().as_slice(), &[field_only]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_enterprise_completion_preserves_unknown_outcome_and_is_not_retried() {
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let server = requests.clone();
|
||||
let table =
|
||||
Table::new_with_handler_version("items", semver::Version::new(0, 4, 0), move |request| {
|
||||
server.lock().unwrap().push(request.url().path().to_owned());
|
||||
match request.url().path() {
|
||||
"/v1/table/items/multipart_write/create" => {
|
||||
response(200, format!(r#"{{"upload_id":"{UPLOAD}"}}"#))
|
||||
}
|
||||
"/v1/table/items/multipart_write/complete" => response(504, "outcome unknown"),
|
||||
path => panic!("unexpected request after unknown completion: {path}"),
|
||||
}
|
||||
});
|
||||
let write = table.begin_write(AddDataMode::Append).await.unwrap();
|
||||
let err = write.commit().await.unwrap_err();
|
||||
match err {
|
||||
Error::Http {
|
||||
source,
|
||||
status_code: Some(status),
|
||||
request_id,
|
||||
} => {
|
||||
assert_eq!(status, reqwest::StatusCode::GATEWAY_TIMEOUT);
|
||||
assert!(!request_id.is_empty());
|
||||
assert!(source.downcast_ref::<UnknownWriteOutcome>().is_some());
|
||||
}
|
||||
other => panic!("expected unknown completion: {other:?}"),
|
||||
}
|
||||
assert_eq!(
|
||||
requests.lock().unwrap().as_slice(),
|
||||
[
|
||||
"/v1/table/items/multipart_write/create",
|
||||
"/v1/table/items/multipart_write/complete",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_enterprise_staging_requires_support_and_rejects_pinned_handles() {
|
||||
let unsupported = Table::new_with_handler_version(
|
||||
"items",
|
||||
semver::Version::new(0, 3, 0),
|
||||
|request: reqwest::Request| -> http::Response<String> {
|
||||
panic!("unsupported server got {request:?}")
|
||||
},
|
||||
);
|
||||
assert!(matches!(
|
||||
unsupported.begin_write(AddDataMode::Append).await,
|
||||
Err(Error::NotSupported { .. })
|
||||
));
|
||||
|
||||
let table =
|
||||
Table::new_with_handler_version("items", semver::Version::new(0, 4, 0), |request| {
|
||||
match request.url().path() {
|
||||
"/v1/table/items/describe/" => describe(),
|
||||
"/v1/table/items/multipart_write/create" => {
|
||||
response(200, format!(r#"{{"upload_id":"{UPLOAD}"}}"#))
|
||||
}
|
||||
path => panic!("pinned table attempted {path}"),
|
||||
}
|
||||
});
|
||||
let write = table.begin_write(AddDataMode::Append).await.unwrap();
|
||||
table.checkout(1).await.unwrap();
|
||||
let data = record_batch!(("id", Int32, [5])).unwrap();
|
||||
for error in [
|
||||
table.begin_write(AddDataMode::Append).await.unwrap_err(),
|
||||
table.open_write(write.id()).await.unwrap_err(),
|
||||
write.add(data).execute().await.unwrap_err(),
|
||||
write.commit().await.unwrap_err(),
|
||||
write.abort().await.unwrap_err(),
|
||||
] {
|
||||
assert!(error.to_string().contains("fixed at version 1"), "{error}");
|
||||
}
|
||||
}
|
||||
+130
-8
@@ -90,6 +90,7 @@ pub mod freshness;
|
||||
pub mod function_column_status;
|
||||
pub mod merge;
|
||||
pub mod optimize;
|
||||
mod staged_write;
|
||||
pub use optimize::CompactionResult;
|
||||
mod cleanup;
|
||||
pub use cleanup::{CleanupOptions, CleanupPlan, CleanupResult};
|
||||
@@ -140,6 +141,9 @@ pub use schema_evolution::{
|
||||
UpdateFieldMetadataResult,
|
||||
};
|
||||
use serde_with::skip_serializing_none;
|
||||
#[doc(hidden)]
|
||||
pub use staged_write::StagedWriteId;
|
||||
pub use staged_write::{StagedAddBuilder, StagedWrite};
|
||||
pub use update::{UpdateBuilder, UpdateResult};
|
||||
|
||||
/// Walk a boxed error chain to find the innermost `NamespaceError`.
|
||||
@@ -693,6 +697,35 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
|
||||
|
||||
/// Add new records to the table.
|
||||
async fn add(&self, add: AddDataBuilder) -> Result<AddResult>;
|
||||
#[doc(hidden)]
|
||||
async fn begin_staged_write(&self, _mode: AddDataMode) -> Result<StagedWriteId> {
|
||||
Err(staged_write::unsupported())
|
||||
}
|
||||
#[doc(hidden)]
|
||||
async fn open_staged_write(&self, _id: &StagedWriteId) -> Result<()> {
|
||||
Err(staged_write::unsupported())
|
||||
}
|
||||
#[doc(hidden)]
|
||||
async fn staged_write_schema(&self, _id: &StagedWriteId) -> Result<SchemaRef> {
|
||||
Err(staged_write::unsupported())
|
||||
}
|
||||
#[doc(hidden)]
|
||||
async fn stage_add(
|
||||
&self,
|
||||
_id: &StagedWriteId,
|
||||
_add: AddDataBuilder,
|
||||
_key: uuid::Uuid,
|
||||
) -> Result<()> {
|
||||
Err(staged_write::unsupported())
|
||||
}
|
||||
#[doc(hidden)]
|
||||
async fn commit_staged_write(&self, _id: &StagedWriteId) -> Result<AddResult> {
|
||||
Err(staged_write::unsupported())
|
||||
}
|
||||
#[doc(hidden)]
|
||||
async fn abort_staged_write(&self, _id: &StagedWriteId) -> Result<()> {
|
||||
Err(staged_write::unsupported())
|
||||
}
|
||||
/// Delete rows from the table matching the given [`Predicate`].
|
||||
async fn delete(&self, predicate: Predicate<'_>) -> Result<DeleteResult>;
|
||||
/// Update rows in the table.
|
||||
@@ -1769,6 +1802,44 @@ impl Table {
|
||||
)
|
||||
}
|
||||
|
||||
/// Begin a write that publishes only when [`StagedWrite::commit`] is called.
|
||||
///
|
||||
/// Workers and the committing process can open the same table and branch
|
||||
/// and use the returned ID. The table must be writable. Enterprise requires
|
||||
/// a server with multipart write support.
|
||||
///
|
||||
/// ```
|
||||
/// use lancedb::{Table, table::AddDataMode};
|
||||
///
|
||||
/// # async fn example(table: &Table, worker_table: &Table) -> lancedb::Result<()> {
|
||||
/// let write = table.begin_write(AddDataMode::Append).await?;
|
||||
/// let worker = worker_table.open_write(write.id()).await?;
|
||||
/// let batch = arrow_array::record_batch!(("id", Int32, [1, 2, 3])).unwrap();
|
||||
/// worker.add(batch).idempotency_key("task-1").execute().await?;
|
||||
/// let version = write.commit().await?.version;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn begin_write(&self, mode: AddDataMode) -> Result<StagedWrite> {
|
||||
let id = self.inner.begin_staged_write(mode).await?;
|
||||
Ok(StagedWrite::new(
|
||||
id,
|
||||
self.inner.clone(),
|
||||
self.embedding_registry.clone(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Reopen a staged write on its original writable table and branch.
|
||||
pub async fn open_write(&self, write_id: impl AsRef<str>) -> Result<StagedWrite> {
|
||||
let id = write_id.as_ref().parse()?;
|
||||
self.inner.open_staged_write(&id).await?;
|
||||
Ok(StagedWrite::new(
|
||||
id,
|
||||
self.inner.clone(),
|
||||
self.embedding_registry.clone(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Update existing records in the Table
|
||||
///
|
||||
/// An update operation can be used to adjust existing values. Use the
|
||||
@@ -4519,6 +4590,22 @@ impl NativeTable {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_embedded_add(table_schema: &Schema, add: &AddDataBuilder) -> Result<()> {
|
||||
computed_columns::ensure_supported_function_metadata(table_schema)?;
|
||||
let input_schema = add.data.schema();
|
||||
computed_columns::ensure_not_written(
|
||||
table_schema,
|
||||
input_schema
|
||||
.fields()
|
||||
.iter()
|
||||
.map(|field| field.name().as_str()),
|
||||
)?;
|
||||
if matches!(add.mode, AddDataMode::Overwrite) {
|
||||
computed_columns::ensure_no_foreign_declarations(input_schema.fields())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl BaseTable for NativeTable {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
@@ -4718,6 +4805,48 @@ impl BaseTable for NativeTable {
|
||||
}
|
||||
}
|
||||
|
||||
async fn begin_staged_write(&self, mode: AddDataMode) -> Result<StagedWriteId> {
|
||||
staged_write::native::NativeStagedWrite::begin(self, mode).await
|
||||
}
|
||||
|
||||
async fn open_staged_write(&self, id: &StagedWriteId) -> Result<()> {
|
||||
staged_write::native::NativeStagedWrite::open(self, id).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn staged_write_schema(&self, id: &StagedWriteId) -> Result<SchemaRef> {
|
||||
staged_write::native::NativeStagedWrite::open(self, id)
|
||||
.await?
|
||||
.schema()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn stage_add(
|
||||
&self,
|
||||
id: &StagedWriteId,
|
||||
add: AddDataBuilder,
|
||||
key: uuid::Uuid,
|
||||
) -> Result<()> {
|
||||
staged_write::native::NativeStagedWrite::open(self, id)
|
||||
.await?
|
||||
.add(self, add, key)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn commit_staged_write(&self, id: &StagedWriteId) -> Result<AddResult> {
|
||||
staged_write::native::NativeStagedWrite::open(self, id)
|
||||
.await?
|
||||
.commit(self)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn abort_staged_write(&self, id: &StagedWriteId) -> Result<()> {
|
||||
staged_write::native::NativeStagedWrite::open(self, id)
|
||||
.await?
|
||||
.abort()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn add(&self, mut add: AddDataBuilder) -> Result<AddResult> {
|
||||
let table_def = self.table_definition().await?;
|
||||
|
||||
@@ -4727,14 +4856,7 @@ impl BaseTable for NativeTable {
|
||||
crate::materialized_view::ensure_not_a_view(&self.name, &ds.schema().metadata, "add to")?;
|
||||
|
||||
let table_schema = Schema::from(&ds.schema().clone());
|
||||
computed_columns::ensure_supported_function_metadata(&table_schema)?;
|
||||
computed_columns::ensure_not_written(
|
||||
&table_schema,
|
||||
add.data.schema().fields().iter().map(|f| f.name().as_str()),
|
||||
)?;
|
||||
if matches!(add.mode, AddDataMode::Overwrite) {
|
||||
computed_columns::ensure_no_foreign_declarations(add.data.schema().fields())?;
|
||||
}
|
||||
validate_embedded_add(&table_schema, &add)?;
|
||||
|
||||
let num_partitions = if let Some(parallelism) = add.write_parallelism {
|
||||
parallelism
|
||||
|
||||
@@ -255,15 +255,24 @@ impl DatasetConsistencyWrapper {
|
||||
pub fn ensure_mutable(&self) -> Result<()> {
|
||||
let state = self.state.lock()?;
|
||||
if state.pinned_version.is_some() {
|
||||
Err(crate::Error::InvalidInput {
|
||||
message: "table cannot be modified when a specific version is checked out"
|
||||
.to_string(),
|
||||
})
|
||||
Err(read_only_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Capture a writable dataset and its branch together, after applying the
|
||||
/// normal consistency policy. A checkout after this sample cannot retarget it.
|
||||
pub(crate) async fn writable_dataset(&self) -> Result<Arc<Dataset>> {
|
||||
self.ensure_mutable()?;
|
||||
self.get().await?;
|
||||
let state = self.state.lock()?;
|
||||
if state.pinned_version.is_some() {
|
||||
return Err(read_only_error());
|
||||
}
|
||||
Ok(state.dataset.clone())
|
||||
}
|
||||
|
||||
/// The branch of the visible snapshot, or `None` for `main`.
|
||||
pub fn current_branch(&self) -> Option<String> {
|
||||
self.state
|
||||
@@ -493,6 +502,12 @@ async fn validate_branch_identity(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_only_error() -> Error {
|
||||
Error::InvalidInput {
|
||||
message: "table cannot be modified when a specific version is checked out".into(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn refresh_latest(state: Arc<Mutex<DatasetState>>) -> Result<Arc<Dataset>> {
|
||||
let dataset = { state.lock()?.dataset.clone() };
|
||||
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{AddDataBuilder, AddDataMode, AddResult, BaseTable, NaNVectorBehavior};
|
||||
use crate::data::scannable::Scannable;
|
||||
use crate::embeddings::EmbeddingRegistry;
|
||||
use crate::{Error, Result};
|
||||
|
||||
pub(super) mod native;
|
||||
|
||||
/// A resumable write to one table and branch.
|
||||
///
|
||||
/// Share [`Self::id`] with workers and reopen it with
|
||||
/// [`crate::Table::open_write`]. Workers can stage data without publishing a
|
||||
/// version. After all worker calls finish, explicitly call [`Self::commit`] or
|
||||
/// [`Self::abort`]. Dropping a handle leaves the session available to others.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StagedWrite {
|
||||
id: StagedWriteId,
|
||||
encoded_id: String,
|
||||
table: Arc<dyn BaseTable>,
|
||||
embedding_registry: Arc<dyn EmbeddingRegistry>,
|
||||
}
|
||||
|
||||
impl StagedWrite {
|
||||
pub(super) fn new(
|
||||
id: StagedWriteId,
|
||||
table: Arc<dyn BaseTable>,
|
||||
embedding_registry: Arc<dyn EmbeddingRegistry>,
|
||||
) -> Self {
|
||||
Self {
|
||||
encoded_id: id.to_string(),
|
||||
id,
|
||||
table,
|
||||
embedding_registry,
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque identifier to pass to [`crate::Table::open_write`].
|
||||
pub fn id(&self) -> &str {
|
||||
&self.encoded_id
|
||||
}
|
||||
|
||||
/// The mode set when the write was started. Used by SDK data converters.
|
||||
#[doc(hidden)]
|
||||
pub fn mode(&self) -> AddDataMode {
|
||||
self.id.mode.clone()
|
||||
}
|
||||
|
||||
/// Schema to use for SDK input conversion. Embedded uses the pinned base.
|
||||
#[doc(hidden)]
|
||||
pub async fn input_schema(&self) -> Result<arrow_schema::SchemaRef> {
|
||||
self.table.staged_write_schema(&self.id).await
|
||||
}
|
||||
|
||||
/// Stage data using the table's add preprocessing. An empty input is a no-op.
|
||||
///
|
||||
/// On LanceDB Enterprise, [`StagedAddBuilder::execute`] rejects non-empty
|
||||
/// overwrite input with top-level schema metadata before uploading any parts.
|
||||
/// Field and nested field metadata are supported.
|
||||
pub fn add<T: Scannable + 'static>(&self, data: T) -> StagedAddBuilder {
|
||||
StagedAddBuilder {
|
||||
id: self.id.clone(),
|
||||
add: AddDataBuilder::new(
|
||||
self.table.clone(),
|
||||
Box::new(data),
|
||||
Some(self.embedding_registry.clone()),
|
||||
)
|
||||
.mode(self.mode()),
|
||||
idempotency_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish the staged data as one version. A write with no staged rows fails.
|
||||
///
|
||||
/// Append can rebase over concurrent appends. Overwrite requires identical
|
||||
/// schemas across parts and fails if another write advanced the table since
|
||||
/// this write began. If completion reports an unknown outcome, inspect the
|
||||
/// table before trying to commit or abort again. On Embedded, retrying
|
||||
/// a confirmed commit returns the published version and resumes cleanup.
|
||||
pub async fn commit(&self) -> Result<AddResult> {
|
||||
self.table.commit_staged_write(&self.id).await
|
||||
}
|
||||
|
||||
/// Discard staged data. Repeating an abort is safe and can retry cleanup.
|
||||
/// Current Enterprise servers leave unreferenced overwrite files for
|
||||
/// storage cleanup after aborting the upload.
|
||||
pub async fn abort(&self) -> Result<()> {
|
||||
self.table.abort_staged_write(&self.id).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Configures one [`StagedWrite::add`] call.
|
||||
#[derive(Debug)]
|
||||
pub struct StagedAddBuilder {
|
||||
id: StagedWriteId,
|
||||
add: AddDataBuilder,
|
||||
idempotency_key: Option<String>,
|
||||
}
|
||||
|
||||
impl StagedAddBuilder {
|
||||
/// Set a nonempty caller-chosen key. Use the same key and data for retries
|
||||
/// of one worker task, with the same input order and batching.
|
||||
///
|
||||
/// Enterprise replaces matching parts by key and chunk number. If changed
|
||||
/// input produces fewer chunks, the original trailing chunks remain staged.
|
||||
pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
|
||||
self.idempotency_key = Some(key.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Configure how NaN values and null elements in vector columns are handled.
|
||||
pub fn on_nan_vectors(mut self, behavior: NaNVectorBehavior) -> Self {
|
||||
self.add = self.add.on_nan_vectors(behavior);
|
||||
self
|
||||
}
|
||||
|
||||
/// Run the worker write. Only [`StagedWrite::commit`] publishes a version.
|
||||
pub async fn execute(self) -> Result<()> {
|
||||
let key = match self.idempotency_key.as_deref() {
|
||||
Some("") => return Err(invalid("idempotency_key must be nonempty")),
|
||||
Some(key) => Uuid::new_v5(&self.id.upload, key.as_bytes()),
|
||||
None => Uuid::new_v4(),
|
||||
};
|
||||
self.add
|
||||
.parent
|
||||
.clone()
|
||||
.stage_add(&self.id, self.add, key)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[doc(hidden)]
|
||||
pub struct StagedWriteId {
|
||||
pub(crate) upload: Uuid,
|
||||
pub(crate) mode: AddDataMode,
|
||||
// Enterprise has no open-session endpoint. Match the table and branch
|
||||
// addressed by the client before accepting the ID. Embedded verifies its
|
||||
// stored marker at the selected table and branch instead.
|
||||
pub(crate) enterprise_scope: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl StagedWriteId {
|
||||
pub(crate) fn validate_scope(&self, enterprise_scope: Option<Uuid>) -> Result<()> {
|
||||
if self.enterprise_scope == enterprise_scope {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid("write_id belongs to a different table or branch"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for StagedWriteId {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
let mode = match self.mode {
|
||||
AddDataMode::Append => "append",
|
||||
AddDataMode::Overwrite => "overwrite",
|
||||
};
|
||||
write!(f, "sw1.{mode}.{}", self.upload)?;
|
||||
if let Some(scope) = self.enterprise_scope {
|
||||
write!(f, ".{scope}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for StagedWriteId {
|
||||
type Err = Error;
|
||||
|
||||
fn from_str(value: &str) -> Result<Self> {
|
||||
fn parse(value: &str) -> Option<StagedWriteId> {
|
||||
let mut fields = value.split('.');
|
||||
if fields.next()? != "sw1" {
|
||||
return None;
|
||||
}
|
||||
let mode = match fields.next()? {
|
||||
"append" => AddDataMode::Append,
|
||||
"overwrite" => AddDataMode::Overwrite,
|
||||
_ => return None,
|
||||
};
|
||||
let upload = fields.next()?.parse().ok()?;
|
||||
let enterprise_scope = match fields.next() {
|
||||
Some(scope) => Some(scope.parse().ok()?),
|
||||
None => None,
|
||||
};
|
||||
if fields.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(StagedWriteId {
|
||||
upload,
|
||||
mode,
|
||||
enterprise_scope,
|
||||
})
|
||||
}
|
||||
parse(value).ok_or_else(|| invalid("invalid staged write_id"))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn unsupported() -> Error {
|
||||
Error::NotSupported {
|
||||
message: "staged writes are not supported on this table".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> Error {
|
||||
Error::InvalidInput {
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,626 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use arrow_schema::Schema;
|
||||
use datafusion_physical_plan::execute_stream;
|
||||
use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
|
||||
use futures::{StreamExt, TryStreamExt, stream};
|
||||
use lance::Dataset;
|
||||
use lance::dataset::transaction::{Operation, Transaction};
|
||||
use lance::dataset::{CommitBuilder, InsertBuilder, WriteMode, WriteParams};
|
||||
use lance_table::format::{Fragment, pb};
|
||||
use object_store::ObjectStoreExt;
|
||||
use object_store::path::Path;
|
||||
use prost::Message;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::table::{NativeTable, TableDefinition, computed_columns, validate_embedded_add};
|
||||
use crate::{Error, Result};
|
||||
|
||||
use super::{AddDataBuilder, AddDataMode, AddResult, StagedWriteId, invalid};
|
||||
|
||||
mod journal;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use journal::{
|
||||
Disposition, Entry, Journal, Publication, Registration, SessionMarker, Tail, delete_if_present,
|
||||
};
|
||||
|
||||
pub(in crate::table) struct NativeStagedWrite {
|
||||
dataset: Arc<Dataset>,
|
||||
journal: Journal,
|
||||
marker: SessionMarker,
|
||||
}
|
||||
|
||||
impl NativeStagedWrite {
|
||||
pub(in crate::table) async fn begin(
|
||||
table: &NativeTable,
|
||||
mode: AddDataMode,
|
||||
) -> Result<StagedWriteId> {
|
||||
let dataset = table.dataset.writable_dataset().await?;
|
||||
let latest = dataset.latest_version_id().await?;
|
||||
let dataset = at_version(dataset, latest).await?;
|
||||
crate::materialized_view::ensure_not_a_view(
|
||||
table.name.as_str(),
|
||||
&dataset.schema().metadata,
|
||||
"add to",
|
||||
)?;
|
||||
let id = StagedWriteId {
|
||||
upload: Uuid::new_v4(),
|
||||
mode,
|
||||
enterprise_scope: None,
|
||||
};
|
||||
let marker = SessionMarker {
|
||||
base_version: latest,
|
||||
branch: dataset.branch_identifier().await?,
|
||||
overwrite: matches!(id.mode, AddDataMode::Overwrite),
|
||||
};
|
||||
open_journal(&dataset, &id).await?.start(marker).await?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub(in crate::table) async fn open(table: &NativeTable, id: &StagedWriteId) -> Result<Self> {
|
||||
let dataset = table.dataset.writable_dataset().await?;
|
||||
id.validate_scope(None)?;
|
||||
let journal = open_journal(&dataset, id).await?;
|
||||
let marker = journal.marker().await?;
|
||||
if marker.branch != dataset.branch_identifier().await?
|
||||
|| marker.overwrite != matches!(id.mode, AddDataMode::Overwrite)
|
||||
{
|
||||
return Err(invalid(
|
||||
"write_id does not match the staged write's branch or mode",
|
||||
));
|
||||
}
|
||||
Ok(Self {
|
||||
dataset,
|
||||
journal,
|
||||
marker,
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::table) async fn schema(&self) -> Result<arrow_schema::SchemaRef> {
|
||||
let base = self.base_dataset().await?;
|
||||
Ok(Arc::new(Schema::from(base.schema())))
|
||||
}
|
||||
|
||||
pub(in crate::table) async fn add(
|
||||
&self,
|
||||
table: &NativeTable,
|
||||
add: AddDataBuilder,
|
||||
key: Uuid,
|
||||
) -> Result<()> {
|
||||
let tail = self.journal.writable_tail().await?;
|
||||
let Tail::Open(slot) = tail else {
|
||||
return Err(tail.closed_error());
|
||||
};
|
||||
if add.data.num_rows() == Some(0) {
|
||||
return Ok(());
|
||||
}
|
||||
let base = self.base_dataset().await?;
|
||||
crate::materialized_view::ensure_not_a_view(
|
||||
table.name.as_str(),
|
||||
&base.schema().metadata,
|
||||
"add to",
|
||||
)?;
|
||||
let schema = Arc::new(Schema::from(base.schema()));
|
||||
validate_embedded_add(&schema, &add)?;
|
||||
let definition = TableDefinition::try_from_rich_schema(schema.clone())?;
|
||||
let output = add.into_plan(&schema, &definition)?;
|
||||
let declared: Vec<_> = computed_columns::computed_columns(&schema)
|
||||
.into_iter()
|
||||
.map(|declaration| declaration.name)
|
||||
.collect();
|
||||
// Keep the plan alive through staging, including any source Blob snapshots.
|
||||
let input = execute_stream(output.plan.clone(), Default::default())?;
|
||||
let input_schema = input.schema();
|
||||
let input = input
|
||||
.try_filter(|batch| futures::future::ready(batch.num_rows() != 0))
|
||||
.map(move |batch| {
|
||||
let batch = batch?;
|
||||
computed_columns::ensure_batch_writes_no_computed_values(&declared, &batch)
|
||||
.map_err(|error| {
|
||||
datafusion_common::DataFusionError::External(Box::new(error))
|
||||
})?;
|
||||
Ok(batch)
|
||||
});
|
||||
let input: datafusion_execution::SendableRecordBatchStream =
|
||||
Box::pin(RecordBatchStreamAdapter::new(input_schema, input));
|
||||
let params = WriteParams {
|
||||
mode: if self.marker.overwrite {
|
||||
WriteMode::Overwrite
|
||||
} else {
|
||||
WriteMode::Append
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let transaction = InsertBuilder::new(base)
|
||||
.with_params(¶ms)
|
||||
.execute_uncommitted_stream(input)
|
||||
.await?;
|
||||
if self.part_fragments(&transaction)?.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let attempt = Uuid::new_v4();
|
||||
let part_path = self.part_path(attempt);
|
||||
if let Err(error) = self.write_part(&part_path, &transaction).await {
|
||||
// This attempt has never been offered to the journal.
|
||||
if let Err(cleanup) = self
|
||||
.cleanup_part(&part_path, &transaction, &HashSet::new())
|
||||
.await
|
||||
{
|
||||
log::warn!("Failed to clean up staged write part {part_path}: {cleanup}");
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
// On an ambiguous error, keep this part for finalization. It may
|
||||
// have registered before we lost the acknowledgement.
|
||||
match self
|
||||
.journal
|
||||
.register(slot, Entry::Part { key, attempt })
|
||||
.await?
|
||||
{
|
||||
Registration::Recorded(_) => Ok(()),
|
||||
Registration::Closed(Tail::Finished(disposition)) => {
|
||||
self.cleanup(disposition).await?;
|
||||
Err(disposition.error())
|
||||
}
|
||||
Registration::Closed(tail) => {
|
||||
self.cleanup_part(&part_path, &transaction, &HashSet::new())
|
||||
.await?;
|
||||
Err(tail.closed_error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::table) async fn commit(&self, table: &NativeTable) -> Result<AddResult> {
|
||||
let claim = Uuid::new_v4();
|
||||
let slot = match self.journal.writable_tail().await? {
|
||||
Tail::Open(slot) => match self.journal.register(slot, Entry::Commit(claim)).await? {
|
||||
Registration::Recorded(slot) => slot,
|
||||
Registration::Closed(tail) => return self.recover_commit(table, tail).await,
|
||||
},
|
||||
tail => return self.recover_commit(table, tail).await,
|
||||
};
|
||||
let (mut transaction, base) = match self.prepare_commit(slot).await {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => return Err(self.release_claim(claim, error).await),
|
||||
};
|
||||
transaction.uuid = claim.to_string();
|
||||
let publisher = Arc::new(Publication::new(
|
||||
base.commit_handler(),
|
||||
self.journal.clone(),
|
||||
claim,
|
||||
));
|
||||
let mut builder = CommitBuilder::new(base).with_commit_handler(publisher.clone());
|
||||
if self.marker.overwrite {
|
||||
// Lance strict overwrite attempts exactly base_version + 1.
|
||||
builder = builder.with_max_retries(0);
|
||||
}
|
||||
let committed = match builder.execute(transaction).await {
|
||||
Ok(committed) => committed,
|
||||
Err(error) => {
|
||||
// Before forwarding, we know the manifest was never submitted.
|
||||
// Once forwarded, only Lance's verified conflict errors permit
|
||||
// release. A transport error or a missing manifest is insufficient.
|
||||
if !publisher.forwarded()
|
||||
|| matches!(
|
||||
error.find_root(),
|
||||
lance::Error::CommitConflict { .. }
|
||||
| lance::Error::RetryableCommitConflict { .. }
|
||||
| lance::Error::IncompatibleTransaction { .. }
|
||||
)
|
||||
{
|
||||
return Err(self.release_claim(claim, error.into()).await);
|
||||
}
|
||||
return Err(Error::Other {
|
||||
message: "staged write commit outcome unknown; check the table before retrying or aborting".into(),
|
||||
source: Some(Box::new(error)),
|
||||
});
|
||||
}
|
||||
};
|
||||
let version = committed.manifest().version;
|
||||
table.dataset.update(committed);
|
||||
table.bump_freshness();
|
||||
Ok(self.finish_commit(version, claim).await)
|
||||
}
|
||||
|
||||
async fn recover_commit(&self, table: &NativeTable, tail: Tail) -> Result<AddResult> {
|
||||
let (version, claim) = match tail {
|
||||
Tail::Finished(Disposition::Committed {
|
||||
version,
|
||||
transaction,
|
||||
}) => (version, transaction),
|
||||
Tail::Submitting {
|
||||
claim,
|
||||
first_version,
|
||||
} => {
|
||||
let Some(version) = self.find_commit(claim, first_version).await? else {
|
||||
return Err(tail.closed_error());
|
||||
};
|
||||
(version, claim)
|
||||
}
|
||||
_ => return Err(tail.closed_error()),
|
||||
};
|
||||
// Recovering a published version never submits a Lance transaction again.
|
||||
if self.dataset.manifest().version < version {
|
||||
match self.dataset.checkout_version(version).await {
|
||||
Ok(dataset) => table.dataset.update(dataset),
|
||||
Err(error) => log::warn!(
|
||||
"Failed to refresh table after staged write at version {version}: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
table.bump_freshness();
|
||||
Ok(self.finish_commit(version, claim).await)
|
||||
}
|
||||
|
||||
async fn find_commit(&self, claim: Uuid, first_version: u64) -> Result<Option<u64>> {
|
||||
let uuid = claim.to_string();
|
||||
let latest = self.dataset.latest_version_id().await?;
|
||||
for version in (first_version..=latest).rev() {
|
||||
match self.dataset.read_transaction_by_version(version).await {
|
||||
Ok(Some(transaction)) if transaction.uuid == uuid => return Ok(Some(version)),
|
||||
Ok(_) => {}
|
||||
Err(error) if error.is_not_found() => {}
|
||||
Err(error) => {
|
||||
return Err(Error::Other {
|
||||
message: "could not verify the staged write's publication outcome".into(),
|
||||
source: Some(Box::new(error)),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Entries missing from retained history cannot prove rejection.
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn release_claim(&self, claim: Uuid, cause: Error) -> Error {
|
||||
match self.journal.release(claim).await {
|
||||
Ok(()) => match self.journal.tail().await {
|
||||
Ok(tail @ (Tail::Aborting | Tail::Finished(_))) => tail.closed_error(),
|
||||
_ => cause,
|
||||
},
|
||||
Err(error) => Error::Other {
|
||||
message: format!(
|
||||
"staged write did not commit ({cause}), but could not persist its release"
|
||||
),
|
||||
source: Some(Box::new(error)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async fn finish_commit(&self, version: u64, transaction: Uuid) -> AddResult {
|
||||
let disposition = Disposition::Committed {
|
||||
version,
|
||||
transaction,
|
||||
};
|
||||
if let Err(error) = self.finish(disposition).await {
|
||||
// Publication succeeded. Reopening with the ID can resume cleanup
|
||||
// using the terminal record or the transaction in Lance history.
|
||||
log::warn!(
|
||||
"Failed to clean up staged write {} at version {version}: {error}",
|
||||
self.journal.prefix
|
||||
);
|
||||
}
|
||||
AddResult { version }
|
||||
}
|
||||
|
||||
pub(in crate::table) async fn abort(&self) -> Result<()> {
|
||||
let tail = match self.journal.writable_tail().await? {
|
||||
Tail::Open(slot) => match self
|
||||
.journal
|
||||
.register(slot, Entry::Abort(Uuid::new_v4()))
|
||||
.await?
|
||||
{
|
||||
Registration::Recorded(_) => Tail::Aborting,
|
||||
Registration::Closed(tail) => tail,
|
||||
},
|
||||
tail => tail,
|
||||
};
|
||||
match tail {
|
||||
Tail::Aborting => self.finish(Disposition::Aborted).await,
|
||||
Tail::Finished(Disposition::Aborted) => self.cleanup(Disposition::Aborted).await,
|
||||
_ => Err(tail.closed_error()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn finish(&self, disposition: Disposition) -> Result<()> {
|
||||
self.journal.finish(&self.marker, disposition).await?;
|
||||
self.cleanup(disposition).await
|
||||
}
|
||||
|
||||
async fn base_dataset(&self) -> Result<Arc<Dataset>> {
|
||||
at_version(self.dataset.clone(), self.marker.base_version).await
|
||||
}
|
||||
|
||||
async fn prepare_commit(&self, slot: u64) -> Result<(Transaction, Arc<Dataset>)> {
|
||||
let parts: Vec<_> = stream::iter(0..slot)
|
||||
.map(|index| async move { self.journal.entry(index).await })
|
||||
.buffered(16)
|
||||
.try_collect()
|
||||
.await?;
|
||||
let mut newest = HashMap::new();
|
||||
for (index, part) in parts.into_iter().enumerate() {
|
||||
if let Entry::Part { key, attempt } = part {
|
||||
newest.insert(key, (index, attempt));
|
||||
}
|
||||
}
|
||||
let mut selected: Vec<_> = newest.into_values().collect();
|
||||
selected.sort_unstable_by_key(|&(index, _)| index);
|
||||
if selected.is_empty() {
|
||||
return Err(invalid("cannot commit a staged write with no staged rows"));
|
||||
}
|
||||
let transactions: Vec<_> = stream::iter(selected.into_iter().map(|(_, attempt)| attempt))
|
||||
.map(|attempt| async move { self.read_part(&self.part_path(attempt)).await })
|
||||
.buffered(16)
|
||||
.try_collect()
|
||||
.await?;
|
||||
let merged = self.merge_parts(transactions)?;
|
||||
let base = self.base_dataset().await?;
|
||||
if self.marker.overwrite {
|
||||
let latest = base.latest_version_id().await?;
|
||||
if latest != self.marker.base_version {
|
||||
return Err(invalid(format!(
|
||||
"cannot commit staged overwrite: table advanced from version {} to {latest}",
|
||||
self.marker.base_version,
|
||||
)));
|
||||
}
|
||||
}
|
||||
// A long-running writer can outlive storage retention. Check the files
|
||||
// referenced by the proposed manifest before publishing it.
|
||||
let files: Vec<_> = self
|
||||
.part_fragments(&merged)?
|
||||
.iter()
|
||||
.flat_map(|part| part.files.iter().cloned())
|
||||
.collect();
|
||||
stream::iter(files)
|
||||
.map(|file| {
|
||||
let base = base.clone();
|
||||
async move {
|
||||
let (store, path) = base.resolve_data_file_location(&file).await?;
|
||||
store.inner.head(&path).await?;
|
||||
Ok::<_, Error>(())
|
||||
}
|
||||
})
|
||||
.buffer_unordered(16)
|
||||
.try_for_each(|()| futures::future::ready(Ok(())))
|
||||
.await?;
|
||||
Ok((merged, base))
|
||||
}
|
||||
|
||||
fn merge_parts(&self, transactions: Vec<Transaction>) -> Result<Transaction> {
|
||||
let mut transactions = transactions.into_iter();
|
||||
let mut operation = transactions
|
||||
.next()
|
||||
.ok_or_else(|| invalid("no staged transactions"))?
|
||||
.operation;
|
||||
for transaction in transactions {
|
||||
match (&mut operation, transaction.operation) {
|
||||
(Operation::Append { fragments }, Operation::Append { fragments: other }) => {
|
||||
fragments.extend(other);
|
||||
}
|
||||
// Lance's schema equality ignores the top-level metadata map.
|
||||
(
|
||||
Operation::Overwrite {
|
||||
fragments,
|
||||
schema,
|
||||
config_upsert_values,
|
||||
initial_bases,
|
||||
},
|
||||
Operation::Overwrite {
|
||||
fragments: other,
|
||||
schema: other_schema,
|
||||
config_upsert_values: other_config,
|
||||
initial_bases: other_bases,
|
||||
},
|
||||
) if schema.fields == other_schema.fields
|
||||
&& schema.metadata == other_schema.metadata
|
||||
&& *config_upsert_values == other_config
|
||||
&& *initial_bases == other_bases =>
|
||||
{
|
||||
fragments.extend(other);
|
||||
}
|
||||
_ => {
|
||||
return Err(invalid(
|
||||
"staged parts must have identical schemas and compatible write modes",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Transaction::new(self.marker.base_version, operation, None))
|
||||
}
|
||||
|
||||
fn part_fragments<'a>(&self, transaction: &'a Transaction) -> Result<&'a [Fragment]> {
|
||||
if transaction.read_version != self.marker.base_version {
|
||||
return Err(invalid(
|
||||
"staged part was written against a different base version",
|
||||
));
|
||||
}
|
||||
match &transaction.operation {
|
||||
Operation::Append { fragments } if !self.marker.overwrite => Ok(fragments),
|
||||
Operation::Overwrite { fragments, .. } if self.marker.overwrite => Ok(fragments),
|
||||
_ => Err(invalid(
|
||||
"staged part has a different write mode from the session",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn part_path(&self, attempt: Uuid) -> Path {
|
||||
self.journal.path("parts", format!("{attempt}.txn"))
|
||||
}
|
||||
|
||||
async fn write_part(&self, path: &Path, transaction: &Transaction) -> Result<()> {
|
||||
let mut part = pb::Transaction::try_from(transaction)?;
|
||||
// Lance's transaction codec preserves field metadata but omits
|
||||
// top-level schema metadata for overwrites.
|
||||
if let (
|
||||
Operation::Overwrite { schema, .. },
|
||||
Some(pb::transaction::Operation::Overwrite(overwrite)),
|
||||
) = (&transaction.operation, &mut part.operation)
|
||||
{
|
||||
overwrite.schema_metadata = schema
|
||||
.metadata
|
||||
.iter()
|
||||
.map(|(key, value)| (key.clone(), value.as_bytes().to_vec()))
|
||||
.collect();
|
||||
}
|
||||
self.journal
|
||||
.store
|
||||
.put(path, part.encode_to_vec().into())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_part(&self, path: &Path) -> Result<Transaction> {
|
||||
let bytes = self.journal.store.get(path).await?.bytes().await?;
|
||||
let mut part = pb::Transaction::decode(bytes).map_err(lance::Error::from)?;
|
||||
// Restore the map that Lance's conversion would otherwise discard
|
||||
// before checking agreement across the overwrite parts.
|
||||
let schema_metadata = match &mut part.operation {
|
||||
Some(pb::transaction::Operation::Overwrite(overwrite)) => {
|
||||
std::mem::take(&mut overwrite.schema_metadata)
|
||||
}
|
||||
_ => HashMap::new(),
|
||||
};
|
||||
let mut transaction: Transaction = part.try_into()?;
|
||||
if let Operation::Overwrite { schema, .. } = &mut transaction.operation {
|
||||
schema.metadata = schema_metadata
|
||||
.into_iter()
|
||||
.map(|(key, value)| {
|
||||
let value = String::from_utf8(value).map_err(|_| {
|
||||
invalid("invalid UTF-8 in staged overwrite schema metadata")
|
||||
})?;
|
||||
Ok((key, value))
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
}
|
||||
self.part_fragments(&transaction)?;
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
async fn cleanup(&self, disposition: Disposition) -> Result<()> {
|
||||
let prefix = self.journal.prefix.clone().join("parts");
|
||||
let paths: Vec<_> = self
|
||||
.journal
|
||||
.store
|
||||
.list(Some(&prefix))
|
||||
.map_ok(|meta| meta.location)
|
||||
.try_collect()
|
||||
.await?;
|
||||
if !paths.is_empty() {
|
||||
let keep = self.published_files(disposition).await?;
|
||||
for path in paths {
|
||||
// Another finalizer can remove the transaction after its data
|
||||
// is safe. This also covers a worker cleaning its rejected part.
|
||||
let transaction = match self.read_part(&path).await {
|
||||
Ok(transaction) => transaction,
|
||||
Err(Error::ObjectStore {
|
||||
source: object_store::Error::NotFound { .. },
|
||||
}) => continue,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
self.cleanup_part(&path, &transaction, &keep).await?;
|
||||
}
|
||||
}
|
||||
self.journal.delete_metadata().await
|
||||
}
|
||||
|
||||
async fn published_files(&self, disposition: Disposition) -> Result<HashSet<String>> {
|
||||
let Disposition::Committed {
|
||||
version,
|
||||
transaction,
|
||||
} = disposition
|
||||
else {
|
||||
return Ok(HashSet::new());
|
||||
};
|
||||
// The authoritative Lance transaction protects committed data even
|
||||
// when the journal has already been partly swept. If the transaction
|
||||
// is no longer available, keep the remaining parts for safe recovery.
|
||||
let uuid = transaction.to_string();
|
||||
let committed = self
|
||||
.dataset
|
||||
.read_transaction_by_version(version)
|
||||
.await?
|
||||
.filter(|commit| commit.uuid == uuid)
|
||||
.ok_or_else(|| invalid("cannot verify published files for staged write cleanup"))?;
|
||||
let fragments = match committed.operation {
|
||||
Operation::Append { fragments } | Operation::Overwrite { fragments, .. } => fragments,
|
||||
_ => return Err(invalid("staged write published an unexpected operation")),
|
||||
};
|
||||
Ok(fragments
|
||||
.into_iter()
|
||||
.flat_map(|fragment| fragment.files)
|
||||
.map(|file| file.path)
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn cleanup_part(
|
||||
&self,
|
||||
path: &Path,
|
||||
transaction: &Transaction,
|
||||
keep: &HashSet<String>,
|
||||
) -> Result<()> {
|
||||
for fragment in self.part_fragments(transaction)? {
|
||||
for file in &fragment.files {
|
||||
if keep.contains(&file.path) {
|
||||
continue;
|
||||
}
|
||||
let (store, data_path) = self.dataset.resolve_data_file_location(file).await?;
|
||||
// Clean Lance-owned sidecars while preserving referenced
|
||||
// objects in Managed or External storage.
|
||||
let stem = file
|
||||
.path
|
||||
.strip_suffix(".lance")
|
||||
.filter(|stem| !stem.is_empty() && !stem.contains('/'))
|
||||
.ok_or_else(|| invalid("invalid staged data filename"))?;
|
||||
let parent: Path = data_path
|
||||
.parts()
|
||||
.take(data_path.parts_count() - 1)
|
||||
.collect();
|
||||
let blobs = parent.join(stem);
|
||||
let mut blob_paths = store.inner.list(Some(&blobs));
|
||||
while let Some(blob) = blob_paths.try_next().await? {
|
||||
delete_if_present(&store.inner, &blob.location).await?;
|
||||
}
|
||||
delete_if_present(&store.inner, &data_path).await?;
|
||||
}
|
||||
}
|
||||
// Keep the reference until all data and its sidecars are safe.
|
||||
self.journal.delete(path).await
|
||||
}
|
||||
}
|
||||
|
||||
async fn at_version(dataset: Arc<Dataset>, version: u64) -> Result<Arc<Dataset>> {
|
||||
if dataset.manifest().version == version {
|
||||
Ok(dataset)
|
||||
} else {
|
||||
Ok(Arc::new(dataset.checkout_version(version).await?))
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_journal(dataset: &Dataset, id: &StagedWriteId) -> Result<Journal> {
|
||||
let prefix = dataset
|
||||
.data_dir()
|
||||
.join("_transactions")
|
||||
.join(id.upload.to_string());
|
||||
let store = dataset.object_store(None).await?;
|
||||
// Lance excludes COS from put-if-absent because bucket versioning can
|
||||
// make it accept a conflicting creation. On filesystems the pinned
|
||||
// object_store publishes Create with a hard link and hides its temp file
|
||||
// from journal listings.
|
||||
if store.scheme() == "cos" {
|
||||
return Err(Error::NotSupported {
|
||||
message:
|
||||
"staged writes require atomic object creation, which Tencent COS does not guarantee"
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
Ok(Journal {
|
||||
store: store.inner.clone(),
|
||||
prefix,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use futures::TryStreamExt;
|
||||
use lance_io::object_store::ObjectStore as LanceObjectStore;
|
||||
use lance_table::format::{IndexMetadata, Manifest, Transaction as ManifestTransaction};
|
||||
use lance_table::io::commit::{
|
||||
CommitError, CommitHandler, ManifestLocation, ManifestNamingScheme, ManifestWriter,
|
||||
};
|
||||
use object_store::path::Path;
|
||||
use object_store::{ObjectStore, ObjectStoreExt, PutMode};
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::super::invalid;
|
||||
use crate::{Error, Result};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
pub(super) struct SessionMarker {
|
||||
pub(super) base_version: u64,
|
||||
pub(super) branch: lance::dataset::refs::BranchIdentifier,
|
||||
pub(super) overwrite: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
|
||||
pub(super) enum Entry {
|
||||
Part { key: Uuid, attempt: Uuid },
|
||||
Commit(Uuid),
|
||||
Abort(Uuid),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
|
||||
enum Decision {
|
||||
Release,
|
||||
Submit { first_version: u64 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
|
||||
pub(super) enum Disposition {
|
||||
Committed { version: u64, transaction: Uuid },
|
||||
Aborted,
|
||||
}
|
||||
|
||||
impl Disposition {
|
||||
pub(super) fn error(self) -> Error {
|
||||
match self {
|
||||
Self::Committed { version, .. } => {
|
||||
invalid(format!("staged write committed at version {version}"))
|
||||
}
|
||||
Self::Aborted => invalid("staged write has been aborted"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
struct Terminal {
|
||||
session: SessionMarker,
|
||||
disposition: Disposition,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Tail {
|
||||
Open(u64),
|
||||
Preparing(Uuid),
|
||||
Submitting { claim: Uuid, first_version: u64 },
|
||||
Aborting,
|
||||
Finished(Disposition),
|
||||
}
|
||||
|
||||
impl Tail {
|
||||
pub(super) fn closed_error(self) -> Error {
|
||||
match self {
|
||||
Self::Finished(disposition) => disposition.error(),
|
||||
Self::Aborting => invalid("staged write is being aborted"),
|
||||
_ => invalid(
|
||||
"staged write has been sealed for commit; check the table if its outcome is unknown",
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) enum Registration {
|
||||
Recorded(u64),
|
||||
Closed(Tail),
|
||||
}
|
||||
|
||||
/// Write-once session journal on storage with atomic create and consistent
|
||||
/// reads and listings. A part and a finalizer contend for the same next slot.
|
||||
/// A commit slot reserves the inputs, but requires a separate atomic decision
|
||||
/// before it can submit a manifest. Any process can release a claim that has
|
||||
/// yet to acquire that authority. After submission, only a durable rejection
|
||||
/// receipt can reopen the journal. The terminal record is authoritative even
|
||||
/// when an operation started before finalization recreates a deleted slot.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Journal {
|
||||
pub(super) store: Arc<dyn ObjectStore>,
|
||||
pub(super) prefix: Path,
|
||||
}
|
||||
|
||||
impl Journal {
|
||||
pub(super) async fn start(&self, marker: SessionMarker) -> Result<()> {
|
||||
let stored = self
|
||||
.create(&self.prefix.clone().join("created"), marker.clone())
|
||||
.await?;
|
||||
if stored != marker {
|
||||
return Err(invalid("staged write id is already in use"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn marker(&self) -> Result<SessionMarker> {
|
||||
if let Some(terminal) = self.terminal().await? {
|
||||
return Ok(terminal.session);
|
||||
}
|
||||
if let Some(marker) = self.read(&self.prefix.clone().join("created")).await? {
|
||||
return Ok(marker);
|
||||
}
|
||||
// Cleanup may have removed the active marker between the two reads.
|
||||
self.terminal()
|
||||
.await?
|
||||
.map(|terminal| terminal.session)
|
||||
.ok_or_else(|| invalid("staged write_id was not found on this table and branch"))
|
||||
}
|
||||
|
||||
pub(super) fn path(&self, directory: &str, name: impl ToString) -> Path {
|
||||
self.prefix.clone().join(directory).join(name.to_string())
|
||||
}
|
||||
|
||||
fn entry_path(&self, slot: u64) -> Path {
|
||||
self.path("journal", format!("{slot:020}"))
|
||||
}
|
||||
|
||||
fn terminal_path(&self) -> Path {
|
||||
self.prefix.clone().join("terminal")
|
||||
}
|
||||
|
||||
async fn terminal(&self) -> Result<Option<Terminal>> {
|
||||
self.read(&self.terminal_path()).await
|
||||
}
|
||||
|
||||
pub(super) async fn finish(
|
||||
&self,
|
||||
session: &SessionMarker,
|
||||
disposition: Disposition,
|
||||
) -> Result<()> {
|
||||
let terminal = Terminal {
|
||||
session: session.clone(),
|
||||
disposition,
|
||||
};
|
||||
if self.create(&self.terminal_path(), terminal.clone()).await? != terminal {
|
||||
return Err(invalid("staged write has a different terminal outcome"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn entry(&self, slot: u64) -> Result<Entry> {
|
||||
self.read(&self.entry_path(slot))
|
||||
.await?
|
||||
.ok_or_else(|| invalid(format!("missing staged write journal slot {slot}")))
|
||||
}
|
||||
|
||||
async fn active_tail(&self) -> Result<Tail> {
|
||||
let prefix = self.prefix.clone().join("journal");
|
||||
let mut entries = self.store.list(Some(&prefix));
|
||||
let mut last = None;
|
||||
while let Some(meta) = entries.try_next().await? {
|
||||
let slot = meta
|
||||
.location
|
||||
.filename()
|
||||
.and_then(|name| name.parse::<u64>().ok())
|
||||
.ok_or_else(|| invalid("invalid staged write journal slot"))?;
|
||||
last = last.max(Some(slot));
|
||||
}
|
||||
let Some(last) = last else {
|
||||
return Ok(Tail::Open(0));
|
||||
};
|
||||
self.after_entry(last, self.entry(last).await?).await
|
||||
}
|
||||
|
||||
async fn after_entry(&self, slot: u64, entry: Entry) -> Result<Tail> {
|
||||
match entry {
|
||||
Entry::Part { .. } => Ok(Tail::Open(slot + 1)),
|
||||
Entry::Abort(_) => Ok(Tail::Aborting),
|
||||
Entry::Commit(claim) => match self.read(&self.path("decisions", claim)).await? {
|
||||
None => Ok(Tail::Preparing(claim)),
|
||||
Some(Decision::Release) => Ok(Tail::Open(slot + 1)),
|
||||
Some(Decision::Submit { first_version }) => {
|
||||
if self.read::<bool>(&self.path("rejected", claim)).await? == Some(true) {
|
||||
Ok(Tail::Open(slot + 1))
|
||||
} else {
|
||||
Ok(Tail::Submitting {
|
||||
claim,
|
||||
first_version,
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn tail(&self) -> Result<Tail> {
|
||||
if let Some(terminal) = self.terminal().await? {
|
||||
return Ok(Tail::Finished(terminal.disposition));
|
||||
}
|
||||
let active = self.active_tail().await;
|
||||
// A terminal sweep may have removed entries while we listed/read them.
|
||||
match self.terminal().await? {
|
||||
Some(terminal) => Ok(Tail::Finished(terminal.disposition)),
|
||||
None => active,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn writable_tail(&self) -> Result<Tail> {
|
||||
loop {
|
||||
let tail = self.tail().await?;
|
||||
let Tail::Preparing(claim) = tail else {
|
||||
return Ok(tail);
|
||||
};
|
||||
// Release competes with submission. The missing decision by
|
||||
// itself is never authority to resume or clean up the session.
|
||||
self.decide(claim, Decision::Release).await?;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn register(&self, mut slot: u64, entry: Entry) -> Result<Registration> {
|
||||
loop {
|
||||
if let Some(terminal) = self.terminal().await? {
|
||||
return Ok(Registration::Closed(Tail::Finished(terminal.disposition)));
|
||||
}
|
||||
let path = self.entry_path(slot);
|
||||
let written = self.create(&path, entry).await;
|
||||
if let Some(terminal) = self.terminal().await? {
|
||||
// If the request arrived after the sweep, remove the recreated
|
||||
// slot. Cleanup never consults the journal after termination.
|
||||
self.delete(&path).await?;
|
||||
return Ok(Registration::Closed(Tail::Finished(terminal.disposition)));
|
||||
}
|
||||
if written? == entry {
|
||||
return Ok(Registration::Recorded(slot));
|
||||
}
|
||||
match self.writable_tail().await? {
|
||||
Tail::Open(next) => slot = next,
|
||||
closed => return Ok(Registration::Closed(closed)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return the actual choice after a conflict or a lost acknowledgement. A
|
||||
// late request may recreate an old choice after cleanup, so check the
|
||||
// terminal record again before treating it as authorization.
|
||||
async fn decide(&self, claim: Uuid, decision: Decision) -> Result<Option<Decision>> {
|
||||
if self.terminal().await?.is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let path = self.path("decisions", claim);
|
||||
let result = self.create(&path, decision).await;
|
||||
if self.terminal().await?.is_some() {
|
||||
self.delete(&path).await?;
|
||||
return Ok(None);
|
||||
}
|
||||
result.map(Some)
|
||||
}
|
||||
|
||||
pub(super) async fn release(&self, claim: Uuid) -> Result<()> {
|
||||
if matches!(
|
||||
self.decide(claim, Decision::Release).await?,
|
||||
Some(Decision::Submit { .. })
|
||||
) {
|
||||
// Only the submitting caller, after a proven rejection, may write
|
||||
// this receipt. A restarted process can act on it without making
|
||||
// assumptions about the previous caller or a missing manifest.
|
||||
let path = self.path("rejected", claim);
|
||||
if self.terminal().await?.is_none() {
|
||||
if let Err(first_error) = self.create(&path, true).await {
|
||||
// The proof lives in memory until either write persists.
|
||||
// Retry the same immutable receipt while we still have it.
|
||||
if let Err(error) = self.create(&path, true).await {
|
||||
log::warn!(
|
||||
"First attempt to record staged write rejection failed: {first_error}"
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
if self.terminal().await?.is_some() {
|
||||
self.delete(&path).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read<T: DeserializeOwned>(&self, path: &Path) -> Result<Option<T>> {
|
||||
match self.store.get(path).await {
|
||||
Ok(found) => serde_json::from_slice(&found.bytes().await?)
|
||||
.map(Some)
|
||||
.map_err(metadata_error),
|
||||
Err(object_store::Error::NotFound { .. }) => Ok(None),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn create<T: DeserializeOwned + Serialize>(&self, path: &Path, value: T) -> Result<T> {
|
||||
let payload = serde_json::to_vec(&value).map_err(metadata_error)?;
|
||||
match self
|
||||
.store
|
||||
.put_opts(path, payload.into(), PutMode::Create.into())
|
||||
.await
|
||||
{
|
||||
Ok(_) => Ok(value),
|
||||
Err(error) => match self.read(path).await {
|
||||
Ok(Some(stored)) => Ok(stored),
|
||||
Ok(None) => Err(error.into()),
|
||||
Err(read_error) => Err(Error::Other {
|
||||
message: format!(
|
||||
"could not verify staged write metadata at {path}: {read_error}"
|
||||
),
|
||||
source: Some(Box::new(error)),
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn delete(&self, path: &Path) -> Result<()> {
|
||||
delete_if_present(&self.store, path).await
|
||||
}
|
||||
|
||||
pub(super) async fn delete_metadata(&self) -> Result<()> {
|
||||
// Part records are removed only together with their payload disposition.
|
||||
// A late worker may create one while this metadata sweep is running.
|
||||
for directory in ["journal", "decisions", "rejected"] {
|
||||
let prefix = self.prefix.clone().join(directory);
|
||||
let paths: Vec<_> = self
|
||||
.store
|
||||
.list(Some(&prefix))
|
||||
.map_ok(|meta| meta.location)
|
||||
.try_collect()
|
||||
.await?;
|
||||
for path in paths {
|
||||
self.delete(&path).await?;
|
||||
}
|
||||
}
|
||||
self.delete(&self.prefix.clone().join("created")).await
|
||||
}
|
||||
}
|
||||
|
||||
fn metadata_error(error: serde_json::Error) -> Error {
|
||||
Error::Runtime {
|
||||
message: format!("invalid staged write metadata: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn delete_if_present(store: &Arc<dyn ObjectStore>, path: &Path) -> Result<()> {
|
||||
match store.delete(path).await {
|
||||
Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpose only at manifest publication. Lance still prepares and rebases
|
||||
/// the transaction, verifies write outcomes, and uses the dataset's original
|
||||
/// commit handler. A schema or conflict error before this boundary can release
|
||||
/// the claim even if the committing process disappears before writing a reply.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Publication {
|
||||
inner: Arc<dyn CommitHandler>,
|
||||
journal: Journal,
|
||||
claim: Uuid,
|
||||
forwarded: AtomicBool,
|
||||
}
|
||||
|
||||
impl Publication {
|
||||
pub(super) fn new(inner: Arc<dyn CommitHandler>, journal: Journal, claim: Uuid) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
journal,
|
||||
claim,
|
||||
forwarded: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn forwarded(&self) -> bool {
|
||||
self.forwarded.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
impl CommitHandler for Publication {
|
||||
fn is_version_not_found_definitive(&self) -> bool {
|
||||
self.inner.is_version_not_found_definitive()
|
||||
}
|
||||
|
||||
fn propagate_commit_error_after_success(&self) -> bool {
|
||||
// After positive manifest readback, Lance must report success even if
|
||||
// the underlying handler returned a conflict-shaped error.
|
||||
false
|
||||
}
|
||||
|
||||
async fn resolve_latest_location(
|
||||
&self,
|
||||
base: &Path,
|
||||
store: &LanceObjectStore,
|
||||
) -> lance::Result<ManifestLocation> {
|
||||
self.inner.resolve_latest_location(base, store).await
|
||||
}
|
||||
|
||||
async fn resolve_version_location(
|
||||
&self,
|
||||
base: &Path,
|
||||
version: u64,
|
||||
store: &dyn ObjectStore,
|
||||
) -> lance::Result<ManifestLocation> {
|
||||
self.inner
|
||||
.resolve_version_location(base, version, store)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn commit(
|
||||
&self,
|
||||
manifest: &mut Manifest,
|
||||
indices: Option<Vec<IndexMetadata>>,
|
||||
base: &Path,
|
||||
store: &LanceObjectStore,
|
||||
writer: ManifestWriter,
|
||||
scheme: ManifestNamingScheme,
|
||||
transaction: Option<ManifestTransaction>,
|
||||
) -> std::result::Result<ManifestLocation, CommitError> {
|
||||
let decision = Decision::Submit {
|
||||
first_version: manifest.version,
|
||||
};
|
||||
match self.journal.decide(self.claim, decision).await {
|
||||
Ok(Some(Decision::Submit { .. })) => {}
|
||||
Ok(Some(Decision::Release) | None) => {
|
||||
return Err(
|
||||
lance::Error::invalid_input("staged write commit claim was released").into(),
|
||||
);
|
||||
}
|
||||
Err(error) => return Err(lance::Error::wrapped(Box::new(error)).into()),
|
||||
}
|
||||
self.forwarded.store(true, Ordering::Relaxed);
|
||||
self.inner
|
||||
.commit(manifest, indices, base, store, writer, scheme, transaction)
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,583 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use arrow_array::{RecordBatch, record_batch};
|
||||
use futures::stream::BoxStream;
|
||||
use lance::io::WrappingObjectStore;
|
||||
use object_store::{
|
||||
CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore,
|
||||
PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions,
|
||||
list::PaginatedListStore,
|
||||
};
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use super::*;
|
||||
use crate::table::BaseTable;
|
||||
use crate::{Table, connect};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Reply {
|
||||
FailBeforeWrite,
|
||||
LoseAfterWrite,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Target {
|
||||
Journal,
|
||||
Decision,
|
||||
Rejection,
|
||||
Terminal,
|
||||
Manifest,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
fn matches(self, path: &Path) -> bool {
|
||||
let directory = path.as_ref().rsplit('/').nth(1);
|
||||
match self {
|
||||
Self::Journal => directory == Some("journal"),
|
||||
Self::Decision => directory == Some("decisions"),
|
||||
Self::Rejection => directory == Some("rejected"),
|
||||
Self::Terminal => path.filename() == Some("terminal"),
|
||||
Self::Manifest => {
|
||||
directory == Some("_versions")
|
||||
&& path
|
||||
.filename()
|
||||
.is_some_and(|filename| filename.ends_with(".manifest"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Gate {
|
||||
reached: Notify,
|
||||
resume: Notify,
|
||||
persisted: AtomicBool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Faults {
|
||||
next_put: Mutex<Option<(Target, Reply, usize)>>,
|
||||
delete_journal: AtomicBool,
|
||||
next_pause: Mutex<Option<(Target, Arc<Gate>)>>,
|
||||
lose_manifest_reply: AtomicBool,
|
||||
unreadable_manifest: Mutex<Option<Path>>,
|
||||
}
|
||||
|
||||
impl Faults {
|
||||
fn gate(&self, target: Target) -> Arc<Gate> {
|
||||
let gate = Arc::new(Gate::default());
|
||||
*self.next_pause.lock().unwrap() = Some((target, gate.clone()));
|
||||
gate
|
||||
}
|
||||
|
||||
fn fail_put(&self, target: Target, reply: Reply, attempts: usize) {
|
||||
*self.next_put.lock().unwrap() = Some((target, reply, attempts));
|
||||
}
|
||||
|
||||
async fn pause(&self, path: &Path) -> Option<Arc<Gate>> {
|
||||
let gate = {
|
||||
let mut pause = self.next_pause.lock().unwrap();
|
||||
if pause
|
||||
.as_ref()
|
||||
.is_some_and(|(target, _)| target.matches(path))
|
||||
{
|
||||
pause.take().map(|(_, gate)| gate)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(gate) = &gate {
|
||||
gate.reached.notify_one();
|
||||
gate.resume.notified().await;
|
||||
}
|
||||
gate
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct FaultWrapper(Arc<Faults>);
|
||||
|
||||
impl WrappingObjectStore for FaultWrapper {
|
||||
fn wrap(&self, _prefix: &str, inner: Arc<dyn ObjectStore>) -> Arc<dyn ObjectStore> {
|
||||
Arc::new(FaultStore {
|
||||
inner,
|
||||
faults: self.0.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn wrap_paginated(
|
||||
&self,
|
||||
_prefix: &str,
|
||||
original: Arc<dyn PaginatedListStore>,
|
||||
) -> Option<Arc<dyn PaginatedListStore>> {
|
||||
Some(original)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct FaultStore {
|
||||
inner: Arc<dyn ObjectStore>,
|
||||
faults: Arc<Faults>,
|
||||
}
|
||||
|
||||
impl fmt::Display for FaultStore {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("staged write fault store")
|
||||
}
|
||||
}
|
||||
|
||||
fn io_fault(message: &'static str) -> object_store::Error {
|
||||
object_store::Error::Generic {
|
||||
store: "test",
|
||||
source: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
impl FaultStore {
|
||||
fn finish_manifest_request(&self, path: &Path) -> object_store::Result<()> {
|
||||
if Target::Manifest.matches(path)
|
||||
&& self
|
||||
.faults
|
||||
.lose_manifest_reply
|
||||
.swap(false, Ordering::SeqCst)
|
||||
{
|
||||
*self.faults.unreadable_manifest.lock().unwrap() = Some(path.clone());
|
||||
return Err(io_fault("injected lost manifest publication response"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ObjectStore for FaultStore {
|
||||
async fn put_opts(
|
||||
&self,
|
||||
path: &Path,
|
||||
payload: PutPayload,
|
||||
options: PutOptions,
|
||||
) -> object_store::Result<PutResult> {
|
||||
let fault = {
|
||||
let mut next = self.faults.next_put.lock().unwrap();
|
||||
match next.as_mut() {
|
||||
Some((target, reply, attempts)) if target.matches(path) => {
|
||||
let reply = *reply;
|
||||
*attempts -= 1;
|
||||
if *attempts == 0 {
|
||||
next.take();
|
||||
}
|
||||
Some(reply)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
if matches!(fault, Some(Reply::FailBeforeWrite)) {
|
||||
return Err(io_fault("injected write failure before persistence"));
|
||||
}
|
||||
let gate = self.faults.pause(path).await;
|
||||
let result = self.inner.put_opts(path, payload, options).await?;
|
||||
if let Some(gate) = gate {
|
||||
gate.persisted.store(true, Ordering::SeqCst);
|
||||
}
|
||||
if matches!(fault, Some(Reply::LoseAfterWrite)) {
|
||||
return Err(io_fault("injected lost write reply after persistence"));
|
||||
}
|
||||
self.finish_manifest_request(path)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn put_multipart_opts(
|
||||
&self,
|
||||
path: &Path,
|
||||
options: PutMultipartOptions,
|
||||
) -> object_store::Result<Box<dyn MultipartUpload>> {
|
||||
self.inner.put_multipart_opts(path, options).await
|
||||
}
|
||||
|
||||
async fn get_opts(&self, path: &Path, options: GetOptions) -> object_store::Result<GetResult> {
|
||||
if self.faults.unreadable_manifest.lock().unwrap().as_ref() == Some(path) {
|
||||
return Err(io_fault("injected unavailable manifest readback"));
|
||||
}
|
||||
self.inner.get_opts(path, options).await
|
||||
}
|
||||
|
||||
fn delete_stream(
|
||||
&self,
|
||||
locations: BoxStream<'static, object_store::Result<Path>>,
|
||||
) -> BoxStream<'static, object_store::Result<Path>> {
|
||||
let faults = self.faults.clone();
|
||||
self.inner.delete_stream(
|
||||
locations
|
||||
.map(move |location| {
|
||||
let location = location?;
|
||||
if Target::Journal.matches(&location)
|
||||
&& faults.delete_journal.swap(false, Ordering::SeqCst)
|
||||
{
|
||||
return Err(io_fault("injected journal cleanup failure"));
|
||||
}
|
||||
Ok(location)
|
||||
})
|
||||
.boxed(),
|
||||
)
|
||||
}
|
||||
|
||||
fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, object_store::Result<ObjectMeta>> {
|
||||
self.inner.list(prefix)
|
||||
}
|
||||
|
||||
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> object_store::Result<ListResult> {
|
||||
self.inner.list_with_delimiter(prefix).await
|
||||
}
|
||||
|
||||
async fn copy_opts(
|
||||
&self,
|
||||
from: &Path,
|
||||
to: &Path,
|
||||
options: CopyOptions,
|
||||
) -> object_store::Result<()> {
|
||||
self.inner.copy_opts(from, to, options).await
|
||||
}
|
||||
|
||||
async fn rename_opts(
|
||||
&self,
|
||||
from: &Path,
|
||||
to: &Path,
|
||||
options: RenameOptions,
|
||||
) -> object_store::Result<()> {
|
||||
self.faults.pause(to).await;
|
||||
self.inner.rename_opts(from, to, options).await?;
|
||||
self.finish_manifest_request(to)
|
||||
}
|
||||
}
|
||||
|
||||
fn row(id: i32) -> RecordBatch {
|
||||
record_batch!(("id", Int32, [id])).unwrap()
|
||||
}
|
||||
|
||||
async fn open(dir: &tempfile::TempDir, faults: Option<Arc<Faults>>) -> Table {
|
||||
let path = dir.path().join("items.lance");
|
||||
let wrapper =
|
||||
faults.map(|faults| Arc::new(FaultWrapper(faults)) as Arc<dyn WrappingObjectStore>);
|
||||
let table = NativeTable::open_with_params(
|
||||
path.to_str().unwrap(),
|
||||
"items",
|
||||
Vec::new(),
|
||||
wrapper,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
HashSet::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
Table::from(Arc::new(table) as Arc<dyn BaseTable>)
|
||||
}
|
||||
|
||||
async fn fixture() -> (tempfile::TempDir, Table, Arc<Faults>) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = connect(dir.path().to_str().unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
db.create_table("items", row(1)).execute().await.unwrap();
|
||||
let faults = Arc::new(Faults::default());
|
||||
let table = open(&dir, Some(faults.clone())).await;
|
||||
(dir, table, faults)
|
||||
}
|
||||
|
||||
async fn metadata(dir: &tempfile::TempDir, id: &str) -> Vec<String> {
|
||||
let table = open(dir, None).await;
|
||||
let dataset = table.dataset().unwrap().get().await.unwrap();
|
||||
let parsed = id.parse().unwrap();
|
||||
let journal = open_journal(&dataset, &parsed).await.unwrap();
|
||||
let mut paths: Vec<_> = journal
|
||||
.store
|
||||
.list(Some(&journal.prefix))
|
||||
.map_ok(|meta| {
|
||||
meta.location
|
||||
.as_ref()
|
||||
.strip_prefix(journal.prefix.as_ref())
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
})
|
||||
.try_collect()
|
||||
.await
|
||||
.unwrap();
|
||||
paths.sort();
|
||||
paths
|
||||
}
|
||||
|
||||
fn data_files(dir: &tempfile::TempDir) -> BTreeSet<std::path::PathBuf> {
|
||||
std::fs::read_dir(dir.path().join("items.lance/data"))
|
||||
.unwrap()
|
||||
.map(|entry| entry.unwrap().path())
|
||||
.filter(|path| {
|
||||
path.extension()
|
||||
.is_some_and(|extension| extension == "lance")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn wait(gate: &Gate) {
|
||||
tokio::time::timeout(Duration::from_secs(10), gate.reached.notified())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::empty_before(false, Reply::FailBeforeWrite)]
|
||||
#[case::schema_after(true, Reply::LoseAfterWrite)]
|
||||
#[tokio::test]
|
||||
async fn prepare_release_recovers_after_a_storage_fault(
|
||||
#[case] bad_schema: bool,
|
||||
#[case] reply: Reply,
|
||||
) {
|
||||
let (dir, table, faults) = fixture().await;
|
||||
let write = table.begin_write(AddDataMode::Overwrite).await.unwrap();
|
||||
let id = write.id().to_owned();
|
||||
if bad_schema {
|
||||
write.add(row(2)).execute().await.unwrap();
|
||||
write
|
||||
.add(record_batch!(("text", Utf8, ["x"])).unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
faults.fail_put(Target::Decision, reply, 1);
|
||||
let error = write.commit().await.unwrap_err();
|
||||
match reply {
|
||||
Reply::FailBeforeWrite => match error {
|
||||
Error::Other {
|
||||
message,
|
||||
source: Some(source),
|
||||
} => {
|
||||
assert!(message.contains("no staged rows"), "{message}");
|
||||
assert!(
|
||||
message.contains("could not persist its release"),
|
||||
"{message}"
|
||||
);
|
||||
assert!(
|
||||
source.to_string().contains("before persistence"),
|
||||
"{source}"
|
||||
);
|
||||
}
|
||||
other => panic!("expected the failed release write, got {other:?}"),
|
||||
},
|
||||
Reply::LoseAfterWrite => {
|
||||
assert!(matches!(error, Error::InvalidInput { .. }));
|
||||
assert!(error.to_string().contains("identical schemas"), "{error}");
|
||||
}
|
||||
}
|
||||
assert!(faults.next_put.lock().unwrap().is_none());
|
||||
drop(write);
|
||||
drop(table);
|
||||
let reopened = open(&dir, None).await.open_write(&id).await.unwrap();
|
||||
if bad_schema {
|
||||
reopened.abort().await.unwrap();
|
||||
assert_eq!(open(&dir, None).await.version().await.unwrap(), 1);
|
||||
} else {
|
||||
reopened.add(row(2)).execute().await.unwrap();
|
||||
assert_eq!(reopened.commit().await.unwrap().version, 2);
|
||||
}
|
||||
assert_eq!(metadata(&dir, &id).await, ["/terminal"]);
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::one_failed_write(Reply::FailBeforeWrite, 1)]
|
||||
#[case::one_lost_reply(Reply::LoseAfterWrite, 1)]
|
||||
#[case::rejection_could_not_be_recorded(Reply::FailBeforeWrite, 2)]
|
||||
#[tokio::test]
|
||||
async fn rejection_receipt_controls_recovery_after_submission(
|
||||
#[case] reply: Reply,
|
||||
#[case] failures: usize,
|
||||
) {
|
||||
let (dir, table, faults) = fixture().await;
|
||||
let write = table.begin_write(AddDataMode::Overwrite).await.unwrap();
|
||||
write.add(row(2)).execute().await.unwrap();
|
||||
let id = write.id().to_owned();
|
||||
let gate = faults.gate(Target::Manifest);
|
||||
faults.fail_put(Target::Rejection, reply, failures);
|
||||
let committing = tokio::spawn(async move { write.commit().await });
|
||||
wait(&gate).await;
|
||||
let competing = open(&dir, None).await;
|
||||
assert_eq!(competing.add(row(3)).execute().await.unwrap().version, 2);
|
||||
gate.resume.notify_one();
|
||||
let error = committing.await.unwrap().unwrap_err();
|
||||
assert!(faults.next_put.lock().unwrap().is_none());
|
||||
let reopened = open(&dir, None).await.open_write(&id).await.unwrap();
|
||||
let files = metadata(&dir, &id).await;
|
||||
if failures == 1 {
|
||||
assert!(
|
||||
matches!(error, Error::Lance { ref source }
|
||||
if matches!(source.find_root(), lance::Error::CommitConflict { .. })),
|
||||
"{error:?}"
|
||||
);
|
||||
assert!(files.iter().any(|path| path.starts_with("/rejected/")));
|
||||
reopened.abort().await.unwrap();
|
||||
assert_eq!(metadata(&dir, &id).await, ["/terminal"]);
|
||||
} else {
|
||||
assert!(
|
||||
error.to_string().contains("could not persist its release"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(files.iter().all(|path| !path.starts_with("/rejected/")));
|
||||
for error in [
|
||||
reopened.commit().await.unwrap_err(),
|
||||
reopened.abort().await.unwrap_err(),
|
||||
] {
|
||||
assert!(error.to_string().contains("sealed for commit"), "{error}");
|
||||
}
|
||||
assert_eq!(metadata(&dir, &id).await, files);
|
||||
}
|
||||
let reader = open(&dir, None).await;
|
||||
assert_eq!(reader.version().await.unwrap(), 2);
|
||||
assert_eq!(reader.count_rows(None).await.unwrap(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_publication_refuses_replay_and_abort_until_lance_proves_success() {
|
||||
let (dir, table, faults) = fixture().await;
|
||||
let write = table.begin_write(AddDataMode::Append).await.unwrap();
|
||||
write.add(row(2)).execute().await.unwrap();
|
||||
let id = write.id().to_owned();
|
||||
let gate = faults.gate(Target::Manifest);
|
||||
faults.lose_manifest_reply.store(true, Ordering::SeqCst);
|
||||
let committing = tokio::spawn(async move { write.commit().await });
|
||||
wait(&gate).await;
|
||||
let other = open(&dir, None).await;
|
||||
let reopened = other.open_write(&id).await.unwrap();
|
||||
assert_eq!(other.version().await.unwrap(), 1);
|
||||
for error in [
|
||||
reopened.abort().await.unwrap_err(),
|
||||
reopened.commit().await.unwrap_err(),
|
||||
] {
|
||||
assert!(error.to_string().contains("sealed for commit"), "{error}");
|
||||
}
|
||||
gate.resume.notify_one();
|
||||
let error = committing.await.unwrap().unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains("commit outcome unknown"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
matches!(error, Error::Other { source: Some(ref source), .. }
|
||||
if source.downcast_ref::<lance::Error>().is_some_and(lance::Error::is_commit_status_unknown)),
|
||||
"{error:?}"
|
||||
);
|
||||
assert!(
|
||||
metadata(&dir, &id)
|
||||
.await
|
||||
.iter()
|
||||
.all(|path| !path.starts_with("/rejected/"))
|
||||
);
|
||||
assert!(
|
||||
reopened
|
||||
.abort()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("sealed for commit")
|
||||
);
|
||||
assert_eq!(reopened.commit().await.unwrap().version, 2);
|
||||
assert_eq!(metadata(&dir, &id).await, ["/terminal"]);
|
||||
let reader = open(&dir, None).await;
|
||||
assert_eq!(reader.version().await.unwrap(), 2);
|
||||
assert_eq!(reader.count_rows(None).await.unwrap(), 2);
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::late_worker(Target::Journal)]
|
||||
#[case::late_publisher(Target::Decision)]
|
||||
#[tokio::test]
|
||||
async fn a_late_create_cannot_reopen_a_finished_session(#[case] target: Target) {
|
||||
let (dir, table, faults) = fixture().await;
|
||||
let initial = data_files(&dir);
|
||||
let write = table.begin_write(AddDataMode::Append).await.unwrap();
|
||||
write.add(row(2)).execute().await.unwrap();
|
||||
let with_first_part = data_files(&dir);
|
||||
let id = write.id().to_owned();
|
||||
let gate = faults.gate(target);
|
||||
let late = tokio::spawn(async move {
|
||||
if target == Target::Journal {
|
||||
write.add(row(3)).execute().await.unwrap_err()
|
||||
} else {
|
||||
write.commit().await.unwrap_err()
|
||||
}
|
||||
});
|
||||
wait(&gate).await;
|
||||
let reopened = open(&dir, None).await.open_write(&id).await.unwrap();
|
||||
let (version, rows, expected_files, message) = if target == Target::Journal {
|
||||
(
|
||||
reopened.commit().await.unwrap().version,
|
||||
2,
|
||||
with_first_part,
|
||||
"committed at version 2",
|
||||
)
|
||||
} else {
|
||||
reopened.abort().await.unwrap();
|
||||
(1, 1, initial, "aborted")
|
||||
};
|
||||
assert_eq!(metadata(&dir, &id).await, ["/terminal"]);
|
||||
gate.resume.notify_one();
|
||||
let error = late.await.unwrap();
|
||||
assert!(
|
||||
gate.persisted.load(Ordering::SeqCst),
|
||||
"the late create must actually recreate its slot"
|
||||
);
|
||||
assert!(error.to_string().contains(message), "{error}");
|
||||
assert_eq!(metadata(&dir, &id).await, ["/terminal"]);
|
||||
assert!(reopened.add(row(4)).execute().await.is_err());
|
||||
assert_eq!(data_files(&dir), expected_files);
|
||||
let reader = open(&dir, None).await;
|
||||
assert_eq!(reader.version().await.unwrap(), version);
|
||||
assert_eq!(reader.count_rows(None).await.unwrap(), rows);
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::lost_terminal(true)]
|
||||
#[case::partial_metadata_cleanup(false)]
|
||||
#[tokio::test]
|
||||
async fn committed_cleanup_retries_without_publishing_again(#[case] fail_terminal: bool) {
|
||||
let (dir, table, faults) = fixture().await;
|
||||
let mut expected_files = data_files(&dir);
|
||||
let write = table.begin_write(AddDataMode::Append).await.unwrap();
|
||||
let id = write.id().to_owned();
|
||||
write
|
||||
.add(row(2))
|
||||
.idempotency_key("same-task")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let old_attempt = data_files(&dir);
|
||||
write
|
||||
.add(row(3))
|
||||
.idempotency_key("same-task")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let new_attempt = data_files(&dir);
|
||||
expected_files.extend(new_attempt.difference(&old_attempt).cloned());
|
||||
if fail_terminal {
|
||||
faults.fail_put(Target::Terminal, Reply::FailBeforeWrite, 1);
|
||||
} else {
|
||||
faults.delete_journal.store(true, Ordering::SeqCst);
|
||||
}
|
||||
assert_eq!(write.commit().await.unwrap().version, 2);
|
||||
assert!(metadata(&dir, &id).await.len() > 1);
|
||||
assert!(faults.next_put.lock().unwrap().is_none());
|
||||
assert!(!faults.delete_journal.load(Ordering::SeqCst));
|
||||
let reopened = open(&dir, None).await.open_write(&id).await.unwrap();
|
||||
assert_eq!(reopened.commit().await.unwrap().version, 2);
|
||||
assert_eq!(metadata(&dir, &id).await, ["/terminal"]);
|
||||
assert_eq!(data_files(&dir), expected_files);
|
||||
let reader = open(&dir, None).await;
|
||||
assert_eq!(reader.version().await.unwrap(), 2);
|
||||
assert_eq!(reader.count_rows(None).await.unwrap(), 2);
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use arrow_array::{
|
||||
Int32Array, RecordBatch, StringArray, StructArray, cast::AsArray, record_batch,
|
||||
types::Int32Type,
|
||||
};
|
||||
use arrow_schema::{DataType, Field, Fields, Schema};
|
||||
use futures::{TryStreamExt, stream};
|
||||
use lancedb::arrow::{SendableRecordBatchStream, SimpleRecordBatchStream};
|
||||
use lancedb::query::ExecutableQuery;
|
||||
use lancedb::table::AddDataMode;
|
||||
use lancedb::{Table, connect};
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn row(id: i32) -> RecordBatch {
|
||||
record_batch!(("id", Int32, [id])).unwrap()
|
||||
}
|
||||
|
||||
async fn new_table() -> (TempDir, Table) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = connect(dir.path().to_str().unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let table = db.create_table("items", row(1)).execute().await.unwrap();
|
||||
(dir, table)
|
||||
}
|
||||
|
||||
async fn reopen(dir: &TempDir) -> Table {
|
||||
let db = connect(dir.path().to_str().unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
db.open_table("items").execute().await.unwrap()
|
||||
}
|
||||
|
||||
fn data_files(dir: &Path) -> HashSet<PathBuf> {
|
||||
std::fs::read_dir(dir.join("items.lance").join("data"))
|
||||
.unwrap()
|
||||
.map(|entry| entry.unwrap().path())
|
||||
.filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "lance"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn ids(table: &Table) -> Vec<i32> {
|
||||
let batches: Vec<RecordBatch> = table
|
||||
.query()
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect()
|
||||
.await
|
||||
.unwrap();
|
||||
let mut ids: Vec<_> = batches
|
||||
.iter()
|
||||
.flat_map(|batch| {
|
||||
batch
|
||||
.column(0)
|
||||
.as_primitive::<Int32Type>()
|
||||
.values()
|
||||
.iter()
|
||||
.copied()
|
||||
})
|
||||
.collect();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn staged_append_is_resumable_and_rebases_with_one_version() {
|
||||
let (dir, driver) = new_table().await;
|
||||
let id = driver
|
||||
.begin_write(AddDataMode::Append)
|
||||
.await
|
||||
.unwrap()
|
||||
.id()
|
||||
.to_owned();
|
||||
let worker_table = reopen(&dir).await;
|
||||
let write = worker_table.open_write(&id).await.unwrap();
|
||||
let data = record_batch!(("id", Int16, [2])).unwrap();
|
||||
for _ in 0..2 {
|
||||
write
|
||||
.add(data.clone())
|
||||
.idempotency_key("partition-a")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
drop(write);
|
||||
reopen(&dir)
|
||||
.await
|
||||
.open_write(&id)
|
||||
.await
|
||||
.unwrap()
|
||||
.add(row(3))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ids(&reopen(&dir).await).await, [1]);
|
||||
assert_eq!(driver.add(row(4)).execute().await.unwrap().version, 2);
|
||||
|
||||
let committer = reopen(&dir).await;
|
||||
let result = committer
|
||||
.open_write(&id)
|
||||
.await
|
||||
.unwrap()
|
||||
.commit()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.version, 3);
|
||||
assert_eq!(ids(&committer).await, [1, 2, 3, 4]);
|
||||
assert_eq!(committer.list_versions().await.unwrap().len(), 3);
|
||||
assert_eq!(data_files(dir.path()).len(), 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn staged_overwrite_validates_parts_and_publishes_only_at_commit() {
|
||||
let (dir, table) = new_table().await;
|
||||
let write = table.begin_write(AddDataMode::Overwrite).await.unwrap();
|
||||
let first = record_batch!(("text", Utf8, ["a"])).unwrap();
|
||||
write.add(first.clone()).execute().await.unwrap();
|
||||
write
|
||||
.add(row(2))
|
||||
.idempotency_key("b")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ids(&reopen(&dir).await).await, [1]);
|
||||
let err = write.commit().await.unwrap_err();
|
||||
assert!(err.to_string().contains("identical schemas"), "{err}");
|
||||
write
|
||||
.add(record_batch!(("text", Utf8, ["b"])).unwrap())
|
||||
.idempotency_key("b")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(write.commit().await.unwrap().version, 2);
|
||||
assert_eq!(table.schema().await.unwrap(), first.schema());
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 2);
|
||||
|
||||
let conflict = table.begin_write(AddDataMode::Overwrite).await.unwrap();
|
||||
conflict.add(row(9)).execute().await.unwrap();
|
||||
table.add(first).execute().await.unwrap();
|
||||
let err = conflict.commit().await.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("advanced from version 2 to 3"),
|
||||
"{err}"
|
||||
);
|
||||
conflict.abort().await.unwrap();
|
||||
assert_eq!(table.version().await.unwrap(), 3);
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::schema("other", "label", "nested")]
|
||||
#[case::field("keep-✓", "other", "nested")]
|
||||
#[case::nested_field("keep-✓", "label", "other")]
|
||||
#[tokio::test]
|
||||
async fn staged_overwrite_round_trips_metadata_across_reopened_handles(
|
||||
#[case] schema_value: &str,
|
||||
#[case] field_value: &str,
|
||||
#[case] nested_value: &str,
|
||||
) {
|
||||
let batch = |id, schema_value: &str, field_value: &str, nested_value: &str| {
|
||||
let children = Fields::from(vec![
|
||||
Field::new("label", DataType::Utf8, true)
|
||||
.with_metadata(HashMap::from([("child".into(), nested_value.into())])),
|
||||
]);
|
||||
let info = StructArray::new(
|
||||
children.clone(),
|
||||
vec![Arc::new(StringArray::from(vec!["item"]))],
|
||||
None,
|
||||
);
|
||||
let schema = Schema::new_with_metadata(
|
||||
vec![
|
||||
Field::new("id", DataType::Int32, true),
|
||||
Field::new("info", DataType::Struct(children), true)
|
||||
.with_metadata(HashMap::from([("field".into(), field_value.into())])),
|
||||
],
|
||||
HashMap::from([
|
||||
("application".into(), schema_value.into()),
|
||||
("embedding_functions".into(), "[]".into()),
|
||||
(
|
||||
"lancedb::column_definitions".into(),
|
||||
r#"[{"kind":"Physical"},{"kind":"Physical"}]"#.into(),
|
||||
),
|
||||
]),
|
||||
);
|
||||
RecordBatch::try_new(
|
||||
Arc::new(schema),
|
||||
vec![Arc::new(Int32Array::from(vec![id])), Arc::new(info)],
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let (dir, table) = new_table().await;
|
||||
let original = batch(1, "original", "label", "nested");
|
||||
table
|
||||
.add(original.clone())
|
||||
.mode(AddDataMode::Overwrite)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
reopen(&dir).await.schema().await.unwrap(),
|
||||
original.schema()
|
||||
);
|
||||
|
||||
let first = batch(2, "keep-✓", "label", "nested");
|
||||
let id = table
|
||||
.begin_write(AddDataMode::Overwrite)
|
||||
.await
|
||||
.unwrap()
|
||||
.id()
|
||||
.to_owned();
|
||||
reopen(&dir)
|
||||
.await
|
||||
.open_write(&id)
|
||||
.await
|
||||
.unwrap()
|
||||
.add(first.clone())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let worker = reopen(&dir).await.open_write(&id).await.unwrap();
|
||||
worker
|
||||
.add(batch(3, schema_value, field_value, nested_value))
|
||||
.idempotency_key("second-part")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let committer = reopen(&dir).await.open_write(&id).await.unwrap();
|
||||
let error = committer.commit().await.unwrap_err();
|
||||
assert!(error.to_string().contains("identical schemas"), "{error}");
|
||||
let before_commit = reopen(&dir).await;
|
||||
assert_eq!(before_commit.version().await.unwrap(), 2);
|
||||
assert_eq!(ids(&before_commit).await, [1]);
|
||||
assert_eq!(before_commit.schema().await.unwrap(), original.schema());
|
||||
|
||||
worker
|
||||
.add(batch(4, "keep-✓", "label", "nested"))
|
||||
.idempotency_key("second-part")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(committer.commit().await.unwrap().version, 3);
|
||||
let reopened = reopen(&dir).await;
|
||||
assert_eq!(reopened.schema().await.unwrap(), first.schema());
|
||||
assert_eq!(ids(&reopened).await, [2, 4]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn staged_write_validates_scope_empty_input_and_checked_out_handles() {
|
||||
let (dir, main) = new_table().await;
|
||||
let branch = main.create_branch("dev", 1_u64).await.unwrap();
|
||||
let write = branch.begin_write(AddDataMode::Append).await.unwrap();
|
||||
let err = main.open_write(write.id()).await.unwrap_err();
|
||||
assert!(err.to_string().contains("this table and branch"), "{err}");
|
||||
let db = connect(dir.path().to_str().unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let other = db.create_table("other", row(1)).execute().await.unwrap();
|
||||
assert!(
|
||||
other
|
||||
.open_write(write.id())
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("this table and branch")
|
||||
);
|
||||
assert!(
|
||||
main.open_write("invalid")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("invalid staged write_id")
|
||||
);
|
||||
|
||||
let worker = reopen(&dir)
|
||||
.await
|
||||
.checkout_branch("dev", None)
|
||||
.await
|
||||
.unwrap();
|
||||
let worker_write = worker.open_write(write.id()).await.unwrap();
|
||||
worker_write
|
||||
.add(RecordBatch::new_empty(row(1).schema()))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
worker_write
|
||||
.commit()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("no staged rows")
|
||||
);
|
||||
assert!(
|
||||
worker_write
|
||||
.add(row(2))
|
||||
.idempotency_key("")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("must be nonempty")
|
||||
);
|
||||
|
||||
let version = worker.version().await.unwrap();
|
||||
worker.checkout(version).await.unwrap();
|
||||
for error in [
|
||||
worker.begin_write(AddDataMode::Append).await.unwrap_err(),
|
||||
worker.open_write(write.id()).await.unwrap_err(),
|
||||
worker_write.add(row(2)).execute().await.unwrap_err(),
|
||||
worker_write.commit().await.unwrap_err(),
|
||||
worker_write.abort().await.unwrap_err(),
|
||||
] {
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("specific version is checked out"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
write.add(row(3)).execute().await.unwrap();
|
||||
assert_eq!(write.commit().await.unwrap().version, version + 1);
|
||||
assert_eq!(ids(&branch).await, [1, 3]);
|
||||
assert_eq!(ids(&main).await, [1]);
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case(AddDataMode::Append)]
|
||||
#[case(AddDataMode::Overwrite)]
|
||||
#[tokio::test]
|
||||
async fn staged_abort_deletes_data_and_can_recover_from_a_storage_error(#[case] mode: AddDataMode) {
|
||||
let (dir, table) = new_table().await;
|
||||
let initial = data_files(dir.path());
|
||||
let write = table.begin_write(mode).await.unwrap();
|
||||
write.add(row(2)).execute().await.unwrap();
|
||||
let after_stage = data_files(dir.path());
|
||||
let part = after_stage.difference(&initial).next().unwrap();
|
||||
let backup = dir.path().join("staged-data-backup");
|
||||
std::fs::rename(part, &backup).unwrap();
|
||||
let err = write.commit().await.unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
lancedb::Error::ObjectStore {
|
||||
source: object_store::Error::NotFound { .. }
|
||||
}
|
||||
),
|
||||
"{err}"
|
||||
);
|
||||
assert_eq!(table.version().await.unwrap(), 1);
|
||||
|
||||
// Deleting a directory as an object fails. The durable abort seal and its
|
||||
// transaction references must survive until another process can retry.
|
||||
std::fs::create_dir(part).unwrap();
|
||||
let err = write.abort().await.unwrap_err();
|
||||
assert!(matches!(err, lancedb::Error::ObjectStore { .. }), "{err}");
|
||||
std::fs::remove_dir(part).unwrap();
|
||||
std::fs::rename(&backup, part).unwrap();
|
||||
let reopened = reopen(&dir).await.open_write(write.id()).await.unwrap();
|
||||
reopened.abort().await.unwrap();
|
||||
reopened.abort().await.unwrap();
|
||||
assert_eq!(data_files(dir.path()), initial);
|
||||
assert_eq!(ids(&reopen(&dir).await).await, [1]);
|
||||
assert!(
|
||||
reopened
|
||||
.commit()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("aborted")
|
||||
);
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case(true)]
|
||||
#[case(false)]
|
||||
#[tokio::test]
|
||||
async fn staged_add_that_loses_finalization_discards_its_attempt(#[case] commit: bool) {
|
||||
let (dir, table) = new_table().await;
|
||||
let write = table.begin_write(AddDataMode::Append).await.unwrap();
|
||||
write.add(row(2)).execute().await.unwrap();
|
||||
|
||||
let worker = reopen(&dir).await.open_write(write.id()).await.unwrap();
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
let (resume, resumed) = tokio::sync::oneshot::channel();
|
||||
let late_part = stream::once(async move {
|
||||
started.send(()).unwrap();
|
||||
resumed.await.unwrap();
|
||||
Ok(row(3))
|
||||
});
|
||||
let input: SendableRecordBatchStream =
|
||||
Box::pin(SimpleRecordBatchStream::new(late_part, row(3).schema()));
|
||||
let adding = tokio::spawn(worker.add(input).execute());
|
||||
ready.await.unwrap();
|
||||
if commit {
|
||||
assert_eq!(write.commit().await.unwrap().version, 2);
|
||||
assert!(
|
||||
write
|
||||
.abort()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("committed at version 2")
|
||||
);
|
||||
} else {
|
||||
write.abort().await.unwrap();
|
||||
}
|
||||
resume.send(()).unwrap();
|
||||
let err = adding.await.unwrap().unwrap_err();
|
||||
let (expected_error, expected_ids) = if commit {
|
||||
("committed at version 2", vec![1, 2])
|
||||
} else {
|
||||
("aborted", vec![1])
|
||||
};
|
||||
assert!(err.to_string().contains(expected_error), "{err}");
|
||||
assert_eq!(data_files(dir.path()).len(), expected_ids.len());
|
||||
assert_eq!(ids(&reopen(&dir).await).await, expected_ids);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn staged_commit_and_abort_cannot_both_win() {
|
||||
let (dir, table) = new_table().await;
|
||||
let write = table.begin_write(AddDataMode::Append).await.unwrap();
|
||||
write.add(row(2)).execute().await.unwrap();
|
||||
let other = reopen(&dir).await.open_write(write.id()).await.unwrap();
|
||||
let (commit, abort) = tokio::join!(write.commit(), other.abort());
|
||||
match (commit, abort) {
|
||||
(Ok(result), Err(err)) => {
|
||||
assert_eq!(result.version, 2);
|
||||
let message = err.to_string();
|
||||
assert!(
|
||||
message.contains("committed at version 2") || message.contains("sealed for commit"),
|
||||
"{err}"
|
||||
);
|
||||
assert_eq!(ids(&reopen(&dir).await).await, [1, 2]);
|
||||
}
|
||||
(Err(err), Ok(())) => {
|
||||
let message = err.to_string();
|
||||
assert!(
|
||||
message.contains("abort") || message.contains("claim was released"),
|
||||
"{err}"
|
||||
);
|
||||
assert_eq!(ids(&reopen(&dir).await).await, [1]);
|
||||
}
|
||||
results => panic!("expected exactly one finalizer to succeed: {results:?}"),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user