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
+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>,