mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-28 05:24:00 +00:00
fix: preserve original branch across tag time travel
This commit is contained in:
@@ -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: ...
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -2094,6 +2094,40 @@ 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()))
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
|
||||
Reference in New Issue
Block a user