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
+11 -3
View File
@@ -191,6 +191,11 @@ the `restore` function.
Calling this method will set the table into time-travel mode. If you
wish to return to standard mode, call `checkoutLatest`.
In LanceDB Embedded, a tag can select a read-only snapshot on another branch.
`checkoutLatest()` returns to this handle's original branch. Restoring a
snapshot from another branch is rejected before writing. Use
[Branches.checkout](Branches.md#checkout) to open that branch before restoring its tag.
#### Parameters
* **version**: `string` \| `number`
@@ -520,10 +525,10 @@ account for the replacement caveat described in [Table.createIndex](Table.md#cre
abstract currentBranch(): null | string
```
The branch this table handle is scoped to, or `null` for the main branch.
The branch of the visible snapshot, or `null` for the main branch.
A handle returned by [Branches.create](Branches.md#create) or [Branches.checkout](Branches.md#checkout)
reports the branch it targets; a handle opened normally reports `null`.
During Embedded tag time travel, this can differ from the handle's original
branch, which `checkoutLatest()` returns to.
#### Returns
@@ -1668,6 +1673,9 @@ abstract restore(): Promise<void>
Restore the table to the currently checked out version
LanceDB Embedded rejects a snapshot on another branch before writing.
Open that branch with [Branches.checkout](Branches.md#checkout) before restoring its tag.
This operation will fail if checkout has not been called previously
This operation will overwrite the latest version of the table with a
+14 -4
View File
@@ -1741,10 +1741,20 @@ page).
The tags API supports the standard CRUD operations (create, list, update, delete),
plus checking out by tag name.
A tag identifies both a branch and a version. On Enterprise tables, a tag must belong
to the handle's current branch; checking out a tag on another branch raises an
error without changing the current selection. Obtain a handle for the tag's
branch first: in Python, use `branch_table = table.branches.checkout("exp")`, then
A tag identifies both a branch and a version.
On Embedded tables, checking out a tag on another branch selects a read-only
snapshot on that branch. `checkout_latest()` (Python and Rust) or
`checkoutLatest()` (TypeScript) returns to the handle's original branch, so later
writes stay on that branch. Restoring a snapshot from another branch raises an
error before writing. To restore the tag's snapshot, first open a handle on its
branch with `branches.checkout()` (Python and TypeScript) or `checkout_branch()`
(Rust).
On Enterprise tables, a tag must belong to the handle's current branch;
checking out a tag on another branch raises an error without changing the
current selection. Obtain a handle for the tag's branch first: in Python, use
`branch_table = table.branches.checkout("exp")`, then
`branch_table.checkout("baseline")` to read a tag named `baseline` on `exp`.
See [Branches](/tables/branching) for more on branch handles.
+37
View File
@@ -4184,6 +4184,43 @@ describe("when dealing with branches", () => {
tmpDir.removeCallback();
});
it("reads cross-branch tags without redirecting writes or restores", async () => {
const conn = await connect(tmpDir.name, { readConsistencyInterval: 0 });
const main = await conn.createTable("tag_branch", [{ i: 0 }]);
const exp = await (await main.branches()).create("exp");
await main.add([{ i: 100 }]);
await exp.add([{ i: 10 }]);
await (await main.tags()).create("main-v2", 2);
await (await exp.tags()).create("exp-v2", 2);
for (const [handle, tag, ownBranch, snapshotRow] of [
[main, "exp-v2", null, 10],
[exp, "main-v2", "exp", 100],
] as const) {
await handle.checkout(tag);
expect(await handle.version()).toBe(2);
expect(await handle.countRows(`i = ${snapshotRow}`)).toBe(1);
await expect(handle.restore()).rejects.toThrow("cannot restore");
expect(await main.version()).toBe(2);
expect(await exp.version()).toBe(2);
await handle.checkoutLatest();
expect(handle.currentBranch()).toBe(ownBranch);
}
await main.add([{ i: 101 }]);
await exp.add([{ i: 11 }]);
for (const [branch, expectedRow, unexpectedRow] of [
["main", 101, 11],
["exp", 11, 101],
] as const) {
const fresh = await (await main.branches()).checkout(branch);
expect(await fresh.version()).toBe(3);
expect(await fresh.countRows()).toBe(3);
expect(await fresh.countRows(`i = ${expectedRow}`)).toBe(1);
expect(await fresh.countRows(`i = ${unexpectedRow}`)).toBe(0);
}
});
it("forks from a tag on a branch with the same version as main", async () => {
const conn = await connect(tmpDir.name, {
readConsistencyInterval: 0,
+12 -3
View File
@@ -1468,6 +1468,12 @@ export abstract class Table {
*
* Calling this method will set the table into time-travel mode. If you
* wish to return to standard mode, call `checkoutLatest`.
*
* In LanceDB Embedded, a tag can select a read-only snapshot on another branch.
* `checkoutLatest()` returns to this handle's original branch. Restoring a
* snapshot from another branch is rejected before writing. Use
* {@link Branches.checkout} to open that branch before restoring its tag.
*
* @param {number | string} version The version to checkout, could be version number or tag
* @example
* ```typescript
@@ -1525,16 +1531,19 @@ export abstract class Table {
abstract branches(): Promise<Branches>;
/**
* The branch this table handle is scoped to, or `null` for the main branch.
* The branch of the visible snapshot, or `null` for the main branch.
*
* A handle returned by {@link Branches.create} or {@link Branches.checkout}
* reports the branch it targets; a handle opened normally reports `null`.
* During Embedded tag time travel, this can differ from the handle's original
* branch, which `checkoutLatest()` returns to.
*/
abstract currentBranch(): string | null;
/**
* Restore the table to the currently checked out version
*
* LanceDB Embedded rejects a snapshot on another branch before writing.
* Open that branch with {@link Branches.checkout} before restoring its tag.
*
* This operation will fail if checkout has not been called previously
*
* This operation will overwrite the latest version of the table with a
+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>,
+279 -19
View File
@@ -1192,7 +1192,9 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
.append_to("Cherry-picking branches is only supported on Enterprise tables."),
})
}
/// The branch this 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.
fn current_branch(&self) -> Option<String>;
/// Get the table definition.
async fn table_definition(&self) -> Result<TableDefinition>;
@@ -3080,6 +3082,11 @@ impl Table {
/// As a consequence, calling this method will disable any read consistency interval
/// that was previously set.
///
/// On Embedded tables, a tag can select a read-only snapshot on another branch.
/// [`Self::checkout_latest`] returns to the handle's original branch. Restoring
/// a snapshot from another branch is rejected before writing; open that branch
/// with [`Self::checkout_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.
@@ -3102,6 +3109,9 @@ impl Table {
/// Restore the table to the currently checked out version
///
/// Embedded tables reject a snapshot on another branch before writing. Open
/// that branch with [`Self::checkout_branch`] before restoring its tag.
///
/// This operation will fail if checkout has not been called previously
///
/// This operation will overwrite the latest version of the table with a
@@ -3479,7 +3489,9 @@ impl Table {
self.inner.cherry_pick(from_branch, dry_run).await
}
/// The branch this 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.
pub fn current_branch(&self) -> Option<String> {
self.inner.current_branch()
}
@@ -4470,11 +4482,10 @@ impl BaseTable for NativeTable {
}
async fn checkout_current(&self) -> Result<Arc<dyn BaseTable>> {
let current = self.dataset.get().await?;
let dataset = dataset::DatasetConsistencyWrapper::new_time_travel(
current.as_ref().clone(),
self.read_consistency_interval,
);
let dataset = self
.dataset
.new_snapshot(self.read_consistency_interval)
.await?;
Ok(Arc::new(Self {
dataset,
..self.clone()
@@ -4575,18 +4586,10 @@ impl BaseTable for NativeTable {
}
async fn restore(&self) -> Result<()> {
let version = self
.dataset
.time_travel_version()
.ok_or_else(|| Error::InvalidInput {
message: "you must run checkout before running restore".to_string(),
})?;
{
// restore is the only "write" operation allowed in time travel mode
let mut dataset = (*self.dataset.get().await?).clone();
debug_assert_eq!(dataset.version().version, version);
dataset.restore().await?;
}
// Restore is the only write allowed in time travel mode. Validate the
// snapshot's branch before Lance can publish any restore transaction.
let mut dataset = self.dataset.restore_target().await?.as_ref().clone();
dataset.restore().await?;
// Restore moves "latest", so bump before resolving it (as RemoteTable does).
self.bump_freshness();
self.dataset.as_latest().await?;
@@ -5861,6 +5864,263 @@ mod tests {
assert_eq!(table.version().await.unwrap(), 4);
}
#[rstest::rstest]
#[case(None)]
#[case(Some(Duration::ZERO))]
#[case(Some(Duration::from_secs(60)))]
#[tokio::test]
async fn test_checkout_tag_preserves_handle_branch(#[case] interval: Option<Duration>) {
let tmp_dir = tempdir().unwrap();
let mut builder = ConnectBuilder::new(tmp_dir.path().to_str().unwrap());
if let Some(interval) = interval {
builder = builder.read_consistency_interval(interval);
}
let conn = builder.execute().await.unwrap();
let main = conn
.create_table("my_table", sample_rows(vec![0]))
.execute()
.await
.unwrap();
let exp = main.create_branch("exp", 1u64).await.unwrap();
let other = main.create_branch("other", 1u64).await.unwrap();
let handles = [
(&main, "main", 100),
(&exp, "exp", 10),
(&other, "other", 20),
];
for (handle, tag, row) in handles {
handle.add(sample_rows(vec![row])).execute().await.unwrap();
// Equal version numbers must still resolve to each branch's own data.
assert_eq!(handle.version().await.unwrap(), 2);
handle.tags().await.unwrap().create(tag, 2).await.unwrap();
}
for (handle, own_branch, own_row) in handles {
for (_, foreign_branch, foreign_row) in handles {
if foreign_branch == own_branch {
continue;
}
handle.checkout_tag(foreign_branch).await.unwrap();
assert_eq!(handle.version().await.unwrap(), 2);
assert_eq!(
handle.current_branch().as_deref(),
(foreign_branch != "main").then_some(foreign_branch)
);
assert_eq!(handle.count_rows(None).await.unwrap(), 2);
assert_eq!(
handle
.count_rows(Some(format!("i = {foreign_row}")))
.await
.unwrap(),
1
);
assert!(handle.add(sample_rows(vec![999])).execute().await.is_err());
let err = handle.restore().await.unwrap_err();
assert!(matches!(err, Error::InvalidInput { .. }), "{err}");
assert_eq!(
handle
.count_rows(Some(format!("i = {foreign_row}")))
.await
.unwrap(),
1
);
// A snapshot copy must retain the handle's branch, too.
let snapshot = handle.checkout_current().await.unwrap();
assert!(snapshot.restore().await.is_err());
snapshot.checkout_latest().await.unwrap();
assert_eq!(
snapshot.current_branch().as_deref(),
(own_branch != "main").then_some(own_branch)
);
// Numeric time travel still reads the visible snapshot's branch.
handle.checkout(2).await.unwrap();
assert_eq!(
handle
.count_rows(Some(format!("i = {foreign_row}")))
.await
.unwrap(),
1
);
// Explicit branch/version references must resolve the branch
// even when both snapshots have the same version number.
handle
.dataset()
.unwrap()
.as_time_travel((own_branch, 2u64))
.await
.unwrap();
assert_eq!(
handle
.count_rows(Some(format!("i = {own_row}")))
.await
.unwrap(),
1
);
handle.checkout_tag(foreign_branch).await.unwrap();
handle.dataset().unwrap().reload().await.unwrap();
assert_eq!(
handle
.count_rows(Some(format!("i = {foreign_row}")))
.await
.unwrap(),
1
);
handle.checkout_latest().await.unwrap();
assert_eq!(
handle.current_branch().as_deref(),
(own_branch != "main").then_some(own_branch)
);
}
}
// Rejected restores must not commit to either the source or destination.
for (_, branch, row) in handles {
let fresh = conn
.open_table("my_table")
.branch(branch)
.execute()
.await
.unwrap();
assert_eq!(fresh.version().await.unwrap(), 2);
assert_eq!(fresh.count_rows(None).await.unwrap(), 2);
assert_eq!(
fresh.count_rows(Some(format!("i = {row}"))).await.unwrap(),
1
);
}
for (handle, _, row) in handles {
handle
.add(sample_rows(vec![row + 1]))
.execute()
.await
.unwrap();
}
for (handle, branch, row) in handles {
let fresh = conn
.open_table("my_table")
.branch(branch)
.execute()
.await
.unwrap();
assert_eq!(fresh.version().await.unwrap(), 3);
assert_eq!(fresh.count_rows(None).await.unwrap(), 3);
for (_, _, candidate) in handles {
assert_eq!(
fresh
.count_rows(Some(format!("i = {}", candidate + 1)))
.await
.unwrap(),
usize::from(candidate == row)
);
}
handle.checkout_tag(branch).await.unwrap();
handle.restore().await.unwrap();
}
// Same-branch restores must publish only on the handle's own branch.
for (_, branch, row) in handles {
let fresh = conn
.open_table("my_table")
.branch(branch)
.execute()
.await
.unwrap();
assert_eq!(fresh.version().await.unwrap(), 4);
assert_eq!(fresh.count_rows(None).await.unwrap(), 2);
assert_eq!(
fresh.count_rows(Some(format!("i = {row}"))).await.unwrap(),
1
);
}
}
#[rstest::rstest]
#[case(None)]
#[case(Some(Duration::ZERO))]
#[case(Some(Duration::from_secs(60)))]
#[tokio::test]
async fn test_branch_identity_after_foreign_snapshot(
#[case] interval: Option<Duration>,
#[values(false, true)] restore: bool,
#[values(false, true)] snapshot_copy: bool,
) {
let tmp_dir = tempdir().unwrap();
let mut builder = ConnectBuilder::new(tmp_dir.path().to_str().unwrap());
if let Some(interval) = interval {
builder = builder.read_consistency_interval(interval);
}
let conn = builder.execute().await.unwrap();
let main = conn
.create_table("my_table", sample_rows(vec![0]))
.execute()
.await
.unwrap();
let stale = main.create_branch("exp", 1u64).await.unwrap();
stale.add(sample_rows(vec![10])).execute().await.unwrap();
let ordinary_pin = stale.checkout_current().await.unwrap();
main.add(sample_rows(vec![100])).execute().await.unwrap();
main.tags()
.await
.unwrap()
.create("main-tip", 2)
.await
.unwrap();
stale.checkout_tag("main-tip").await.unwrap();
let stale = if snapshot_copy {
stale.checkout_current().await.unwrap()
} else {
stale
};
// Reusing a name must not let the old handle attach or commit to the
// replacement, even after its visible snapshot left the original branch.
main.delete_branch("exp").await.unwrap();
let replacement = main.create_branch("exp", 1u64).await.unwrap();
replacement
.add(sample_rows(vec![20]))
.execute()
.await
.unwrap();
replacement
.tags()
.await
.unwrap()
.create("replacement", 1)
.await
.unwrap();
let err = if restore {
// This tag resolves to the original branch name, but a different
// BranchIdentifier. Merely comparing branch names cannot catch it.
stale.checkout_tag("replacement").await.unwrap();
stale.restore().await.unwrap_err()
} else {
stale.checkout_latest().await.unwrap_err()
};
assert!(err.to_string().contains("deleted and recreated"), "{err}");
assert_eq!(stale.version().await.unwrap(), if restore { 1 } else { 2 });
assert!(stale.add(sample_rows(vec![999])).execute().await.is_err());
assert!(ordinary_pin.checkout_latest().await.is_err());
// Neither rejection may publish a new version or change either tip.
for (branch, expected_row) in [("main", 100), ("exp", 20)] {
let fresh = conn
.open_table("my_table")
.branch(branch)
.execute()
.await
.unwrap();
assert_eq!(fresh.version().await.unwrap(), 2);
assert_eq!(fresh.count_rows(None).await.unwrap(), 2);
for row in [0, 10, 20, 100, 999] {
assert_eq!(
fresh.count_rows(Some(format!("i = {row}"))).await.unwrap(),
usize::from(row == 0 || row == expected_row),
"unexpected contents on {branch} for row {row}"
);
}
}
}
#[tokio::test]
async fn test_branches() {
let tmp_dir = tempdir().unwrap();
+176 -14
View File
@@ -7,6 +7,7 @@ use std::{
};
use lance::{Dataset, dataset::refs};
use tokio::sync::OnceCell;
use crate::table::merge::lsm::ShardWriterCache;
use crate::{Error, error::Result, utils::background_cache::BackgroundCache};
@@ -29,6 +30,11 @@ pub struct DatasetConsistencyWrapper {
#[derive(Debug, Clone)]
struct DatasetState {
dataset: Arc<Dataset>,
/// The handle's branch, independent of the branch of a pinned snapshot.
tracking_branch: Option<String>,
/// Capture the identity before time travel replaces the dataset that holds
/// it. Snapshot copies share the identity, even while reading other branches.
tracking_branch_identifier: Arc<OnceCell<refs::BranchIdentifier>>,
/// `Some(version)` = pinned to a specific version (time travel),
/// `None` = tracking latest.
pinned_version: Option<u64>,
@@ -59,6 +65,7 @@ enum ConsistencyMode {
impl DatasetConsistencyWrapper {
/// Create a new wrapper in the latest version mode.
pub fn new_latest(dataset: Dataset, read_consistency_interval: Option<Duration>) -> Self {
let tracking_branch = dataset.manifest().branch.clone();
let dataset = Arc::new(dataset);
let consistency = match read_consistency_interval {
Some(d) if d == Duration::ZERO => ConsistencyMode::Strong,
@@ -73,6 +80,8 @@ impl DatasetConsistencyWrapper {
Self {
state: Arc::new(Mutex::new(DatasetState {
dataset,
tracking_branch,
tracking_branch_identifier: Arc::new(OnceCell::new()),
pinned_version: None,
query_snapshot: false,
})),
@@ -98,6 +107,21 @@ impl DatasetConsistencyWrapper {
wrapper
}
/// Pin an independent handle to the visible snapshot, retaining the branch
/// that `as_latest` will reattach to.
pub async fn new_snapshot(&self, read_consistency_interval: Option<Duration>) -> Result<Self> {
self.get().await?;
let state = self.state.lock()?.clone();
let wrapper =
Self::new_time_travel(state.dataset.as_ref().clone(), read_consistency_interval);
{
let mut snapshot_state = wrapper.state.lock()?;
snapshot_state.tracking_branch = state.tracking_branch;
snapshot_state.tracking_branch_identifier = state.tracking_branch_identifier;
}
Ok(wrapper)
}
/// Create an independent read-only wrapper pinned to the current dataset
/// while retaining this wrapper's live RTE read context.
pub async fn new_query_snapshot(&self) -> Result<Self> {
@@ -107,12 +131,14 @@ impl DatasetConsistencyWrapper {
// be cloned together from one authoritative state sample below.
self.get().await?;
let (dataset, query_snapshot) = {
let (dataset, tracking_branch, tracking_branch_identifier, query_snapshot) = {
let state = self.state.lock()?;
// Preserve user time travel so the RTE safety guard still sees
// it. Latest and already-internal snapshots remain internal pins.
(
state.dataset.clone(),
state.tracking_branch.clone(),
state.tracking_branch_identifier.clone(),
state.query_snapshot || state.pinned_version.is_none(),
)
};
@@ -120,6 +146,8 @@ impl DatasetConsistencyWrapper {
Ok(Self {
state: Arc::new(Mutex::new(DatasetState {
dataset,
tracking_branch,
tracking_branch_identifier,
pinned_version: Some(version),
query_snapshot,
})),
@@ -180,10 +208,9 @@ impl DatasetConsistencyWrapper {
/// is silently ignored — the write already committed to storage.
pub fn update(&self, dataset: Dataset) {
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
if state.pinned_version.is_some() {
// A concurrent as_time_travel() beat us here. The write succeeded
// in storage, but since we're now pinned we don't advance the
// cached pointer.
if state.pinned_version.is_some() || dataset.manifest().branch != state.tracking_branch {
// A concurrent checkout beat us here. The write succeeded in
// storage, but must not replace a pin or another branch's pointer.
return;
}
if dataset.manifest().version >= state.dataset.manifest().version {
@@ -202,6 +229,8 @@ impl DatasetConsistencyWrapper {
let new_dataset = dataset.checkout_branch(&branch).await?;
let mut state = self.state.lock()?;
state.tracking_branch = new_dataset.manifest().branch.clone();
state.tracking_branch_identifier = Arc::new(OnceCell::new());
state.dataset = Arc::new(new_dataset);
state.pinned_version = None;
state.query_snapshot = false;
@@ -225,7 +254,7 @@ impl DatasetConsistencyWrapper {
}
}
/// The branch this wrapper is currently tracking, or `None` for `main`.
/// The branch of the visible snapshot, or `None` for `main`.
pub fn current_branch(&self) -> Option<String> {
self.state
.lock()
@@ -236,6 +265,73 @@ impl DatasetConsistencyWrapper {
.clone()
}
/// The branch to reattach to after time travel, or `None` for `main`.
#[doc(hidden)]
pub fn tracking_branch(&self) -> Option<String> {
self.state
.lock()
.unwrap_or_else(|e| e.into_inner())
.tracking_branch
.clone()
}
/// Retain the original branch identity in serialized handle state.
#[doc(hidden)]
pub async fn tracking_branch_identifier(&self) -> Result<refs::BranchIdentifier> {
let state = self.state.lock()?.clone();
Ok(state
.tracking_branch_identifier
.get_or_try_init(|| state.dataset.branch_identifier())
.await?
.clone())
}
/// Restore the original identity after reopening a serialized handle.
/// A foreign snapshot can still be read, but reattachment and restore must
/// validate against this identity rather than the newly opened branch.
#[doc(hidden)]
pub async fn set_tracking_branch_identifier(
&self,
identifier: refs::BranchIdentifier,
) -> Result<()> {
let state = self.state.lock()?.clone();
if state.pinned_version.is_none()
|| state.dataset.manifest().branch == state.tracking_branch
{
// Do not expose a writable replacement branch, or read replacement
// data at the same version as an original same-branch snapshot.
validate_branch_identity(&state.dataset, &identifier).await?;
}
self.state.lock()?.tracking_branch_identifier =
Arc::new(OnceCell::new_with(Some(identifier)));
Ok(())
}
/// Validate restore against the handle's branch before any commit is made.
pub(crate) async fn restore_target(&self) -> Result<Arc<Dataset>> {
let state = self.state.lock()?.clone();
if state.pinned_version.is_none() || state.query_snapshot {
return Err(Error::InvalidInput {
message: "you must run checkout before running restore".to_string(),
});
}
if state.dataset.manifest().branch != state.tracking_branch {
return Err(Error::InvalidInput {
message: format!(
"cannot restore a snapshot on branch '{}' with a handle scoped to branch '{}'; open a handle on the snapshot's branch before restoring",
state.dataset.manifest().branch.as_deref().unwrap_or("main"),
state.tracking_branch.as_deref().unwrap_or("main"),
),
});
}
let identifier = state
.tracking_branch_identifier
.get_or_try_init(|| state.dataset.branch_identifier())
.await?;
validate_branch_identity(&state.dataset, identifier).await?;
Ok(state.dataset)
}
/// Returns the version, if in time travel mode, or None otherwise.
pub fn time_travel_version(&self) -> Option<u64> {
let state = self.state.lock().unwrap_or_else(|e| e.into_inner());
@@ -246,19 +342,33 @@ impl DatasetConsistencyWrapper {
/// Convert into a wrapper in latest version mode.
pub async fn as_latest(&self) -> Result<()> {
let dataset = {
let (dataset, tracking_branch, tracking_branch_identifier) = {
let state = self.state.lock()?;
if state.pinned_version.is_none() {
return Ok(());
}
state.dataset.clone()
(
state.dataset.clone(),
state.tracking_branch.clone(),
state.tracking_branch_identifier.clone(),
)
};
let latest_version = dataset.latest_version_id().await?;
let new_dataset = dataset.checkout_version(latest_version).await?;
let identifier = tracking_branch_identifier
.get_or_try_init(|| dataset.branch_identifier())
.await?;
let new_dataset = dataset
.checkout_version(refs::Ref::Version(tracking_branch.clone(), None))
.await?;
validate_branch_identity(&new_dataset, identifier).await?;
let mut state = self.state.lock()?;
if state.pinned_version.is_some() {
if state.pinned_version.is_some()
&& Arc::ptr_eq(
&state.tracking_branch_identifier,
&tracking_branch_identifier,
)
{
state.dataset = Arc::new(new_dataset);
state.pinned_version = None;
state.query_snapshot = false;
@@ -270,27 +380,42 @@ impl DatasetConsistencyWrapper {
Ok(())
}
/// Pin to a snapshot without changing the handle's tracking branch.
/// Numeric versions resolve on the visible snapshot's branch; tags and
/// explicit branch/version references can select another branch for reading.
pub async fn as_time_travel(&self, target_version: impl Into<refs::Ref>) -> Result<()> {
let target_ref = target_version.into();
let (should_checkout, dataset) = {
let (should_checkout, dataset, tracking_branch_identifier) = {
let state = self.state.lock()?;
let should = match state.pinned_version {
None => true,
Some(version) => match &target_ref {
refs::Ref::Version(_, Some(target_ver)) => version != *target_ver,
refs::Ref::Version(branch, Some(target_ver)) => {
version != *target_ver
|| branch.as_deref() != state.dataset.manifest().branch.as_deref()
}
refs::Ref::Version(_, None) => true,
refs::Ref::VersionNumber(target_ver) => version != *target_ver,
refs::Ref::Tag(_) => true,
},
};
(should, state.dataset.clone())
(
should,
state.dataset.clone(),
state.tracking_branch_identifier.clone(),
)
};
if !should_checkout {
return Ok(());
}
// Once the visible snapshot leaves this branch, its Dataset can no
// longer detect reuse of the original name. Retain that identity first.
tracking_branch_identifier
.get_or_try_init(|| dataset.branch_identifier())
.await?;
let new_dataset = dataset.checkout_version(target_ref).await?;
let version_value = new_dataset.version().version;
@@ -332,6 +457,22 @@ impl DatasetConsistencyWrapper {
}
}
async fn validate_branch_identity(
dataset: &Dataset,
expected: &refs::BranchIdentifier,
) -> Result<()> {
if &dataset.branch_identifier().await? != expected {
return Err(lance::Error::RefNotFound {
message: format!(
"branch {} was deleted and recreated",
dataset.manifest().branch.as_deref().unwrap_or("main")
),
}
.into());
}
Ok(())
}
async fn refresh_latest(state: Arc<Mutex<DatasetState>>) -> Result<Arc<Dataset>> {
let dataset = { state.lock()?.dataset.clone() };
@@ -342,6 +483,7 @@ async fn refresh_latest(state: Arc<Mutex<DatasetState>>) -> Result<Arc<Dataset>>
{
let mut state = state.lock()?;
if state.pinned_version.is_none()
&& new_arc.manifest().branch == state.tracking_branch
&& new_arc.manifest().version >= state.dataset.manifest().version
{
state.dataset = new_arc.clone();
@@ -864,5 +1006,25 @@ mod tests {
// get() returns the branch dataset
let on_branch = wrapper.get().await.unwrap();
assert_eq!(on_branch.manifest().branch.as_deref(), Some("exp"));
// Cross-branch snapshots keep the branch selected by as_branch,
// including when an internal query snapshot is taken.
wrapper.as_time_travel(("main", v1)).await.unwrap();
assert_eq!(wrapper.current_branch(), None);
let snapshot = wrapper.new_query_snapshot().await.unwrap();
assert!(snapshot.restore_target().await.is_err());
snapshot.as_latest().await.unwrap();
assert_eq!(snapshot.current_branch().as_deref(), Some("exp"));
wrapper.as_latest().await.unwrap();
assert_eq!(wrapper.current_branch().as_deref(), Some("exp"));
// Internal query snapshots must retain the original identity, too.
wrapper.as_time_travel(("main", v1)).await.unwrap();
let snapshot = wrapper.new_query_snapshot().await.unwrap();
let mut main = wrapper.get().await.unwrap().as_ref().clone();
main.delete_branch("exp").await.unwrap();
main.create_branch("exp", v1, None).await.unwrap();
assert!(snapshot.as_latest().await.is_err());
assert!(wrapper.as_latest().await.is_err());
}
}