feat: add table.delta for version-to-version row changes (#5135)

Adds native `Table::delta(from_version, to_version=None)` and Python
sync/async `table.delta(...)` for version-to-version row changes.
`TableDelta` exposes streaming `inserted_rows()`, `updated_rows()`,
`upserted_rows()`, `deleted_row_ids()`, and `list_transactions()`.

Endpoints are resolved once on independent dataset handles.
`to_version=None` uses the table handle's visible snapshot, and the
handle's checkout is not changed. Only versions `>= 1` and tags on the
current branch are accepted; cross-branch tags, reversed ranges, version
0, and missing endpoints are rejected. Equal valid endpoints return
empty readers with the same schemas.

Row-level readers require stable row ids at both endpoints and report
the `storage_options={"new_table_enable_stable_row_ids": "true"}`
creation guidance when they are absent. `list_transactions()` does not
require stable row ids.

Row-level readers also fail closed when the range contains a `Restore`,
or when transaction history cannot prove the range is restore-free,
because restored rows can retain older row-version metadata that the
delta readers omit. The error directs consumers to a full rescan and
reinitializing the checkpoint at the range end version.
`list_transactions()` remains available for readable history. The
Versioning guide includes Python and Rust checkpoint-delta examples with
stable-row-ID setup and this Embedded limitation.

Embedded `branches.diff()` remains a separate API.

Refs OSS-2860
This commit is contained in:
Xuanwo
2026-11-21 06:41:38 +08:00
committed by GitHub
parent baea02eebd
commit 8dc03bd288
14 changed files with 1892 additions and 3 deletions
+4
View File
@@ -428,6 +428,8 @@ code that used the former LanceDB Enterprise-only argument order.
::: lancedb.table.Branches
::: lancedb.table.TableDelta
::: lancedb.RTEWriteSpec
## Functions and Jobs
@@ -1317,6 +1319,8 @@ Table hold your actual data as a collection of records / rows.
::: lancedb.table.AsyncBranches
::: lancedb.table.AsyncTableDelta
## Materialized Views (Asynchronous)
::: lancedb.materialized_view.AsyncMaterializedView
@@ -0,0 +1,41 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
def test_versioning_checkpoint_delta(tmp_db):
db = tmp_db
# --8<-- [start:versioning_checkpoint_delta]
table = db.create_table(
"checkpoint_delta_example",
[
{"id": 1, "author": "Richard", "quote": "Wubba Lubba Dub Dub!"},
{"id": 2, "author": "Morty", "quote": "Rick, what's going on?"},
],
storage_options={"new_table_enable_stable_row_ids": "true"},
mode="overwrite",
)
table.tags.create("baseline", table.version)
table.add([{"id": 3, "author": "Summer", "quote": "Whatever, Grandpa"}])
table.update(where="id = 2", values={"quote": "Aww geez, Rick!"})
table.delete("id = 1")
delta = table.delta("baseline")
print("inserted:", delta.inserted_rows().read_all()["id"].to_pylist())
print("updated:", delta.updated_rows().read_all()["id"].to_pylist())
print("deleted:", delta.deleted_row_ids().read_all()["_rowid"].to_pylist())
print(
"transactions:",
[transaction["operation"] for transaction in delta.list_transactions()],
)
# --8<-- [end:versioning_checkpoint_delta]
assert table.version == 4
assert delta.inserted_rows().read_all()["id"].to_pylist() == [3]
assert delta.updated_rows().read_all()["id"].to_pylist() == [2]
assert delta.deleted_row_ids().read_all().num_rows == 1
assert [transaction["operation"] for transaction in delta.list_transactions()] == [
"Append",
"Update",
"Delete",
]
+44
View File
@@ -87,6 +87,10 @@ import {
RsVersioningTags as RsVersioningTags,
RsVersioningMakeQuotesReader as RsVersioningMakeQuotesReader,
} from '/snippets/tables.mdx';
import {
PyVersioningCheckpointDelta as VersioningCheckpointDelta,
RsVersioningCheckpointDelta as RsVersioningCheckpointDelta,
} from '/snippets/table_delta_docs.mdx';
import {
PyMultimodalImports as MultimodalImports,
TsMultimodalImports as TsMultimodalImports,
@@ -1766,6 +1770,46 @@ Deleting a tag only removes the label, not the version it points to. After
deletion, the underlying table version becomes eligible for cleanup again.
</Note>
{/*
Draft until the checkpoint-delta API is released.
### Compute changes since a checkpoint {#versioning-checkpoint-delta}
Use `table.delta(from_version, to_version=None)` to stream the rows inserted,
updated, or deleted since a checkpoint. Tag the checkpoint version, then create
a delta from that tag. Omitting `to_version` uses the table's current visible
snapshot. The endpoints are fixed when the delta is created, so later writes or
tag moves do not change the comparison.
The row-level readers require stable row IDs at both endpoints. Create the table
with stable row IDs enabled, as shown below. If a table does not have them, the
row-level readers explain how to recreate it with the option. `list_transactions()`
reports the transactions in the range and works without stable row IDs.
This preview supports Python and Rust for LanceDB Embedded. TypeScript support
is a follow-up. The API accepts versions and tags on the current branch only,
and rejects tags that belong to another branch. LanceDB Enterprise tables do
not support row-level deltas.
A `Restore` can reintroduce rows with older row-version metadata that the delta
readers do not report as changed. For that reason, the row-level readers reject
a nonempty range that contains a `Restore`. They also reject a range whose
transaction history is incomplete, because they cannot rule out a hidden
`Restore`. Recompute the checkpoint with a full rescan and reinitialize it at
the range end version. `list_transactions()` remains available for the same
range. Branch-vs-main summaries remain a separate `branches.diff()` API.
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{VersioningCheckpointDelta}
</CodeBlock>
<CodeBlock filename="Rust" language="Rust" icon="rust">
{RsVersioningCheckpointDelta}
</CodeBlock>
</CodeGroup>
*/}
{/*
Draft until branching reaches early access.
+5
View File
@@ -0,0 +1,5 @@
{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */}
export const PyVersioningCheckpointDelta = "table = db.create_table(\n \"checkpoint_delta_example\",\n [\n {\"id\": 1, \"author\": \"Richard\", \"quote\": \"Wubba Lubba Dub Dub!\"},\n {\"id\": 2, \"author\": \"Morty\", \"quote\": \"Rick, what's going on?\"},\n ],\n storage_options={\"new_table_enable_stable_row_ids\": \"true\"},\n mode=\"overwrite\",\n)\ntable.tags.create(\"baseline\", table.version)\ntable.add([{\"id\": 3, \"author\": \"Summer\", \"quote\": \"Whatever, Grandpa\"}])\ntable.update(where=\"id = 2\", values={\"quote\": \"Aww geez, Rick!\"})\ntable.delete(\"id = 1\")\n\ndelta = table.delta(\"baseline\")\nprint(\"inserted:\", delta.inserted_rows().read_all()[\"id\"].to_pylist())\nprint(\"updated:\", delta.updated_rows().read_all()[\"id\"].to_pylist())\nprint(\"deleted:\", delta.deleted_row_ids().read_all()[\"_rowid\"].to_pylist())\nprint(\n \"transactions:\",\n [transaction[\"operation\"] for transaction in delta.list_transactions()],\n)\n";
export const RsVersioningCheckpointDelta = "use futures::TryStreamExt;\n\nlet table = db\n .create_table(\n \"checkpoint_delta_example\",\n make_quotes_reader(vec![\n (1, \"Richard\", \"Wubba Lubba Dub Dub!\"),\n (2, \"Morty\", \"Rick, what's going on?\"),\n ]),\n )\n .storage_option(\"new_table_enable_stable_row_ids\", \"true\")\n .execute()\n .await?;\n\nlet mut tags = table.tags().await?;\ntags.create(\"baseline\", table.version().await?).await?;\ntable\n .add(make_quotes_reader(vec![(3, \"Summer\", \"Whatever, Grandpa\")]))\n .execute()\n .await?;\ntable\n .update()\n .only_if(\"id = 2\")\n .column(\"quote\", \"'Aww geez, Rick!'\")\n .execute()\n .await?;\ntable.delete(\"id = 1\").await?;\n\nlet delta = table.delta(\"baseline\", None).await?;\nlet mut inserted = delta.inserted_rows().await?;\nwhile let Some(batch) = inserted.try_next().await? {\n println!(\"inserted: {:?}\", batch.column_by_name(\"id\"));\n}\nlet mut deleted = delta.deleted_row_ids().await?;\nwhile let Some(batch) = deleted.try_next().await? {\n println!(\"deleted row ids: {batch:?}\");\n}\nfor transaction in delta.list_transactions().await? {\n println!(\"{}\", transaction.operation.name());\n}\n";
+14
View File
@@ -649,6 +649,11 @@ class Table:
) -> Job: ...
async def list_versions(self) -> List[Dict[str, Any]]: ...
async def version(self) -> int: ...
async def delta(
self,
from_version: Union[int, str],
to_version: Optional[Union[int, str]] = None,
) -> TableDelta: ...
async def checkout(self, version: Union[int, str]): ...
async def checkout_latest(self): ...
async def _checkout_current(self) -> Table: ...
@@ -966,6 +971,15 @@ class ColumnOrdering(TypedDict):
ascending: bool
nulls_first: bool
class TableDelta:
def begin_version(self) -> int: ...
def end_version(self) -> int: ...
async def inserted_rows(self) -> RecordBatchStream: ...
async def updated_rows(self) -> RecordBatchStream: ...
async def upserted_rows(self) -> RecordBatchStream: ...
async def deleted_row_ids(self) -> RecordBatchStream: ...
async def list_transactions(self) -> List[Dict[str, Any]]: ...
class Query:
def where(self, filter: str): ...
def where_expr(self, expr: PyExpr): ...
+14
View File
@@ -85,6 +85,7 @@ from ..table import (
IndexStatistics,
Query,
Table,
TableDelta,
Tags,
)
from ..types import BaseTokenizerType, ScalarIndexType
@@ -287,6 +288,19 @@ class RemoteTable(Table):
"""List all versions of the table"""
return LOOP.run(self._table.list_versions())
def delta(
self,
from_version: int | str,
to_version: Optional[int | str] = None,
) -> TableDelta:
"""Compare two versions or tags.
Streamed version deltas are not supported by LanceDB Enterprise tables;
this raises ``NotImplementedError``.
"""
async_delta = LOOP.run(self._table.delta(from_version, to_version))
return TableDelta(async_delta._inner)
def to_arrow(self, *, blob_mode: BlobMode = "lazy") -> pa.Table:
"""to_arrow() is not supported in LanceDB Enterprise."""
validate_blob_mode(blob_mode)
+206 -1
View File
@@ -46,7 +46,7 @@ from ._blob import (
validate_blob_mode,
)
from .types import BlobMode
from lancedb.arrow import peek_reader
from lancedb.arrow import AsyncRecordBatchReader, peek_reader
from lancedb.sql import QueryParameters, to_parameter_batch
from lancedb.background_loop import LOOP, embedding_executor
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
@@ -1598,6 +1598,63 @@ class Table(ABC):
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
raise NotImplementedError("current_branch is not supported for this table type")
def delta(
self,
from_version: int | str,
to_version: Optional[int | str] = None,
) -> "TableDelta":
"""Compare two persisted versions of this table on its current branch.
``from_version`` is exclusive and ``to_version`` is inclusive. Both
accept a version number (starting at 1) or a tag on the current branch.
Omitting ``to_version`` uses the version this handle currently sees,
including a time-travel checkout. Endpoints are resolved once when this
method is called, so moving a tag or advancing the table later does not
change the delta, and this table's checkout state is left untouched.
The returned [TableDelta][lancedb.table.TableDelta] streams inserted,
updated, upserted, and deleted rows. Those row-level readers require
stable row ids at both endpoints; create the table with
``storage_options={"new_table_enable_stable_row_ids": "true"}`` to
enable them. ``list_transactions()`` works without stable row ids.
Equal valid versions produce empty readers with the same schemas.
Reversed ranges, version 0, missing versions or tags, and tags from a
different branch are rejected. A row-level range that contains a
``Restore``, or whose transaction history is incomplete, is rejected
because the restored snapshot can retain older row-version metadata that
the delta readers would omit; recompute the checkpoint with a full
rescan and reinitialize it at the end version. Remote tables raise
``NotImplementedError``.
Parameters
----------
from_version: int | str
The version or tag to compare from (exclusive).
to_version: int | str, optional
The version or tag to compare to (inclusive). Defaults to the
currently visible version.
Examples
--------
>>> import lancedb
>>> db = lancedb.connect("memory://")
>>> table = db.create_table(
... "delta_example",
... [{"id": 1}, {"id": 2}],
... storage_options={"new_table_enable_stable_row_ids": "true"},
... )
>>> table.tags.create("baseline", table.version)
>>> _ = table.add([{"id": 3}])
>>> delta = table.delta("baseline")
>>> inserted = delta.inserted_rows().read_all()
>>> inserted["id"].to_pylist()
[3]
>>> [transaction["operation"] for transaction in delta.list_transactions()]
['Append']
"""
raise NotImplementedError("delta is not supported for this table type")
def __len__(self) -> int:
"""The number of rows in this Table"""
return self.count_rows(None)
@@ -4618,6 +4675,18 @@ class LanceTable(Table):
"""List all versions of the table"""
return LOOP.run(self._table.list_versions())
def delta(
self,
from_version: int | str,
to_version: Optional[int | str] = None,
) -> "TableDelta":
"""Compare two versions or tags.
See [Table.delta][lancedb.table.Table.delta].
"""
async_delta = LOOP.run(self._table.delta(from_version, to_version))
return TableDelta(async_delta._inner)
@property
def version(self) -> int:
"""Get the current version of the table"""
@@ -9764,6 +9833,20 @@ class AsyncTable:
return versions
async def delta(
self,
from_version: int | str,
to_version: Optional[int | str] = None,
) -> "AsyncTableDelta":
"""Compare two versions or tags.
See [Table.delta][lancedb.table.Table.delta] for endpoint, stable-row-id,
and branch-tag semantics. The returned
[AsyncTableDelta][lancedb.table.AsyncTableDelta] streams
``AsyncRecordBatchReader`` values.
"""
return AsyncTableDelta(await self._inner.delta(from_version, to_version))
async def checkout(self, version: int | str):
"""
Checks out a specific version of the Table
@@ -10569,6 +10652,128 @@ class Branches:
return self._parent._wrap_branch_handle(async_table, version)
class TableDelta:
"""Streaming row changes between two table versions.
Created by [Table.delta][lancedb.table.Table.delta]. The endpoints are
fixed when the delta is created.
Row-level readers require stable row ids at both endpoints. Create the
table with ``storage_options={"new_table_enable_stable_row_ids": "true"}``
to enable them. [list_transactions][lancedb.table.TableDelta.list_transactions]
works without stable row ids.
A nonempty range that contains a ``Restore``, or whose transaction history
is incomplete, rejects the row-level readers. Recompute the checkpoint with
a full rescan and reinitialize it at the end version; transaction history
remains available.
"""
def __init__(self, inner: Any):
self._inner = inner
self._async = AsyncTableDelta(inner)
@property
def begin_version(self) -> int:
"""The version this delta starts from (exclusive)."""
return self._inner.begin_version()
@property
def end_version(self) -> int:
"""The version this delta ends at (inclusive)."""
return self._inner.end_version()
def inserted_rows(self) -> pa.RecordBatchReader:
"""Stream rows inserted in ``(begin_version, end_version]``.
Each batch carries the table columns plus ``_rowid``,
``_row_created_at_version``, and ``_row_last_updated_at_version``.
"""
return _record_batch_reader(LOOP.run(self._async.inserted_rows()))
def updated_rows(self) -> pa.RecordBatchReader:
"""Stream rows updated in ``(begin_version, end_version]``.
Newly inserted rows are excluded; use
[upserted_rows][lancedb.table.TableDelta.upserted_rows] for both.
"""
return _record_batch_reader(LOOP.run(self._async.updated_rows()))
def upserted_rows(self) -> pa.RecordBatchReader:
"""Stream inserted and updated rows in ``(begin_version, end_version]``."""
return _record_batch_reader(LOOP.run(self._async.upserted_rows()))
def deleted_row_ids(self) -> pa.RecordBatchReader:
"""Stream the ``_rowid`` values of rows deleted in the range.
Each batch carries one ``_rowid`` column of type ``uint64``. Deleted
rows are not reconstructed from earlier versions.
"""
return _record_batch_reader(LOOP.run(self._async.deleted_row_ids()))
def list_transactions(self) -> List[Dict[str, Any]]:
"""List transactions committed in ``(begin_version, end_version]``.
Each item has ``read_version``, ``uuid``, ``operation``, ``tag``, and
``transaction_properties``. Unlike row readers, this works without
stable row ids.
"""
return LOOP.run(self._async.list_transactions())
class AsyncTableDelta:
"""Async streaming row changes between two table versions.
Created by [AsyncTable.delta][lancedb.table.AsyncTable.delta]. See
[TableDelta][lancedb.table.TableDelta] for the endpoint and stable-row-id
contract.
"""
def __init__(self, inner: Any):
self._inner = inner
@property
def begin_version(self) -> int:
"""The version this delta starts from (exclusive)."""
return self._inner.begin_version()
@property
def end_version(self) -> int:
"""The version this delta ends at (inclusive)."""
return self._inner.end_version()
async def inserted_rows(self) -> AsyncRecordBatchReader:
"""Stream rows inserted in ``(begin_version, end_version]``."""
return AsyncRecordBatchReader(await self._inner.inserted_rows())
async def updated_rows(self) -> AsyncRecordBatchReader:
"""Stream rows updated in ``(begin_version, end_version]``."""
return AsyncRecordBatchReader(await self._inner.updated_rows())
async def upserted_rows(self) -> AsyncRecordBatchReader:
"""Stream inserted and updated rows in ``(begin_version, end_version]``."""
return AsyncRecordBatchReader(await self._inner.upserted_rows())
async def deleted_row_ids(self) -> AsyncRecordBatchReader:
"""Stream the ``_rowid`` values of rows deleted in the range."""
return AsyncRecordBatchReader(await self._inner.deleted_row_ids())
async def list_transactions(self) -> List[Dict[str, Any]]:
"""List transactions committed in ``(begin_version, end_version]``."""
return await self._inner.list_transactions()
def _record_batch_reader(stream) -> pa.RecordBatchReader:
def iter_sync():
try:
while True:
yield LOOP.run(stream.__anext__())
except StopAsyncIteration:
return
return pa.RecordBatchReader.from_batches(stream.schema, iter_sync())
class AsyncTags:
"""
Async table tag manager.
+264
View File
@@ -1373,6 +1373,270 @@ def test_versioning(mem_db: DBConnection):
assert len(table) == 2
def test_delta_streams_and_pins_endpoints(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table(
"delta",
data=[
{"id": 1, "value": 0},
{"id": 2, "value": 0},
],
storage_options={"new_table_enable_stable_row_ids": "true"},
)
table.add([{"id": 3, "value": 0}])
table.tags.create("baseline", 2)
table.update(where="id = 1", values_sql={"value": "value + 10"})
table.delete("id = 2")
assert table.version == 4
delta = table.delta(1)
assert delta.begin_version == 1
assert delta.end_version == 4
inserted = delta.inserted_rows().read_all()
assert inserted["id"].to_pylist() == [3]
assert inserted.schema.names == [
"id",
"value",
"_rowid",
"_row_created_at_version",
"_row_last_updated_at_version",
]
updated = delta.updated_rows().read_all()
assert updated["id"].to_pylist() == [1]
assert updated["value"].to_pylist() == [10]
upserted = delta.upserted_rows().read_all()
assert sorted(upserted["id"].to_pylist()) == [1, 3]
deleted = delta.deleted_row_ids().read_all()
assert deleted.schema.names == ["_rowid"]
assert deleted.schema.field("_rowid").type == pa.uint64()
assert deleted.num_rows == 1
transactions = delta.list_transactions()
assert [transaction["operation"] for transaction in transactions] == [
"Append",
"Update",
"Delete",
]
assert transactions[0]["read_version"] == 1
# Tags are resolved on the current branch and can be either endpoint.
from_tag = table.delta("baseline")
assert from_tag.begin_version == 2
assert from_tag.end_version == 4
assert from_tag.updated_rows().read_all()["id"].to_pylist() == [1]
to_tag = table.delta(1, "baseline")
assert to_tag.end_version == 2
assert to_tag.inserted_rows().read_all()["id"].to_pylist() == [3]
# Equal valid versions keep the reader schemas even when no rows change.
equal = table.delta(2, 2)
empty_inserted = equal.inserted_rows().read_all()
assert empty_inserted.num_rows == 0
assert empty_inserted.schema == inserted.schema
empty_deleted = equal.deleted_row_ids().read_all()
assert empty_deleted.num_rows == 0
assert empty_deleted.schema.names == ["_rowid"]
# Reversed, zero, missing, and missing-tag endpoints are input errors.
with pytest.raises(ValueError, match="newer than"):
table.delta(4, 2)
with pytest.raises(ValueError, match="start at 1"):
table.delta(0)
with pytest.raises(ValueError, match="does not exist"):
table.delta(999)
with pytest.raises(ValueError, match="does not exist"):
table.delta("missing-tag")
# An omitted target follows the visible checkout and leaves the shared
# checkout in place.
table.checkout(2)
checked_out = table.delta(1)
assert checked_out.end_version == 2
assert checked_out.inserted_rows().read_all()["id"].to_pylist() == [3]
assert table.version == 2
# An explicit target works from a pinned handle without moving it.
explicit = table.delta(1, 3)
assert explicit.updated_rows().read_all()["id"].to_pylist() == [1]
assert table.version == 2
table.checkout_latest()
assert table.version == 4
@pytest.mark.parametrize("mutation", ["update", "delete"])
def test_delta_rejects_restore_ranges(tmp_path, mutation):
table = lancedb.connect(tmp_path).create_table(
"restore_delta",
[{"id": 1, "value": 0}],
storage_options={"new_table_enable_stable_row_ids": "true"},
)
if mutation == "update":
table.update(values={"value": 10})
else:
table.delete("id = 1")
assert table.version == 2
table.restore(1)
assert table.version == 3
assert table.to_arrow().to_pylist() == [{"id": 1, "value": 0}]
restore_range = table.delta(2, 3)
assert [tx["operation"] for tx in restore_range.list_transactions()] == ["Restore"]
for reader in (
restore_range.inserted_rows,
restore_range.updated_rows,
restore_range.upserted_rows,
restore_range.deleted_row_ids,
):
with pytest.raises(ValueError) as exc_info:
reader()
message = str(exc_info.value)
assert "Restore" in message
assert "full rescan" in message
assert "reinitialize" in message
# A restore in the middle of the range is still unverifiable.
table.add([{"id": 2, "value": 0}])
assert table.version == 4
with pytest.raises(ValueError, match="Restore"):
table.delta(2, 4).upserted_rows()
# A restore at the exclusive boundary is the base snapshot, so later
# changes remain usable.
after_restore = table.delta(3, 4)
assert after_restore.inserted_rows().read_all()["id"].to_pylist() == [2]
assert [tx["operation"] for tx in after_restore.list_transactions()] == ["Append"]
# Equal endpoints remain empty and do not run the restore guard.
equal = table.delta(3, 3)
assert equal.inserted_rows().read_all().num_rows == 0
def test_delta_rejects_restore_after_same_uri_recreate(tmp_path):
stable = {"new_table_enable_stable_row_ids": "true"}
old_db = lancedb.connect(tmp_path)
old = old_db.create_table("t", [{"id": 1, "value": 0}], storage_options=stable)
old.add([{"id": 2, "value": 0}])
old.add([{"id": 3, "value": 0}])
assert [tx["operation"] for tx in old.delta(2, 3).list_transactions()] == ["Append"]
writer_db = lancedb.connect(tmp_path)
writer_db.drop_table("t")
schema = pa.schema(
[("id", pa.int32()), ("value", pa.int32())],
metadata={"padding": "x" * (256 * 1024)},
)
recreated = writer_db.create_table(
"t",
pa.Table.from_pylist([{"id": 1, "value": 0}], schema=schema),
storage_options=stable,
)
recreated.update(values={"value": 10})
recreated.restore(1)
assert [tx["operation"] for tx in recreated.delta(2, 3).list_transactions()] == [
"Restore"
]
delta = old_db.open_table("t").delta(2, 3)
assert [tx["operation"] for tx in delta.list_transactions()] == ["Restore"]
with pytest.raises(ValueError, match="Restore"):
delta.upserted_rows()
def test_delta_requires_stable_row_ids(mem_db: DBConnection):
table = mem_db.create_table("delta_no_stable", data=[{"id": 1}])
table.add([{"id": 2}])
delta = table.delta(1)
for reader in (
delta.inserted_rows,
delta.updated_rows,
delta.upserted_rows,
delta.deleted_row_ids,
):
with pytest.raises(ValueError) as exc_info:
reader()
message = str(exc_info.value)
assert "new_table_enable_stable_row_ids" in message
assert "list_transactions" in message
# Transactions remain available without stable row ids.
transactions = delta.list_transactions()
assert [transaction["operation"] for transaction in transactions] == ["Append"]
# Equal endpoints need no row lineage, so they are empty rather than
# rejected.
version = table.version
equal = table.delta(version, version)
assert equal.inserted_rows().read_all().num_rows == 0
assert equal.deleted_row_ids().read_all().num_rows == 0
def test_delta_rejects_cross_branch_tags(tmp_path):
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
table = db.create_table(
"delta_branches",
data=[{"id": 0}],
storage_options={"new_table_enable_stable_row_ids": "true"},
)
branch = table.branches.create("exp")
branch.add([{"id": 1}])
table.add([{"id": 100}, {"id": 101}, {"id": 102}])
assert branch.version == table.version
table.tags.create("main_tag", table.version)
branch.tags.create("exp_tag", branch.version)
# The same-branch tag resolves through the branch, not main's data at the
# same version number.
delta = branch.delta(1, "exp_tag")
assert delta.inserted_rows().read_all()["id"].to_pylist() == [1]
# Cross-branch tags are rejected even though the version number exists on
# both branches.
with pytest.raises(ValueError) as exc_info:
branch.delta("main_tag")
message = str(exc_info.value)
assert "main_tag" in message
assert "main" in message
assert "exp" in message
with pytest.raises(ValueError, match="exp_tag"):
table.delta("exp_tag")
@pytest.mark.asyncio
async def test_async_delta(tmp_path):
db = await lancedb.connect_async(tmp_path)
table = await db.create_table(
"async_delta",
data=[{"id": 1}],
storage_options={"new_table_enable_stable_row_ids": "true"},
)
await table.add([{"id": 2}])
delta = await table.delta(1)
assert delta.begin_version == 1
assert delta.end_version == 2
reader = await delta.inserted_rows()
inserted = await reader.read_all()
assert inserted[0]["id"].to_pylist() == [2]
transactions = await delta.list_transactions()
assert [transaction["operation"] for transaction in transactions] == ["Append"]
equal = await table.delta(2, 2)
reader = await equal.inserted_rows()
assert await reader.read_all() == []
def test_tags(mem_db: DBConnection):
table = mem_db.create_table(
"test",
+1
View File
@@ -98,6 +98,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::TableDelta>()?;
m.add_class::<crate::oauth::PyOAuthSession>()?;
m.add_class::<crate::oauth::PySessionStatus>()?;
m.add_class::<crate::oauth::PySessionLogout>()?;
+115 -2
View File
@@ -29,10 +29,10 @@ use lancedb::blob::{BlobDescriptor, BlobFile, BlobRangeRequest};
use lancedb::connection::LanceFileVersion;
use lancedb::index::scalar::FtsIndexBuilder;
use lancedb::table::{
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration,
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, DeltaRef, Duration,
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig,
FunctionRefreshPodResources, FunctionWorkerResourceBudget, IndexRemapMode, NewColumnTransform,
Ref, RefreshColumnOptions, Table as LanceDbTable,
Ref, RefreshColumnOptions, Table as LanceDbTable, TableDelta as LanceDbTableDelta,
};
use lancedb::tokenize as lancedb_tokenize;
use pyo3::{
@@ -2075,6 +2075,22 @@ impl Table {
)
}
#[pyo3(signature = (from_version, to_version=None))]
pub fn delta(
self_: PyRef<'_, Self>,
from_version: LanceVersion,
to_version: Option<LanceVersion>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let delta = inner
.delta(from_version, to_version.map(Into::into))
.await
.infer_error()?;
Ok(TableDelta::new(delta))
})
}
pub fn list_versions(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
@@ -3244,6 +3260,103 @@ pub enum LanceVersion {
Tag(String),
}
impl From<LanceVersion> for DeltaRef {
fn from(version: LanceVersion) -> Self {
match version {
LanceVersion::Version(version) => DeltaRef::Version(version),
LanceVersion::Tag(tag) => DeltaRef::Tag(tag),
}
}
}
/// Streaming row changes between two table versions.
#[pyclass]
pub struct TableDelta {
inner: Arc<LanceDbTableDelta>,
}
impl TableDelta {
fn new(inner: LanceDbTableDelta) -> Self {
Self {
inner: Arc::new(inner),
}
}
}
#[pymethods]
impl TableDelta {
/// The version this delta starts from (exclusive).
pub fn begin_version(&self) -> u64 {
self.inner.begin_version()
}
/// The version this delta ends at (inclusive).
pub fn end_version(&self) -> u64 {
self.inner.end_version()
}
pub fn inserted_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
let stream = inner.inserted_rows().await.infer_error()?;
Ok(crate::arrow::RecordBatchStream::new(stream.into()))
})
}
pub fn updated_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
let stream = inner.updated_rows().await.infer_error()?;
Ok(crate::arrow::RecordBatchStream::new(stream.into()))
})
}
pub fn upserted_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
let stream = inner.upserted_rows().await.infer_error()?;
Ok(crate::arrow::RecordBatchStream::new(stream.into()))
})
}
pub fn deleted_row_ids(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
let stream = inner.deleted_row_ids().await.infer_error()?;
Ok(crate::arrow::RecordBatchStream::new(stream.into()))
})
}
pub fn list_transactions(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
let transactions = inner.list_transactions().await.infer_error()?;
Python::attach(|py| {
let output = PyList::empty(py);
for transaction in transactions {
let item = PyDict::new(py);
item.set_item("read_version", transaction.read_version)?;
item.set_item("uuid", transaction.uuid)?;
item.set_item("operation", transaction.operation.name())?;
item.set_item("tag", transaction.tag)?;
match transaction.transaction_properties {
Some(properties) => {
let py_properties = PyDict::new(py);
for (key, value) in properties.iter() {
py_properties.set_item(key, value)?;
}
item.set_item("transaction_properties", py_properties)?;
}
None => item.set_item("transaction_properties", py.None())?,
}
output.append(item)?;
}
Ok(output.unbind())
})
})
}
}
#[derive(FromPyObject)]
#[pyo3(from_item_all)]
pub struct MergeInsertParams {
+13
View File
@@ -5251,6 +5251,19 @@ mod tests {
}
}
#[tokio::test]
async fn test_delta_not_supported() {
let table = Table::new_with_handler("my_table", |_| -> http::Response<String> {
panic!("table.delta must not send a remote request")
});
let error = table.delta(1u64, None).await.unwrap_err();
assert!(
matches!(error, Error::NotSupported { .. }),
"expected NotSupported, got {error:?}"
);
}
#[tokio::test]
async fn test_version() {
let table = Table::new_with_handler("my_table", |request| {
+67
View File
@@ -84,6 +84,7 @@ mod create_index;
pub mod datafusion;
pub(crate) mod dataset;
pub mod delete;
pub mod delta;
pub mod freshness;
pub mod function_column_status;
pub mod merge;
@@ -114,6 +115,7 @@ pub use computed_columns::{
ComputedColumn, ComputedColumnKind, computed_column_from_field, computed_columns,
};
pub use delete::DeleteResult;
pub use delta::{DeltaRef, TableDelta};
pub use function_column_status::{
FunctionColumnAutoRefreshBlockedReason, FunctionColumnAutoRefreshState,
FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus,
@@ -1071,6 +1073,20 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
async fn drop_columns(&self, columns: &[&str]) -> Result<DropColumnsResult>;
/// Get the version of the table.
async fn version(&self) -> Result<u64>;
/// Compare two persisted versions on this table's current branch.
///
/// The default implementation returns [`Error::NotSupported`]; table types
/// without a local Lance dataset, such as remote tables, cannot stream row
/// changes.
async fn delta(
&self,
_from_version: DeltaRef,
_to_version: Option<DeltaRef>,
) -> Result<TableDelta> {
Err(Error::NotSupported {
message: "table.delta is only supported on LanceDB Embedded tables".into(),
})
}
/// Return a new table handle pinned to the exact revision currently visible.
async fn checkout_current(&self) -> Result<Arc<dyn BaseTable>> {
Err(Error::NotSupported {
@@ -2923,6 +2939,48 @@ impl Table {
self.inner.version().await
}
/// Compare two persisted versions of this table on its current branch.
///
/// `from_version` is exclusive and `to_version` is inclusive. Both accept
/// a version number (starting at 1) or a tag on the current branch.
/// Omitting `to_version` uses the version this handle currently sees,
/// including a time-travel [`Self::checkout`]. The endpoints are resolved
/// once when this method is called, so moving a tag or advancing the table
/// later does not change the delta, and the table's own checkout state is
/// left untouched.
///
/// The returned [`TableDelta`] streams the rows inserted, updated,
/// upserted, or deleted between the endpoints. Those row-level readers
/// require stable row ids at both endpoints; create the table with
/// `storage_options={"new_table_enable_stable_row_ids": "true"}` to enable
/// them. [`TableDelta::list_transactions`] works without stable row ids.
/// Equal valid versions produce empty streams with the same schemas.
///
/// Reversed ranges, version 0, missing versions or tags, and tags from a
/// different branch are rejected. A row-level range that contains a
/// `Restore`, or whose transaction history is incomplete, is rejected
/// because the restored snapshot can retain older row-version metadata that
/// the delta readers would omit; recompute the checkpoint with a full
/// rescan and reinitialize it at the end version. Remote tables return
/// [`Error::NotSupported`].
///
/// ```no_run
/// # use lancedb::table::DeltaRef;
/// # async fn example(table: &lancedb::Table) -> Result<(), Box<dyn std::error::Error>> {
/// let delta = table.delta(1u64, Some(DeltaRef::Version(table.version().await?))).await?;
/// let _inserted = delta.inserted_rows().await?;
/// let transactions = delta.list_transactions().await?;
/// # Ok(())
/// # }
/// ```
pub async fn delta(
&self,
from_version: impl Into<DeltaRef>,
to_version: Option<DeltaRef>,
) -> Result<TableDelta> {
self.inner.delta(from_version.into(), to_version).await
}
/// Return a new table handle pinned to the exact revision currently visible.
///
/// This is used when asynchronous preparation must remain consistent with
@@ -4270,6 +4328,15 @@ impl BaseTable for NativeTable {
Ok(self.dataset.get().await?.version().version)
}
async fn delta(
&self,
from_version: DeltaRef,
to_version: Option<DeltaRef>,
) -> Result<TableDelta> {
let visible = self.dataset.get().await?;
TableDelta::from_visible_snapshot(&visible, from_version, to_version).await
}
async fn checkout_current(&self) -> Result<Arc<dyn BaseTable>> {
let current = self.dataset.get().await?;
let dataset = dataset::DatasetConsistencyWrapper::new_time_travel(
+969
View File
@@ -0,0 +1,969 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
//! Streaming row changes between two persisted table versions.
use std::sync::Arc;
use arrow_array::RecordBatch;
use arrow_schema::{Schema as ArrowSchema, SchemaRef};
use datafusion_common::DataFusionError;
use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
use futures::stream;
use lance::Dataset;
use lance::dataset::delta::{DatasetDelta, DatasetDeltaBuilder};
use lance::dataset::scanner::DatasetRecordBatchStream;
use lance::dataset::transaction::{Operation, Transaction};
use lance_core::{ROW_CREATED_AT_VERSION_FIELD, ROW_ID_FIELD, ROW_LAST_UPDATED_AT_VERSION_FIELD};
use crate::error::{Error, Result};
/// A version or tag that identifies one end of a [`TableDelta`].
///
/// Version numbers start at 1. Tags are resolved on the table handle's current
/// branch; a tag that belongs to another branch is rejected instead of being
/// followed to that branch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeltaRef {
/// A persisted table version on the current branch.
Version(u64),
/// A tag that points at a version on the current branch.
Tag(String),
}
impl From<u64> for DeltaRef {
fn from(version: u64) -> Self {
Self::Version(version)
}
}
impl From<&str> for DeltaRef {
fn from(tag: &str) -> Self {
Self::Tag(tag.to_string())
}
}
impl From<String> for DeltaRef {
fn from(tag: String) -> Self {
Self::Tag(tag)
}
}
/// Streaming row changes between two versions of an embedded LanceDB table.
///
/// A delta is created by [`crate::Table::delta`]. The two endpoints are
/// resolved when the delta is created, so moving a tag or advancing the table
/// afterwards does not change what the delta compares.
///
/// Row-level readers require stable row ids at both endpoints. Tables created
/// with the default local settings do not enable them; create the table with
/// `storage_options={"new_table_enable_stable_row_ids": "true"}` to use
/// [`Self::inserted_rows`], [`Self::updated_rows`], [`Self::upserted_rows`],
/// and [`Self::deleted_row_ids`]. [`Self::list_transactions`] works without
/// stable row ids.
///
/// A nonempty range that contains a `Restore` rejects the row-level readers,
/// because a restored snapshot can retain older row-version metadata that the
/// delta readers would omit. The same happens when transaction history in the
/// range is incomplete. Recompute the checkpoint with a full rescan and
/// reinitialize it at the end version; [`Self::list_transactions`] remains
/// available.
pub struct TableDelta {
/// The resolved start endpoint. Kept alongside the numeric version so the
/// handle remains pinned even if the source table is checked out or moves
/// forward later.
begin: Dataset,
/// The resolved end endpoint. Kept for schema construction and to pin the
/// endpoint independently of the table handle.
end: Dataset,
begin_version: u64,
end_version: u64,
delta: DatasetDelta,
transactions: Vec<Transaction>,
row_change_error: Option<String>,
row_schema: SchemaRef,
deleted_schema: SchemaRef,
}
impl std::fmt::Debug for TableDelta {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TableDelta")
.field("begin_version", &self.begin_version)
.field("end_version", &self.end_version)
.finish_non_exhaustive()
}
}
impl TableDelta {
/// Resolve both endpoints from the snapshot currently visible through
/// `visible`. The table wrapper is not touched, so its checkout state and
/// version stay exactly as they were.
pub(crate) async fn from_visible_snapshot(
visible: &Dataset,
from_version: DeltaRef,
to_version: Option<DeltaRef>,
) -> Result<Self> {
let begin = resolve_endpoint(visible, from_version, "from_version").await?;
let end = match to_version {
Some(to_version) => resolve_endpoint(visible, to_version, "to_version").await?,
// The visible snapshot is the implicit target, including when the
// table handle is in time-travel mode.
None => visible.clone(),
};
let begin_version = begin.version().version;
let end_version = end.version().version;
if begin_version > end_version {
return Err(Error::InvalidInput {
message: format!(
"delta begin version {begin_version} is newer than end version {end_version}; \
from_version must be less than or equal to to_version"
),
});
}
let delta = DatasetDeltaBuilder::new(end.clone())
.with_begin_version(begin_version)
.with_end_version(end_version)
.build()?;
// Read the pinned range once so every row reader shares the same
// Restore/history check instead of scanning it again. Use the end
// dataset because its branch is the one the delta is pinned to.
let (transactions, row_change_error) = if begin_version == end_version {
(Vec::new(), None)
} else {
read_range_history(&end, begin_version, end_version).await?
};
Ok(Self {
row_schema: row_change_schema(&end),
deleted_schema: deleted_row_ids_schema(),
begin,
end,
begin_version,
end_version,
delta,
transactions,
row_change_error,
})
}
/// The version this delta starts from (exclusive).
pub fn begin_version(&self) -> u64 {
self.begin_version
}
/// The version this delta ends at (inclusive).
pub fn end_version(&self) -> u64 {
self.end_version
}
/// Stream rows inserted in `(begin_version, end_version]`.
///
/// Each batch carries the table columns plus `_rowid`,
/// `_row_created_at_version`, and `_row_last_updated_at_version`, read as
/// of the end version.
pub async fn inserted_rows(&self) -> Result<DatasetRecordBatchStream> {
self.scan_rows(DeltaRowChange::Inserted).await
}
/// Stream rows updated in `(begin_version, end_version]`.
///
/// Newly inserted rows are excluded; see [`Self::upserted_rows`] for both.
/// Each batch carries the table columns plus `_rowid`,
/// `_row_created_at_version`, and `_row_last_updated_at_version`, read as
/// of the end version.
pub async fn updated_rows(&self) -> Result<DatasetRecordBatchStream> {
self.scan_rows(DeltaRowChange::Updated).await
}
/// Stream inserted and updated rows in `(begin_version, end_version]`.
///
/// Each batch carries the table columns plus `_rowid`,
/// `_row_created_at_version`, and `_row_last_updated_at_version`, read as
/// of the end version.
pub async fn upserted_rows(&self) -> Result<DatasetRecordBatchStream> {
self.scan_rows(DeltaRowChange::Upserted).await
}
/// Stream the ids of rows deleted in `(begin_version, end_version]`.
///
/// Each batch carries one `_rowid` column of type `UInt64`. Deleted rows
/// are not reconstructed from earlier versions.
pub async fn deleted_row_ids(&self) -> Result<DatasetRecordBatchStream> {
if self.begin_version == self.end_version {
return Ok(empty_stream(self.deleted_schema.clone()));
}
self.ensure_row_changes_allowed()?;
Ok(self.delta.get_deleted_row_ids().await?)
}
/// List the transactions committed in `(begin_version, end_version]`.
///
/// Unlike the row readers, this does not require stable row ids. A version
/// with no readable transaction entry is skipped; the returned list keeps
/// any transactions that are available.
pub async fn list_transactions(&self) -> Result<Vec<Transaction>> {
Ok(self.transactions.clone())
}
async fn scan_rows(&self, change: DeltaRowChange) -> Result<DatasetRecordBatchStream> {
if self.begin_version == self.end_version {
return Ok(empty_stream(self.row_schema.clone()));
}
self.ensure_row_changes_allowed()?;
let rows = match change {
DeltaRowChange::Inserted => self.delta.get_inserted_rows().await?,
DeltaRowChange::Updated => self.delta.get_updated_rows().await?,
DeltaRowChange::Upserted => self.delta.get_upserted_rows().await?,
};
Ok(rows)
}
fn ensure_row_changes_allowed(&self) -> Result<()> {
if let Some(message) = &self.row_change_error {
return Err(Error::InvalidInput {
message: message.clone(),
});
}
self.ensure_stable_row_ids()
}
fn ensure_stable_row_ids(&self) -> Result<()> {
if self.begin.manifest().uses_stable_row_ids() && self.end.manifest().uses_stable_row_ids()
{
return Ok(());
}
Err(Error::InvalidInput {
message: format!(
"row-level delta requires stable row ids at both endpoints (versions {} and {}); \
create the table with storage_options={{\"new_table_enable_stable_row_ids\": \"true\"}} \
to use inserted_rows(), updated_rows(), upserted_rows(), or deleted_row_ids(). \
list_transactions() is available without stable row ids",
self.begin_version, self.end_version
),
})
}
}
/// Read the pinned range's transactions through Lance's lineage-aware,
/// cache-bypassing path. This matters when a table is dropped and recreated at
/// the same URI in the same session: `read_transaction()` can return the old
/// incarnation's transaction for a version number.
async fn read_range_history(
end: &Dataset,
begin_version: u64,
end_version: u64,
) -> Result<(Vec<Transaction>, Option<String>)> {
let mut transactions = Vec::new();
let mut missing_transactions = 0u64;
let mut has_restore = false;
for version in (begin_version + 1)..=end_version {
let record = end.read_version_transaction(version).await?;
match record.transaction {
Some(transaction) => {
if matches!(&transaction.operation, Operation::Restore { .. }) {
has_restore = true;
}
transactions.push(transaction);
}
// A missing entry is readable as a gap for list_transactions(), but
// it cannot prove the version was not a Restore.
None => missing_transactions += 1,
}
}
let row_change_error = row_change_error(
begin_version,
end_version,
has_restore,
missing_transactions,
);
Ok((transactions, row_change_error))
}
fn row_change_error(
begin_version: u64,
end_version: u64,
has_restore: bool,
missing_transactions: u64,
) -> Option<String> {
if begin_version == end_version {
return None;
}
if has_restore {
return Some(format!(
"row-level table.delta cannot verify versions ({begin_version}, {end_version}] \
because the range contains a Restore; a restore can reintroduce rows with older \
row-version metadata that the delta readers omit. Recompute the checkpoint with a \
full rescan and reinitialize it at version {end_version}, or use \
list_transactions() to inspect the range"
));
}
if missing_transactions > 0 {
let expected_transactions = end_version - begin_version;
return Some(format!(
"row-level table.delta cannot verify versions ({begin_version}, {end_version}] \
because transaction history is missing for {missing_transactions} of \
{expected_transactions} versions; a Restore may be hidden. Recompute the checkpoint \
with a full rescan and reinitialize it at version {end_version}, or use \
list_transactions() to inspect the available history"
));
}
None
}
#[derive(Clone, Copy)]
enum DeltaRowChange {
Inserted,
Updated,
Upserted,
}
async fn resolve_endpoint(visible: &Dataset, endpoint: DeltaRef, field: &str) -> Result<Dataset> {
let current_branch = visible.manifest().branch.clone();
match endpoint {
DeltaRef::Version(version) => {
if version == 0 {
return Err(Error::InvalidInput {
message: format!(
"{field} version 0 is not a persisted table version; delta versions start at 1"
),
});
}
visible
.checkout_version(version)
.await
.map_err(|error| endpoint_error(error, field, current_branch.as_deref()))
}
DeltaRef::Tag(tag) => {
let tag_contents = visible
.tags()
.get(&tag)
.await
.map_err(|error| endpoint_error(error, field, current_branch.as_deref()))?;
if tag_contents.version == 0 {
return Err(Error::InvalidInput {
message: format!(
"{field} tag '{tag}' points at version 0, which is not a persisted table version"
),
});
}
let tag_branch = normalize_branch(tag_contents.branch.as_deref());
if tag_branch != current_branch {
return Err(Error::InvalidInput {
message: format!(
"{field} tag '{tag}' belongs to branch '{}', but this table is on branch '{}'; \
table.delta only compares endpoints on the current branch",
branch_label(tag_branch.as_deref()),
branch_label(current_branch.as_deref())
),
});
}
visible
.checkout_version(tag_contents.version)
.await
.map_err(|error| endpoint_error(error, field, current_branch.as_deref()))
}
}
}
fn endpoint_error(error: lance::Error, field: &str, branch: Option<&str>) -> Error {
match error {
lance::Error::VersionNotFound { message } => Error::InvalidInput {
message: format!(
"{field} does not exist on branch '{}': {message}",
branch_label(branch)
),
},
lance::Error::DatasetNotFound { source, .. } => Error::InvalidInput {
message: format!(
"{field} does not exist on branch '{}': {source}",
branch_label(branch)
),
},
lance::Error::RefNotFound { message } => Error::InvalidInput {
message: format!("{field} tag does not exist: {message}"),
},
other => other.into(),
}
}
fn normalize_branch(branch: Option<&str>) -> Option<String> {
match branch {
None | Some("main") => None,
Some(name) => Some(name.to_string()),
}
}
fn branch_label(branch: Option<&str>) -> &str {
branch.unwrap_or("main")
}
fn row_change_schema(end: &Dataset) -> SchemaRef {
let base = ArrowSchema::from(end.schema());
let mut fields = base.fields().to_vec();
fields.push(Arc::new((*ROW_ID_FIELD).clone()));
fields.push(Arc::new((*ROW_CREATED_AT_VERSION_FIELD).clone()));
fields.push(Arc::new((*ROW_LAST_UPDATED_AT_VERSION_FIELD).clone()));
Arc::new(ArrowSchema::new_with_metadata(
fields,
base.metadata().clone(),
))
}
fn deleted_row_ids_schema() -> SchemaRef {
Arc::new(ArrowSchema::new(vec![Arc::new((*ROW_ID_FIELD).clone())]))
}
fn empty_stream(schema: SchemaRef) -> DatasetRecordBatchStream {
let batches = stream::empty::<std::result::Result<RecordBatch, DataFusionError>>();
DatasetRecordBatchStream::new(Box::pin(RecordBatchStreamAdapter::new(schema, batches)))
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use arrow_array::{Array, Int32Array, RecordBatch, UInt64Array};
use arrow_schema::{DataType, Field, Schema as ArrowSchema};
use futures::TryStreamExt;
use lance::dataset::WriteParams;
use lance::io::RecordBatchStream;
use lance_file::format::{MAGIC, MAJOR_VERSION, MINOR_VERSION};
use lance_io::object_writer::ObjectWriter;
use lance_io::traits::{WriteExt, Writer};
use lance_table::format::pb;
use tempfile::tempdir;
use super::*;
use crate::connect;
use crate::query::{ExecutableQuery, QueryBase};
use crate::table::{BaseTable, NativeTable, WriteOptions};
fn rows(ids: &[i32]) -> RecordBatch {
let schema = Arc::new(ArrowSchema::new(vec![
Field::new("id", DataType::Int32, false),
Field::new("value", DataType::Int32, false),
]));
RecordBatch::try_new(
schema,
vec![
Arc::new(Int32Array::from(ids.to_vec())),
Arc::new(Int32Array::from(vec![0; ids.len()])),
],
)
.unwrap()
}
async fn collect(stream: DatasetRecordBatchStream) -> Vec<RecordBatch> {
stream.try_collect().await.unwrap()
}
fn i32_column(batches: &[RecordBatch], name: &str) -> Vec<i32> {
batches
.iter()
.flat_map(|batch| {
batch
.column_by_name(name)
.unwrap()
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.values()
.to_vec()
})
.collect()
}
fn u64_column(batches: &[RecordBatch], name: &str) -> Vec<u64> {
batches
.iter()
.flat_map(|batch| {
batch
.column_by_name(name)
.unwrap()
.as_any()
.downcast_ref::<UInt64Array>()
.unwrap()
.values()
.to_vec()
})
.collect()
}
fn schema_names(schema: &ArrowSchema) -> Vec<String> {
schema
.fields()
.iter()
.map(|field| field.name().clone())
.collect()
}
fn stable_row_ids() -> WriteOptions {
WriteOptions {
lance_write_params: Some(WriteParams {
enable_stable_row_ids: true,
..Default::default()
}),
}
}
#[tokio::test]
async fn test_delta_streams_versions_tags_and_checkout() {
let tmp_dir = tempdir().unwrap();
let conn = connect(tmp_dir.path().to_str().unwrap());
let conn = conn.execute().await.unwrap();
let table = conn
.create_table("t", rows(&[0, 1]))
.write_options(stable_row_ids())
.execute()
.await
.unwrap();
assert_eq!(table.version().await.unwrap(), 1);
table.add(rows(&[2])).execute().await.unwrap();
assert_eq!(table.version().await.unwrap(), 2);
let mut tags = table.tags().await.unwrap();
tags.create("baseline", 2).await.unwrap();
table
.update()
.column("value", "value + 10")
.execute()
.await
.unwrap();
assert_eq!(table.version().await.unwrap(), 3);
// Remember the stable row id before deletion so the deleted reader can
// be checked against a value derived from the table, not the delta.
let row_id_batches = table
.query()
.only_if("id = 1")
.with_row_id()
.execute()
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let deleted_row_id = u64_column(&row_id_batches, ROW_ID_FIELD.name())[0];
table.delete("id = 1").await.unwrap();
assert_eq!(table.version().await.unwrap(), 4);
let delta = table.delta(DeltaRef::Version(1), None).await.unwrap();
assert_eq!(delta.begin_version(), 1);
assert_eq!(delta.end_version(), 4);
let inserted = collect(delta.inserted_rows().await.unwrap()).await;
assert_eq!(i32_column(&inserted, "id"), vec![2]);
assert_eq!(
schema_names(&inserted[0].schema()),
vec![
"id".to_string(),
"value".to_string(),
"_rowid".to_string(),
"_row_created_at_version".to_string(),
"_row_last_updated_at_version".to_string(),
]
);
let updated = collect(delta.updated_rows().await.unwrap()).await;
assert_eq!(i32_column(&updated, "id"), vec![0]);
let upserted = collect(delta.upserted_rows().await.unwrap()).await;
let mut upserted_ids = i32_column(&upserted, "id");
upserted_ids.sort_unstable();
assert_eq!(upserted_ids, vec![0, 2]);
let deleted = collect(delta.deleted_row_ids().await.unwrap()).await;
assert_eq!(
u64_column(&deleted, ROW_ID_FIELD.name()),
vec![deleted_row_id]
);
assert_eq!(
schema_names(&deleted[0].schema()),
vec!["_rowid".to_string()]
);
assert_eq!(
deleted[0]
.column_by_name(ROW_ID_FIELD.name())
.unwrap()
.data_type(),
&DataType::UInt64
);
let transactions = delta.list_transactions().await.unwrap();
assert_eq!(
transactions
.iter()
.map(|transaction| transaction.operation.name())
.collect::<Vec<_>>(),
vec!["Append", "Update", "Delete"]
);
// A tag is resolved on the current branch and can be either endpoint.
let from_tag = table.delta("baseline", None).await.unwrap();
assert_eq!(from_tag.begin_version(), 2);
assert_eq!(from_tag.end_version(), 4);
let mut updated_ids =
i32_column(&collect(from_tag.updated_rows().await.unwrap()).await, "id");
updated_ids.sort_unstable();
// Row 2 was created exactly at the baseline, so the later update to it
// counts as an update in this range.
assert_eq!(updated_ids, vec![0, 2]);
let to_tag = table
.delta(1u64, Some(DeltaRef::Tag("baseline".to_string())))
.await
.unwrap();
assert_eq!(to_tag.end_version(), 2);
let inserted = collect(to_tag.inserted_rows().await.unwrap()).await;
assert_eq!(i32_column(&inserted, "id"), vec![2]);
// Moving a tag does not change an existing delta; a new delta sees the
// new target.
tags.update("baseline", 3).await.unwrap();
assert_eq!(from_tag.begin_version(), 2);
assert_eq!(to_tag.end_version(), 2);
let moved_tag = table.delta("baseline", None).await.unwrap();
assert_eq!(moved_tag.begin_version(), 3);
// Equal endpoints are empty but keep the reader schemas, without
// needing to scan or require stable row ids again.
let equal = table.delta(2u64, Some(DeltaRef::Version(2))).await.unwrap();
let inserted = collect(equal.inserted_rows().await.unwrap()).await;
assert!(inserted.is_empty());
let inserted_schema = equal.inserted_rows().await.unwrap().schema();
assert_eq!(
schema_names(&inserted_schema),
vec![
"id".to_string(),
"value".to_string(),
"_rowid".to_string(),
"_row_created_at_version".to_string(),
"_row_last_updated_at_version".to_string(),
]
);
let deleted = collect(equal.deleted_row_ids().await.unwrap()).await;
assert!(deleted.is_empty());
assert_eq!(
schema_names(&equal.deleted_row_ids().await.unwrap().schema()),
vec!["_rowid".to_string()]
);
// Invalid and reversed endpoints are actionable input errors.
for result in [
table.delta(0u64, None).await,
table.delta(1u64, Some(DeltaRef::Version(0))).await,
table.delta(4u64, Some(DeltaRef::Version(2))).await,
table.delta(999u64, None).await,
table.delta(1u64, Some(DeltaRef::Version(999))).await,
table.delta("missing-tag", None).await,
table
.delta(1u64, Some(DeltaRef::Tag("missing-tag".to_string())))
.await,
] {
assert!(
matches!(result, Err(Error::InvalidInput { .. })),
"expected an invalid input error, got {result:?}"
);
}
// An omitted target follows the visible checkout and leaves the shared
// table checkout exactly where it was.
table.checkout(2).await.unwrap();
let checked_out = table.delta(1u64, None).await.unwrap();
assert_eq!(checked_out.end_version(), 2);
let inserted = collect(checked_out.inserted_rows().await.unwrap()).await;
assert_eq!(i32_column(&inserted, "id"), vec![2]);
assert_eq!(table.version().await.unwrap(), 2);
// An explicit target still works from a pinned handle without moving it.
let explicit = table.delta(1u64, Some(DeltaRef::Version(3))).await.unwrap();
let mut updated_ids =
i32_column(&collect(explicit.updated_rows().await.unwrap()).await, "id");
updated_ids.sort_unstable();
assert_eq!(updated_ids, vec![0, 1]);
assert_eq!(table.version().await.unwrap(), 2);
table.checkout_latest().await.unwrap();
assert_eq!(table.version().await.unwrap(), 4);
}
#[tokio::test]
async fn test_delta_resolves_endpoints_on_the_current_branch() {
let tmp_dir = tempdir().unwrap();
let conn = connect(tmp_dir.path().to_str().unwrap())
.read_consistency_interval(std::time::Duration::ZERO)
.execute()
.await
.unwrap();
let main = conn
.create_table("t", rows(&[0]))
.write_options(stable_row_ids())
.execute()
.await
.unwrap();
let fork = main.version().await.unwrap();
let branch = main.create_branch("exp", fork).await.unwrap();
branch.add(rows(&[1])).execute().await.unwrap();
main.add(rows(&[100, 101, 102])).execute().await.unwrap();
assert_eq!(
branch.version().await.unwrap(),
main.version().await.unwrap(),
"branch and main must share a version number for this test"
);
let mut main_tags = main.tags().await.unwrap();
main_tags
.create("main-tag", main.version().await.unwrap())
.await
.unwrap();
let mut branch_tags = branch.tags().await.unwrap();
branch_tags
.create("exp-tag", branch.version().await.unwrap())
.await
.unwrap();
// The same-branch tag resolves through the branch, not main's data at
// the same version number.
let branch_delta = branch
.delta(1u64, Some(DeltaRef::Tag("exp-tag".to_string())))
.await
.unwrap();
let inserted = collect(branch_delta.inserted_rows().await.unwrap()).await;
assert_eq!(i32_column(&inserted, "id"), vec![1]);
// A tag from another branch is rejected even though its version number
// also exists on this branch.
let wrong_branch = branch.delta("main-tag", None).await;
match wrong_branch {
Err(Error::InvalidInput { message }) => {
assert!(message.contains("main-tag"), "{message}");
assert!(message.contains("exp"), "{message}");
assert!(message.contains("main"), "{message}");
}
other => panic!("expected cross-branch tag rejection, got {other:?}"),
}
let wrong_branch = main.delta("exp-tag", None).await;
assert!(
matches!(wrong_branch, Err(Error::InvalidInput { .. })),
"main must reject a branch tag"
);
}
#[tokio::test]
async fn test_delta_rejects_restore_ranges() {
for mutation in ["update", "delete"] {
let tmp_dir = tempdir().unwrap();
let conn = connect(tmp_dir.path().to_str().unwrap())
.execute()
.await
.unwrap();
let table = conn
.create_table("t", rows(&[0]))
.write_options(stable_row_ids())
.execute()
.await
.unwrap();
assert_eq!(table.version().await.unwrap(), 1);
if mutation == "update" {
table.update().column("value", "1").execute().await.unwrap();
} else {
table.delete("id = 0").await.unwrap();
}
assert_eq!(table.version().await.unwrap(), 2);
table.checkout(1).await.unwrap();
table.restore().await.unwrap();
assert_eq!(table.version().await.unwrap(), 3);
assert_eq!(table.count_rows(None).await.unwrap(), 1);
let restore_range = table.delta(2u64, Some(DeltaRef::Version(3))).await.unwrap();
assert_eq!(
restore_range
.list_transactions()
.await
.unwrap()
.iter()
.map(|transaction| transaction.operation.name())
.collect::<Vec<_>>(),
vec!["Restore"]
);
for result in [
restore_range.inserted_rows().await,
restore_range.updated_rows().await,
restore_range.upserted_rows().await,
restore_range.deleted_row_ids().await,
] {
match result {
Err(Error::InvalidInput { message }) => {
assert!(message.contains("Restore"), "{mutation}: {message}");
assert!(message.contains("full rescan"), "{mutation}: {message}");
assert!(message.contains("reinitialize"), "{mutation}: {message}");
}
Ok(_) => panic!("{mutation}: restore range must be rejected"),
Err(other) => panic!("{mutation}: expected invalid input, got {other:?}"),
}
}
// A restore in the middle of the range is still unverifiable.
table.add(rows(&[1])).execute().await.unwrap();
assert_eq!(table.version().await.unwrap(), 4);
match table
.delta(2u64, Some(DeltaRef::Version(4)))
.await
.unwrap()
.upserted_rows()
.await
{
Err(Error::InvalidInput { message }) => {
assert!(message.contains("Restore"), "{mutation}: {message}");
}
Ok(_) => panic!("{mutation}: restore inside the range must be rejected"),
Err(other) => panic!("{mutation}: expected invalid input, got {other:?}"),
}
// A restore at the exclusive boundary is the base snapshot, so
// changes after it are usable.
let after_restore = table.delta(3u64, Some(DeltaRef::Version(4))).await.unwrap();
let inserted = collect(after_restore.inserted_rows().await.unwrap()).await;
assert_eq!(i32_column(&inserted, "id"), vec![1]);
assert_eq!(
after_restore
.list_transactions()
.await
.unwrap()
.iter()
.map(|transaction| transaction.operation.name())
.collect::<Vec<_>>(),
vec!["Append"]
);
// Equal endpoints remain empty and do not run the restore guard.
let equal = table.delta(3u64, Some(DeltaRef::Version(3))).await.unwrap();
assert!(
collect(equal.upserted_rows().await.unwrap())
.await
.is_empty()
);
}
}
#[tokio::test]
async fn test_delta_rejects_missing_transaction_history() {
let tmp_dir = tempdir().unwrap();
let conn = connect(tmp_dir.path().to_str().unwrap())
.execute()
.await
.unwrap();
let table = conn
.create_table("t", rows(&[0]))
.write_options(stable_row_ids())
.execute()
.await
.unwrap();
table.add(rows(&[1])).execute().await.unwrap();
let uri = table.uri().await.unwrap();
// Simulate a supported dataset whose latest version has no transaction
// entry. Lance cannot then tell us whether that version was a Restore,
// so row readers must fail closed instead of treating it as restore-free.
let dataset = Dataset::open(&uri).await.unwrap();
let manifest_path = dataset.manifest_location().path.clone();
let store = dataset.object_store(None).await.unwrap();
let mut writer = ObjectWriter::new(store.as_ref(), &manifest_path)
.await
.unwrap();
let mut manifest = pb::Manifest::from(dataset.manifest());
manifest.transaction_section = None;
manifest.transaction_section_deprecated = None;
manifest.transaction_file = String::new();
let pos = writer.write_protobuf(&manifest).await.unwrap();
writer
.write_magics(pos, MAJOR_VERSION, MINOR_VERSION, MAGIC)
.await
.unwrap();
Writer::shutdown(&mut writer).await.unwrap();
drop(dataset);
drop(table);
let table = NativeTable::open(&uri).await.unwrap();
let delta = table.delta(DeltaRef::Version(1), None).await.unwrap();
assert!(delta.list_transactions().await.unwrap().is_empty());
match delta.inserted_rows().await {
Err(Error::InvalidInput { message }) => {
assert!(
message.contains("transaction history is missing"),
"{message}"
);
assert!(message.contains("full rescan"), "{message}");
}
Ok(_) => panic!("missing transaction history must fail closed"),
Err(other) => panic!("expected invalid input, got {other:?}"),
}
}
#[tokio::test]
async fn test_delta_without_stable_row_ids_guides_but_lists_transactions() {
let tmp_dir = tempdir().unwrap();
let conn = connect(tmp_dir.path().to_str().unwrap())
.execute()
.await
.unwrap();
let table = conn.create_table("t", rows(&[0])).execute().await.unwrap();
table.add(rows(&[1])).execute().await.unwrap();
let delta = table.delta(1u64, None).await.unwrap();
for result in [
delta.inserted_rows().await,
delta.updated_rows().await,
delta.upserted_rows().await,
delta.deleted_row_ids().await,
] {
match result {
Err(Error::InvalidInput { message }) => {
assert!(
message.contains("new_table_enable_stable_row_ids"),
"{message}"
);
assert!(message.contains("list_transactions"), "{message}");
}
Ok(_) => panic!("row-level delta must require stable row ids"),
Err(other) => panic!("expected invalid input, got {other:?}"),
}
}
// Transactions remain available without stable row ids.
let transactions = delta.list_transactions().await.unwrap();
assert_eq!(transactions.len(), 1);
assert_eq!(transactions[0].operation.name(), "Append");
// Equal endpoints need no row lineage, so their readers are empty.
let version = table.version().await.unwrap();
let equal = table
.delta(version, Some(DeltaRef::Version(version)))
.await
.unwrap();
assert!(
collect(equal.inserted_rows().await.unwrap())
.await
.is_empty()
);
assert!(
collect(equal.deleted_row_ids().await.unwrap())
.await
.is_empty()
);
}
}
+135
View File
@@ -0,0 +1,135 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
use std::sync::Arc;
use arrow_array::cast::AsArray;
use arrow_array::types::Int64Type;
use arrow_array::{RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray};
use arrow_schema::{DataType, Field, Schema};
fn make_quotes_reader(rows: Vec<(i64, &str, &str)>) -> Box<dyn RecordBatchReader + Send> {
let ids: Vec<i64> = rows.iter().map(|(id, _, _)| *id).collect();
let authors: Vec<&str> = rows.iter().map(|(_, author, _)| *author).collect();
let quotes: Vec<&str> = rows.iter().map(|(_, _, quote)| *quote).collect();
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("author", DataType::Utf8, false),
Field::new("quote", DataType::Utf8, false),
]));
let batch = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(arrow_array::Int64Array::from(ids)),
Arc::new(StringArray::from(authors)),
Arc::new(StringArray::from(quotes)),
],
)
.unwrap();
Box::new(RecordBatchIterator::new(
vec![Ok(batch)].into_iter(),
schema,
))
}
#[tokio::test]
async fn checkpoint_delta_docs() -> anyhow::Result<()> {
let directory = tempfile::tempdir()?;
let db = lancedb::connect(directory.path().to_str().unwrap())
.execute()
.await?;
// --8<-- [start:versioning_checkpoint_delta]
use futures::TryStreamExt;
let table = db
.create_table(
"checkpoint_delta_example",
make_quotes_reader(vec![
(1, "Richard", "Wubba Lubba Dub Dub!"),
(2, "Morty", "Rick, what's going on?"),
]),
)
.storage_option("new_table_enable_stable_row_ids", "true")
.execute()
.await?;
let mut tags = table.tags().await?;
tags.create("baseline", table.version().await?).await?;
table
.add(make_quotes_reader(vec![(3, "Summer", "Whatever, Grandpa")]))
.execute()
.await?;
table
.update()
.only_if("id = 2")
.column("quote", "'Aww geez, Rick!'")
.execute()
.await?;
table.delete("id = 1").await?;
let delta = table.delta("baseline", None).await?;
let mut inserted = delta.inserted_rows().await?;
while let Some(batch) = inserted.try_next().await? {
println!("inserted: {:?}", batch.column_by_name("id"));
}
let mut deleted = delta.deleted_row_ids().await?;
while let Some(batch) = deleted.try_next().await? {
println!("deleted row ids: {batch:?}");
}
for transaction in delta.list_transactions().await? {
println!("{}", transaction.operation.name());
}
// --8<-- [end:versioning_checkpoint_delta]
assert_eq!(table.version().await?, 4);
let inserted = delta.inserted_rows().await?.try_collect::<Vec<_>>().await?;
let inserted_ids: Vec<i64> = inserted
.iter()
.flat_map(|batch| {
batch
.column_by_name("id")
.unwrap()
.as_primitive::<Int64Type>()
.values()
.to_vec()
})
.collect();
assert_eq!(inserted_ids, vec![3]);
let updated = delta.updated_rows().await?.try_collect::<Vec<_>>().await?;
let updated_ids: Vec<i64> = updated
.iter()
.flat_map(|batch| {
batch
.column_by_name("id")
.unwrap()
.as_primitive::<Int64Type>()
.values()
.to_vec()
})
.collect();
assert_eq!(updated_ids, vec![2]);
assert_eq!(
delta
.deleted_row_ids()
.await?
.try_collect::<Vec<_>>()
.await?
.len(),
1
);
assert_eq!(
delta
.list_transactions()
.await?
.iter()
.map(|transaction| transaction.operation.name())
.collect::<Vec<_>>(),
vec!["Append", "Update", "Delete"]
);
Ok(())
}