From 2d4e0fb3f2c16065e9ae0cc29fb799000b523b41 Mon Sep 17 00:00:00 2001
From: "lancedb-gatefixer[bot]"
<313497061+lancedb-gatefixer[bot]@users.noreply.github.com>
Date: Mon, 30 Nov 2026 20:05:58 +0800
Subject: [PATCH] fix: preserve branch scope during Embedded tag time travel
(#4852)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
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
## 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).
Snapshot:
[078ecea](https://github.com/lancedb/lancedb/commit/078eceadbedc15cf179d9d4dcce249c83e7010f9)
---------
Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com>
---
docs/src/js/classes/Table.md | 14 +-
docs/web/management/table.mdx | 18 +-
nodejs/__test__/table.test.ts | 37 ++++
nodejs/lancedb/table.ts | 15 +-
python/python/lancedb/_lancedb.pyi | 4 +
python/python/lancedb/table.py | 88 +++++++--
python/python/tests/test_table.py | 142 ++++++++++++++
python/src/table.rs | 68 +++++++
rust/lancedb/src/table.rs | 298 +++++++++++++++++++++++++++--
rust/lancedb/src/table/dataset.rs | 190 ++++++++++++++++--
10 files changed, 820 insertions(+), 54 deletions(-)
diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md
index ad20d1e0a..01258aa4a 100644
--- a/docs/src/js/classes/Table.md
+++ b/docs/src/js/classes/Table.md
@@ -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
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
diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx
index 23e666cc8..d07b7d3fb 100644
--- a/docs/web/management/table.mdx
+++ b/docs/web/management/table.mdx
@@ -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.
diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts
index 00d20521b..73e8c6ffd 100644
--- a/nodejs/__test__/table.test.ts
+++ b/nodejs/__test__/table.test.ts
@@ -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,
diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts
index 973cdde40..46deb2f72 100644
--- a/nodejs/lancedb/table.ts
+++ b/nodejs/lancedb/table.ts
@@ -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;
/**
- * 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
diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi
index 1080626a1..6317f809b 100644
--- a/python/python/lancedb/_lancedb.pyi
+++ b/python/python/lancedb/_lancedb.pyi
@@ -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: ...
diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py
index d6f26de8b..cd8c47f8e 100644
--- a/python/python/lancedb/table.py
+++ b/python/python/lancedb/table.py
@@ -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(
diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py
index 8ec52eb35..13602db7a 100644
--- a/python/python/tests/test_table.py
+++ b/python/python/tests/test_table.py
@@ -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)
diff --git a/python/src/table.rs b/python/src/table.rs
index 9e1ef3821..8690acb83 100644
--- a/python/src/table.rs
+++ b/python/src/table.rs
@@ -2094,6 +2094,74 @@ impl Table {
})
}
+ /// The branch to reattach to after time travel, for pickle reopen state.
+ pub fn _tracking_branch(&self) -> PyResult