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:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user