diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 5d8cd1c86..01258aa4a 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -191,9 +191,10 @@ 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 local mode, a tag must reference this handle's branch. A tag on another -branch is rejected without changing the handle. Use [Branches.checkout](Branches.md#checkout) -to open a handle scoped to that branch before checking out its tag. +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 @@ -524,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 @@ -1672,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/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 0971d66f9..7444ac961 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4129,6 +4129,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 9888a5e2b..dbd773348 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -1426,9 +1426,10 @@ 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 local mode, a tag must reference this handle's branch. A tag on another - * branch is rejected without changing the handle. Use {@link Branches.checkout} - * to open a handle scoped to that branch before checking out its tag. + * 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 @@ -1487,16 +1488,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..98472c41c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -730,6 +730,8 @@ 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 _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 da55fc610..8804b8100 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1598,7 +1598,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( @@ -4239,10 +4243,11 @@ class Table(ABC): version. As a consequence, calling this method will disable any read consistency interval that was previously set. - In local mode, a tag must reference this handle's branch. A tag on another - branch raises `ValueError` without changing the handle. Use - [branches.checkout()][lancedb.table.Branches.checkout] to open a handle - scoped to that branch before checking out its tag. + 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 @@ -4282,6 +4287,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 @@ -4530,10 +4539,14 @@ 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 return table def __getstate__(self) -> dict[str, Any]: @@ -4552,9 +4565,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, @@ -4569,6 +4581,7 @@ 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(), "checkout_version": self._checkout_version, } @@ -4886,7 +4899,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": @@ -4930,10 +4947,11 @@ 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 must reference this handle's branch. A tag on another branch raises - `ValueError` without changing the handle. Use + 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 - scoped to that branch before checking out its tag. + on that branch before restoring its tag. Parameters ---------- @@ -4981,6 +4999,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 @@ -5020,7 +5042,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() @@ -10007,6 +10029,10 @@ 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 list_versions(self): """ List all versions of the table @@ -10044,10 +10070,11 @@ class AsyncTable: version. As a consequence, calling this method will disable any read consistency interval that was previously set. - In local mode, a tag must reference this handle's branch. A tag on another - branch raises `ValueError` without changing the handle. Use - [branches.checkout()][lancedb.table.AsyncBranches.checkout] to open a handle - scoped to that branch before checking out its tag. + 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 @@ -10093,6 +10120,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 @@ -10304,7 +10335,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 7ec1e8dd6..5debb67de 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1279,6 +1279,85 @@ 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] + + +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..cc8855ab2 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2094,6 +2094,40 @@ impl Table { }) } + /// The branch to reattach to after time travel, for pickle reopen state. + pub fn _tracking_branch(&self) -> PyResult> { + let inner = self.inner_ref()?; + Ok(inner + .dataset() + .map(|dataset| dataset.tracking_branch()) + .unwrap_or_else(|| inner.current_branch())) + } + + /// Reopen an exact snapshot without changing the handle's tracking branch. + #[pyo3(signature = (branch, version))] + pub fn _checkout_snapshot( + self_: PyRef<'_, Self>, + branch: Option, + version: u64, + ) -> PyResult> { + 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>, diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 39cdd7e0a..37563bc1e 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -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; /// Get the table definition. async fn table_definition(&self) -> Result; @@ -3083,9 +3085,10 @@ impl Table { /// As a consequence, calling this method will disable any read consistency interval /// that was previously set. /// - /// In local mode, the tag must reference this handle's branch. A tag on another - /// branch is rejected without changing the handle. Use [`Self::checkout_branch`] - /// to obtain a handle scoped to that branch first. + /// 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 @@ -3109,6 +3112,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 @@ -3486,7 +3492,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 { self.inner.current_branch() } @@ -4477,11 +4485,10 @@ impl BaseTable for NativeTable { } async fn checkout_current(&self) -> Result> { - 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() @@ -4582,18 +4589,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()?.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?; @@ -5873,7 +5872,7 @@ mod tests { #[case(Some(Duration::ZERO))] #[case(Some(Duration::from_secs(60)))] #[tokio::test] - async fn test_checkout_tag_rejects_other_branch(#[case] interval: Option) { + async fn test_checkout_tag_preserves_handle_branch(#[case] interval: Option) { let tmp_dir = tempdir().unwrap(); let mut builder = ConnectBuilder::new(tmp_dir.path().to_str().unwrap()); if let Some(interval) = interval { @@ -5892,98 +5891,146 @@ mod tests { (&exp, "exp", 10), (&other, "other", 20), ]; - for (handle, tag, row) in handles { handle.add(sample_rows(vec![row])).execute().await.unwrap(); - // All tags have the same version number but different branch data. + // 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_tag, row) in handles { - for (_, foreign_tag, _) in handles { - if foreign_tag == own_tag { + for (handle, own_branch, own_row) in handles { + for (_, foreign_branch, foreign_row) in handles { + if foreign_branch == own_branch { continue; } - let err = handle.checkout_tag(foreign_tag).await.unwrap_err(); + 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}"); - // A failed checkout must not pin a previously writable handle. - assert!(handle.restore().await.is_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) + ); } - - handle.checkout_tag(own_tag).await.unwrap(); - for (_, foreign_tag, _) in handles { - if foreign_tag != own_tag { - assert!(matches!( - handle.checkout_tag(foreign_tag).await, - Err(Error::InvalidInput { .. }) - )); - // The wrapper's explicit branch/version references must - // also check the branch when version numbers are equal. - assert!(matches!( - handle - .dataset() - .unwrap() - .as_time_travel((foreign_tag, 2u64)) - .await, - Err(Error::InvalidInput { .. }) - )); - } - } - let expected_branch = (own_tag != "main").then_some(own_tag); - assert_eq!(handle.current_branch().as_deref(), expected_branch); - assert_eq!(handle.version().await.unwrap(), 2); - assert_eq!(handle.count_rows(None).await.unwrap(), 2); - assert_eq!( - handle.count_rows(Some(format!("i = {row}"))).await.unwrap(), - 1 - ); - assert!(handle.add(sample_rows(vec![999])).execute().await.is_err()); - - handle.checkout_latest().await.unwrap(); - assert_eq!(handle.current_branch().as_deref(), expected_branch); - handle - .add(sample_rows(vec![row + 1])) - .execute() - .await - .unwrap(); } - for (_, branch, own_row) in handles { + // 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(); - for (_, _, row) in handles { + 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 = {}", row + 1))) + .count_rows(Some(format!("i = {}", candidate + 1))) .await .unwrap(), - usize::from(row == own_row), - "write must stay on {branch}" + usize::from(candidate == row) ); } - } - - for (handle, own_tag, row) in handles { - handle.checkout_tag(own_tag).await.unwrap(); - for (_, foreign_tag, _) in handles { - if foreign_tag != own_tag { - assert!(handle.checkout_tag(foreign_tag).await.is_err()); - } - } + handle.checkout_tag(branch).await.unwrap(); handle.restore().await.unwrap(); - assert_eq!(handle.version().await.unwrap(), 4); + } + // 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!( - handle.current_branch().as_deref(), - (own_tag != "main").then_some(own_tag) - ); - assert_eq!(handle.count_rows(None).await.unwrap(), 2); - assert_eq!( - handle.count_rows(Some(format!("i = {row}"))).await.unwrap(), + fresh.count_rows(Some(format!("i = {row}"))).await.unwrap(), 1 ); } diff --git a/rust/lancedb/src/table/dataset.rs b/rust/lancedb/src/table/dataset.rs index aff7cc5dd..1b2fc6d5f 100644 --- a/rust/lancedb/src/table/dataset.rs +++ b/rust/lancedb/src/table/dataset.rs @@ -29,6 +29,8 @@ pub struct DatasetConsistencyWrapper { #[derive(Debug, Clone)] struct DatasetState { dataset: Arc, + /// The handle's branch, independent of the branch of a pinned snapshot. + tracking_branch: Option, /// `Some(version)` = pinned to a specific version (time travel), /// `None` = tracking latest. pinned_version: Option, @@ -59,6 +61,7 @@ enum ConsistencyMode { impl DatasetConsistencyWrapper { /// Create a new wrapper in the latest version mode. pub fn new_latest(dataset: Dataset, read_consistency_interval: Option) -> 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 +76,7 @@ impl DatasetConsistencyWrapper { Self { state: Arc::new(Mutex::new(DatasetState { dataset, + tracking_branch, pinned_version: None, query_snapshot: false, })), @@ -98,6 +102,17 @@ 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) -> Result { + self.get().await?; + let state = self.state.lock()?.clone(); + let wrapper = + Self::new_time_travel(state.dataset.as_ref().clone(), read_consistency_interval); + wrapper.state.lock()?.tracking_branch = state.tracking_branch; + 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 { @@ -107,12 +122,13 @@ impl DatasetConsistencyWrapper { // be cloned together from one authoritative state sample below. self.get().await?; - let (dataset, query_snapshot) = { + let (dataset, tracking_branch, 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.query_snapshot || state.pinned_version.is_none(), ) }; @@ -120,6 +136,7 @@ impl DatasetConsistencyWrapper { Ok(Self { state: Arc::new(Mutex::new(DatasetState { dataset, + tracking_branch, pinned_version: Some(version), query_snapshot, })), @@ -180,10 +197,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 +218,7 @@ 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.dataset = Arc::new(new_dataset); state.pinned_version = None; state.query_snapshot = false; @@ -225,7 +242,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 { self.state .lock() @@ -236,6 +253,36 @@ impl DatasetConsistencyWrapper { .clone() } + /// The branch to reattach to after time travel, or `None` for `main`. + #[doc(hidden)] + pub fn tracking_branch(&self) -> Option { + self.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .tracking_branch + .clone() + } + + /// Validate restore against the handle's branch before any commit is made. + pub(crate) fn restore_target(&self) -> Result> { + let state = self.state.lock()?; + 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"), + ), + }); + } + Ok(state.dataset.clone()) + } + /// Returns the version, if in time travel mode, or None otherwise. pub fn time_travel_version(&self) -> Option { let state = self.state.lock().unwrap_or_else(|e| e.into_inner()); @@ -246,19 +293,20 @@ impl DatasetConsistencyWrapper { /// Convert into a wrapper in latest version mode. pub async fn as_latest(&self) -> Result<()> { - let dataset = { + let (dataset, tracking_branch) = { let state = self.state.lock()?; if state.pinned_version.is_none() { return Ok(()); } - state.dataset.clone() + (state.dataset.clone(), state.tracking_branch.clone()) }; - let latest_version = dataset.latest_version_id().await?; - let new_dataset = dataset.checkout_version(latest_version).await?; + let new_dataset = dataset + .checkout_version(refs::Ref::Version(tracking_branch.clone(), None)) + .await?; let mut state = self.state.lock()?; - if state.pinned_version.is_some() { + if state.pinned_version.is_some() && state.tracking_branch == tracking_branch { state.dataset = Arc::new(new_dataset); state.pinned_version = None; state.query_snapshot = false; @@ -270,9 +318,9 @@ impl DatasetConsistencyWrapper { Ok(()) } - /// Pin to a version on this wrapper's current branch. - /// - /// References to another branch are rejected without changing the state. + /// 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) -> Result<()> { let target_ref = target_version.into(); @@ -301,16 +349,6 @@ impl DatasetConsistencyWrapper { let version_value = new_dataset.version().version; let mut state = self.state.lock()?; - // Time travel must not change the branch used by checkout_latest or restore. - if new_dataset.manifest().branch != state.dataset.manifest().branch { - return Err(Error::InvalidInput { - message: format!( - "cannot check out a version on branch '{}' with a handle scoped to branch '{}'; use a handle scoped to the target branch instead", - new_dataset.manifest().branch.as_deref().unwrap_or("main"), - state.dataset.manifest().branch.as_deref().unwrap_or("main"), - ), - }); - } state.dataset = Arc::new(new_dataset); state.pinned_version = Some(version_value); state.query_snapshot = false; @@ -358,6 +396,7 @@ async fn refresh_latest(state: Arc>) -> Result> { 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(); @@ -880,5 +919,16 @@ 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().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")); } }