fix: preserve branch scope during Embedded tag time travel (#4852)

Embedded tag checkout replaced the handle's only branch identity. After
reading a tag on another branch, `checkout_latest()` followed that
branch and subsequent writes or restores could commit there.

Keep the handle's original branch and Lance `BranchIdentifier`
separately from its visible snapshot. A branch name alone cannot
distinguish the original branch from a replacement after deletion and
reuse. Cross-branch tags remain readable, and Python pickle and snapshot
copies preserve both identities. `checkout_latest()` reattaches to the
original branch, so later appends stay there. `current_branch()`
continues to report the visible snapshot's branch.

Validate the retained identity before `checkout_latest()` changes the
handle or `restore(tag)` commits; a reused branch name is rejected
without changing either branch tip. Independent and query snapshot
copies retain this identity too. Reject an ambiguous cross-branch
restore before committing. To restore on the tag's branch, first open a
handle there with `branches.checkout(...)` or Rust's
`checkout_branch(...)`. Update Rust, Python sync/async, TypeScript,
generated API documentation, and the tag-based versioning guide for this
behavior.

Python pickle state also carries the original `BranchIdentifier` through
reopening. A foreign snapshot stays readable if the originating branch
is replaced while serialized, but latest checkout and restore reject the
replacement. Latest and same-branch pinned handles validate the saved
identity before reopening returns. Older pickle states without the
identifier keep their existing reopen behavior; they cannot validate an
identity that was never saved.

Validation:

- All 12 new branch-name reuse regression cases failed before the
identity fix and pass afterward. They cover latest checkout and restore,
direct handles and snapshot copies, all three consistency modes, and
unchanged versions and contents on both branch tips. Query snapshot
identity retention is also covered.
- All 8 new Python pickle regression cases failed before the
serialization fix and pass afterward. They replace the branch while the
handle is serialized, cover latest checkout and restore across three
consistency modes, verify unchanged tips, and reject replacement data
when reopening latest or same-branch pinned handles.
- 494 Rust table tests and 23 dataset consistency tests passed with
`--features remote --profile ci`; Clippy for the core and Python
bindings, Rust formatting, and `git diff --check` passed.
- 62 targeted Python tag, branch, pickle, and restore tests passed in
the uv-managed environment after rebuilding the extension. An additional
compatibility check verified that older pickle states without the
identifier still reopen and return to the original branch.
- Earlier SDK validation: 9 targeted Node tests passed, including the
cross-branch regression. Node native build, TypeScript compilation,
lint/format checks, and API documentation generation passed. TypeScript
sources are unchanged in this Python pickle follow-up.
- Python package Ruff lint/format checks passed; repository-wide Ruff
reported 59 pre-existing findings in untouched `docs/web-tests/` files.
Vale 3.24.0 found no prose issues on the changed guide lines.

Fixes #4842

<!-- lance-gatekeeper-fix:v1 agent=c1c6448a3f02ec6db445df5e3d8dd77f
generation=1 -->


<!-- gatefixer-walkthrough:v1
head=078eceadbedc15cf179d9d4dcce249c83e7010f9 -->
## Change walkthrough

```mermaid
flowchart LR
    A["Save original identity"] --> B["Reopen visible snapshot"]
    B --> C{"Foreign snapshot?"}
    C -->|No| D["Validate before return"]
    C -->|Yes| E["Retain saved identity"]
    E --> F["Validate latest or restore"]
```

**Read:** [Serialize and
reopen](https://github.com/lancedb/lancedb/blob/078eceadbedc15cf179d9d4dcce249c83e7010f9/python/python/lancedb/table.py#L4541-L4594)
→ [Reinstate identity
safely](https://github.com/lancedb/lancedb/blob/078eceadbedc15cf179d9d4dcce249c83e7010f9/rust/lancedb/src/table/dataset.rs#L278-L307)
→ [Serialized-handle
regressions](https://github.com/lancedb/lancedb/blob/078eceadbedc15cf179d9d4dcce249c83e7010f9/python/python/tests/test_table.py#L1300-L1360).

<sub>Snapshot:
[078ecea](https://github.com/lancedb/lancedb/commit/078eceadbedc15cf179d9d4dcce249c83e7010f9)</sub>
<!-- gatefixer-walkthrough:end -->

---------

Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com>
This commit is contained in:
lancedb-gatefixer[bot]
2026-11-30 20:05:58 +08:00
committed by GitHub
parent c0d46c31ba
commit 2d4e0fb3f2
10 changed files with 820 additions and 54 deletions
+4
View File
@@ -730,6 +730,10 @@ class Table:
async def checkout(self, version: Union[int, str]): ...
async def checkout_latest(self): ...
async def _checkout_current(self) -> Table: ...
def _tracking_branch(self) -> Optional[str]: ...
async def _tracking_branch_identifier(self) -> Optional[str]: ...
async def _set_tracking_branch_identifier(self, identifier: str) -> None: ...
async def _checkout_snapshot(self, branch: Optional[str], version: int) -> None: ...
async def restore(self, version: Optional[Union[int, str]] = None): ...
async def prewarm_index(self, index_name: str) -> None: ...
async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ...
+77 -11
View File
@@ -1639,7 +1639,11 @@ class Table(ABC):
raise NotImplementedError("branches is not supported for this table type")
def current_branch(self) -> Optional[str]:
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
"""The branch of the visible snapshot, or ``None`` for ``main``.
During Embedded tag time travel, this can differ from the original
branch that ``checkout_latest()`` returns to.
"""
raise NotImplementedError("current_branch is not supported for this table type")
def delta(
@@ -4280,6 +4284,12 @@ class Table(ABC):
version. As a consequence, calling this method will disable any read consistency
interval that was previously set.
In LanceDB Embedded, a tag can select a read-only snapshot on another
branch. `checkout_latest()` returns to this handle's original branch.
Restoring a snapshot from another branch raises `ValueError` before writing.
Use [branches.checkout()][lancedb.table.Branches.checkout] to open a
handle on that branch before restoring its tag.
This is a read-only operation that turns the table into a sort of "view"
or "detached head". Other table instances will not be affected. To make the
change permanent you can use the `[Self::restore]` method.
@@ -4318,6 +4328,10 @@ class Table(ABC):
This creates a new version where the data is equivalent to the
specified previous version. Data is not copied (as of python-v0.2.1).
In LanceDB Embedded, a snapshot on another branch cannot be restored
through this handle. Open that branch with `branches.checkout()` first;
an ambiguous cross-branch restore raises `ValueError` before writing.
Parameters
----------
version : int or str, default None
@@ -4566,10 +4580,19 @@ class LanceTable(Table):
)
version = state["checkout_version"]
if state["branch"] is not None:
table = table.branches.checkout(state["branch"], version)
elif version is not None:
table.checkout(version)
# Older pickle states recorded only the visible snapshot branch.
tracking_branch = state.get("tracking_branch", state["branch"])
if tracking_branch is not None:
table = table.branches.checkout(tracking_branch)
if version is not None:
LOOP.run(table._table._checkout_snapshot(state["branch"], version))
table._branch = state["branch"]
table._checkout_version = version
# Apply after checkout so a foreign snapshot remains readable even if
# the original branch was replaced while the handle was serialized.
identifier = state.get("tracking_branch_identifier")
if identifier is not None:
LOOP.run(table._table._set_tracking_branch_identifier(identifier))
return table
def __getstate__(self) -> dict[str, Any]:
@@ -4588,9 +4611,8 @@ class LanceTable(Table):
def _reopen_state(self) -> dict[str, Any]:
"""Arguments for ``_open_from_pickle_state``, minus the connection."""
# The native handle is authoritative: a tag checkout can move this
# wrapper onto another branch, so never trust the branch captured at
# construction time.
# Preserve the snapshot branch separately from the branch that
# checkout_latest() reattaches to after cross-branch time travel.
self._branch = self.current_branch()
return {
"name": self.name,
@@ -4605,6 +4627,10 @@ class LanceTable(Table):
"pushdown_operations": set(self._pushdown_operations),
"route_pushdown_to_rust": self._route_pushdown_to_rust,
"branch": self._branch,
"tracking_branch": self._table._inner._tracking_branch(),
"tracking_branch_identifier": LOOP.run(
self._table._tracking_branch_identifier()
),
"checkout_version": self._checkout_version,
}
@@ -4922,7 +4948,11 @@ class LanceTable(Table):
return Branches(self)
def current_branch(self) -> Optional[str]:
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
"""The branch of the visible snapshot, or ``None`` for ``main``.
During Embedded tag time travel, this can differ from the original
branch that ``checkout_latest()`` returns to.
"""
return self._table.current_branch()
def _pin_current_snapshot(self) -> "LanceTable":
@@ -4966,6 +4996,12 @@ class LanceTable(Table):
Calling this method will set the table into time-travel mode. If you
wish to return to standard mode, call `checkout_latest`.
A tag can select a read-only snapshot on another branch.
`checkout_latest()` returns to this handle's original branch. Restoring
a snapshot from another branch raises `ValueError` before writing. Use
[branches.checkout()][lancedb.table.Branches.checkout] to open a handle
on that branch before restoring its tag.
Parameters
----------
version: int | str,
@@ -5012,6 +5048,10 @@ class LanceTable(Table):
This creates a new version where the data is equivalent to the
specified previous version. Data is not copied (as of python-v0.2.1).
In LanceDB Embedded, a snapshot on another branch cannot be restored
through this handle. Open that branch with `branches.checkout()` first;
an ambiguous cross-branch restore raises `ValueError` before writing.
Parameters
----------
version : int or str, default None
@@ -5051,7 +5091,7 @@ class LanceTable(Table):
4
"""
if version is not None:
LOOP.run(self._table.checkout(version))
self.checkout(version)
LOOP.run(self._table.restore())
self._checkout_version = None
self._branch = self.current_branch()
@@ -10039,6 +10079,18 @@ class AsyncTable:
"""Return an independent handle pinned to the currently selected snapshot."""
return AsyncTable(await self._inner._checkout_current())
async def _checkout_snapshot(self, branch: Optional[str], version: int) -> None:
"""Reopen a snapshot while retaining the handle's original branch."""
await self._inner._checkout_snapshot(branch, version)
async def _tracking_branch_identifier(self) -> Optional[str]:
"""Serialize the original branch identity for reopening."""
return await self._inner._tracking_branch_identifier()
async def _set_tracking_branch_identifier(self, identifier: str) -> None:
"""Restore branch identity after reopening a serialized snapshot."""
await self._inner._set_tracking_branch_identifier(identifier)
async def list_versions(self):
"""
List all versions of the table
@@ -10076,6 +10128,12 @@ class AsyncTable:
version. As a consequence, calling this method will disable any read consistency
interval that was previously set.
In LanceDB Embedded, a tag can select a read-only snapshot on another
branch. `checkout_latest()` returns to this handle's original branch.
Restoring a snapshot from another branch raises `ValueError` before writing.
Use [branches.checkout()][lancedb.table.AsyncBranches.checkout] to open a
handle on that branch before restoring its tag.
This is a read-only operation that turns the table into a sort of "view"
or "detached head". Other table instances will not be affected. To make the
change permanent you can use the `[Self::restore]` method.
@@ -10120,6 +10178,10 @@ class AsyncTable:
"""
Restore the table to the currently checked out version
In LanceDB Embedded, a snapshot on another branch cannot be restored
through this handle. Open that branch with `branches.checkout()` first;
an ambiguous cross-branch restore raises `ValueError` before writing.
This operation will fail if checkout has not been called previously
This operation will overwrite the latest version of the table with a
@@ -10331,7 +10393,11 @@ class AsyncTable:
return AsyncBranches(self._inner)
def current_branch(self) -> Optional[str]:
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
"""The branch of the visible snapshot, or ``None`` for ``main``.
During Embedded tag time travel, this can differ from the original
branch that ``checkout_latest()`` returns to.
"""
return self._inner.current_branch()
async def explain_cleanup(
+142
View File
@@ -1279,6 +1279,148 @@ def test_lance_table_pickle_preserves_cross_branch_tag_checkout(tmp_path):
assert restored.version == 2
assert restored.to_arrow()["id"].to_pylist() == [0, 1]
# Pickle must preserve both the tagged snapshot and the branch to reattach.
for handle in (main, restored):
with pytest.raises(ValueError, match="cannot restore.*branch"):
handle.restore()
handle.checkout_latest()
assert handle.current_branch() is None
assert handle.to_arrow()["id"].to_pylist() == [0, 9]
restored.add(pa.table({"id": [100]}))
assert db.open_table("pickle_tag_branch").to_arrow()["id"].to_pylist() == [
0,
9,
100,
]
assert db.open_table("pickle_tag_branch", branch="exp").version == 2
assert branch.to_arrow()["id"].to_pylist() == [0, 1]
@pytest.mark.parametrize("operation", ["checkout_latest", "restore"])
@pytest.mark.parametrize(
"consistency_interval", [None, timedelta(0), timedelta(seconds=60)]
)
def test_lance_table_pickle_retains_original_branch_identity(
tmp_path, operation, consistency_interval
):
db = lancedb.connect(tmp_path, read_consistency_interval=consistency_interval)
main = db.create_table("pickle_branch_identity", pa.table({"id": [0]}))
exp = main.branches.create("exp")
exp.add(pa.table({"id": [10]}))
main.add(pa.table({"id": [100]}))
main.tags.create("main_v2", 2)
exp.checkout("main_v2")
payload = pickle.dumps(exp)
# Reuse the original branch name while the handle is serialized. Both
# branches have version 2, but neither is the original exp identity.
main.branches.delete("exp")
replacement = main.branches.create("exp", from_version=1)
replacement.add(pa.table({"id": [20]}))
replacement.tags.create("replacement_v1", 1)
restored = pickle.loads(payload)
assert restored.current_branch() is None
assert restored.version == 2
assert restored.to_arrow()["id"].to_pylist() == [0, 100]
with pytest.raises(RuntimeError, match="deleted and recreated"):
if operation == "checkout_latest":
restored.checkout_latest()
else:
restored.restore("replacement_v1")
for branch, ids in [(None, [0, 100]), ("exp", [0, 20])]:
fresh = db.open_table("pickle_branch_identity", branch=branch)
assert fresh.version == 2
assert fresh.to_arrow()["id"].to_pylist() == ids
@pytest.mark.parametrize("pinned", [False, True])
def test_lance_table_pickle_rejects_replaced_visible_branch(tmp_path, pinned):
db = lancedb.connect(tmp_path)
main = db.create_table("pickle_visible_identity", pa.table({"id": [0]}))
exp = main.branches.create("exp")
exp.add(pa.table({"id": [10]}))
if pinned:
exp.checkout(2)
payload = pickle.dumps(exp)
main.branches.delete("exp")
replacement = main.branches.create("exp", from_version=1)
replacement.add(pa.table({"id": [20]}))
# A latest or same-branch pinned handle must not reopen replacement data
# with the old identity, even when its version number still exists.
with pytest.raises(RuntimeError, match="deleted and recreated"):
pickle.loads(payload)
for branch, version, ids in [(None, 1, [0]), ("exp", 2, [0, 20])]:
fresh = db.open_table("pickle_visible_identity", branch=branch)
assert fresh.version == version
assert fresh.to_arrow()["id"].to_pylist() == ids
def test_restore_cross_branch_tag_does_not_write(tmp_path):
db = lancedb.connect(tmp_path)
main = db.create_table("restore_tag", pa.table({"id": [0]}))
exp = main.branches.create("exp")
main.add(pa.table({"id": [100]}))
exp.add(pa.table({"id": [10]}))
main.tags.create("main_v2", 2)
exp.tags.create("exp_v2", 2)
for handle, tag, own_branch, snapshot_branch, snapshot_ids in [
(main, "exp_v2", None, "exp", [0, 10]),
(exp, "main_v2", "exp", None, [0, 100]),
]:
with pytest.raises(ValueError, match="cannot restore.*branch"):
handle.restore(tag)
assert handle.to_arrow()["id"].to_pylist() == snapshot_ids
restored = pickle.loads(pickle.dumps(handle))
assert restored.current_branch() == snapshot_branch
assert restored.version == 2
assert restored.to_arrow()["id"].to_pylist() == snapshot_ids
with pytest.raises(ValueError, match="cannot restore.*branch"):
restored.restore()
restored.checkout_latest()
assert restored.current_branch() == own_branch
handle.checkout_latest()
assert handle.current_branch() == own_branch
for branch, ids in [(None, [0, 100]), ("exp", [0, 10])]:
fresh = db.open_table("restore_tag", branch=branch)
assert fresh.version == 2
assert fresh.to_arrow()["id"].to_pylist() == ids
@pytest.mark.asyncio
async def test_async_cross_branch_tag_read_and_restore(tmp_path):
db = await lancedb.connect_async(tmp_path)
main = await db.create_table("tag_branch", pa.table({"id": [0]}))
exp = await main.branches.create("exp")
await main.add(pa.table({"id": [100]}))
await exp.add(pa.table({"id": [10]}))
await main.tags.create("main_v2", 2)
await exp.tags.create("exp_v2", 2)
for handle, tag, own_branch, ids, row in [
(main, "exp_v2", None, [0, 10], 101),
(exp, "main_v2", "exp", [0, 100], 11),
]:
await handle.checkout(tag)
assert await handle.version() == 2
assert (await handle.to_arrow())["id"].to_pylist() == ids
with pytest.raises(ValueError, match="cannot restore.*branch"):
await handle.restore(tag)
await handle.checkout_latest()
assert handle.current_branch() == own_branch
await handle.add(pa.table({"id": [row]}))
for branch, ids in [(None, [0, 100, 101]), ("exp", [0, 10, 11])]:
fresh = await db.open_table("tag_branch", branch=branch)
assert await fresh.version() == 3
assert (await fresh.to_arrow())["id"].to_pylist() == ids
def test_lance_table_pickle_preserves_branch_and_version(tmp_path):
db = lancedb.connect(tmp_path)
+68
View File
@@ -2094,6 +2094,74 @@ impl Table {
})
}
/// The branch to reattach to after time travel, for pickle reopen state.
pub fn _tracking_branch(&self) -> PyResult<Option<String>> {
let inner = self.inner_ref()?;
Ok(inner
.dataset()
.map(|dataset| dataset.tracking_branch())
.unwrap_or_else(|| inner.current_branch()))
}
/// Serialize the original branch identity as opaque pickle state.
pub fn _tracking_branch_identifier(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
if let Some(dataset) = inner.dataset() {
let identifier = dataset.tracking_branch_identifier().await.infer_error()?;
serde_json::to_string(&identifier)
.map(Some)
.map_err(|err| PyRuntimeError::new_err(err.to_string()))
} else {
Ok(None)
}
})
}
/// Restore the original branch identity after reopening the visible snapshot.
pub fn _set_tracking_branch_identifier(
self_: PyRef<'_, Self>,
identifier: String,
) -> PyResult<Bound<'_, PyAny>> {
let identifier = serde_json::from_str(&identifier)
.map_err(|err| PyValueError::new_err(err.to_string()))?;
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let dataset = inner.dataset().ok_or_else(|| {
PyValueError::new_err("branch identity is only available for Embedded tables")
})?;
dataset
.set_tracking_branch_identifier(identifier)
.await
.infer_error()
})
}
/// Reopen an exact snapshot without changing the handle's tracking branch.
#[pyo3(signature = (branch, version))]
pub fn _checkout_snapshot(
self_: PyRef<'_, Self>,
branch: Option<String>,
version: u64,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
if let Some(dataset) = inner.dataset() {
dataset
.as_time_travel(Ref::Version(branch, Some(version)))
.await
.infer_error()
} else {
if inner.current_branch() != branch {
return Err(PyValueError::new_err(
"snapshot branch differs from the table handle's branch",
));
}
inner.checkout(version).await.infer_error()
}
})
}
#[pyo3(signature = (version=None))]
pub fn restore(
self_: PyRef<'_, Self>,