diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 98472c41c..6317f809b 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -731,6 +731,8 @@ class Table: 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: ... diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 8804b8100..cd2f05d88 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -4547,6 +4547,11 @@ class LanceTable(Table): 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]: @@ -4582,6 +4587,9 @@ class LanceTable(Table): "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, } @@ -10033,6 +10041,14 @@ class AsyncTable: """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 diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 5debb67de..25703799e 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1297,6 +1297,69 @@ def test_lance_table_pickle_preserves_cross_branch_tag_checkout(tmp_path): 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]})) diff --git a/python/src/table.rs b/python/src/table.rs index cc8855ab2..8690acb83 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2103,6 +2103,40 @@ impl Table { .unwrap_or_else(|| inner.current_branch())) } + /// Serialize the original branch identity as opaque pickle state. + pub fn _tracking_branch_identifier(self_: PyRef<'_, Self>) -> PyResult> { + 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> { + 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( diff --git a/rust/lancedb/src/table/dataset.rs b/rust/lancedb/src/table/dataset.rs index 6316b9d1e..2a1deb44d 100644 --- a/rust/lancedb/src/table/dataset.rs +++ b/rust/lancedb/src/table/dataset.rs @@ -275,6 +275,38 @@ impl DatasetConsistencyWrapper { .clone() } + /// Retain the original branch identity in serialized handle state. + #[doc(hidden)] + pub async fn tracking_branch_identifier(&self) -> Result { + 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> { let state = self.state.lock()?.clone();