mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat(python): support table checkout by timestamp (#5221)
Python callers can pass a `datetime` to `Table.checkout()` and `AsyncTable.checkout()` to read several tables as of a single cutoff. Each table is pinned to the highest retained version on its current branch whose reported commit timestamp is at or before the cutoff. A cutoff before all retained versions raises `ValueError`. The Rust `Table::checkout_as_of` method scans the branch's retained history and compares the commit timestamps at the precision supplied by the backend. On Embedded it resolves and checks out the version on the same dataset. If a concurrent tag checkout moves the handle to another branch, it retries there before pinning the handle. On Enterprise it follows all version-history pages on the same branch before checking out the selected version. Servers that report only whole milliseconds can group commits on opposite sides of a cutoff. For an exact reread, record both the branch and version of each input after checkout, then reopen the table with both values. Python interprets naive datetimes in the system's local time zone and honors explicit UTC offsets. The website guide includes a draft paragraph for the SDK release. Closes #2293. ## Validation - Built the Windows x64 native extension from this checkout with the repository's `ci` profile and CPython 3.12. - `test_table.py` passed 558 tests with 20 skips. `test_remote_db.py` passed 759 tests with 2 skips using its HTTP test server. - The new tests cover two tables at one cutoff, pinning after later writes, recovery with `checkout_latest()`, a cutoff before the first version, non-UTC input, tied commits, and a commit one nanosecond past the cutoff. All three also passed with `TZ=EST5EDT`. - A real Embedded handle switching branches during timestamp lookup selected the wrong branch version in 40/40 attempts before the concurrency fix and the expected version in 40/40 attempts afterward. The Rust regression test forces that interleaving with a filesystem-backed table. - A two-page Enterprise HTTP fixture reproduced checkout at v1 with the previous SDK and confirmed checkout at v2 after the fix. The Rust regression asserts the branch and continuation token on page two and reads back the pinned version. A separate test covers empty intermediate pages and repeated tokens. - Both Rust branch checkout tests and the `Table::checkout_as_of` doctest passed with the `remote` feature enabled. - Python SDK Ruff checks and formatting, Pyright, Rust formatting, and Vale passed. Repository-wide Ruff reports 59 existing diagnostics in the unchanged `docs/web-tests` files. --------- Co-authored-by: lipeih <lipeihan@eazytec.com>
This commit is contained in:
@@ -733,6 +733,7 @@ class Table:
|
||||
to_version: Optional[Union[int, str]] = None,
|
||||
) -> TableDelta: ...
|
||||
async def checkout(self, version: Union[int, str]): ...
|
||||
async def checkout_as_of(self, timestamp: datetime) -> None: ...
|
||||
async def checkout_latest(self): ...
|
||||
async def _checkout_current(self) -> Table: ...
|
||||
def _tracking_branch(self) -> Optional[str]: ...
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from datetime import timedelta
|
||||
from datetime import datetime, timedelta
|
||||
import deprecation
|
||||
import logging
|
||||
from functools import cached_property, wraps
|
||||
@@ -331,8 +331,11 @@ class RemoteTable(Table):
|
||||
"Use table.search().to_polars() instead."
|
||||
)
|
||||
|
||||
def checkout(self, version: Union[int, str]):
|
||||
"""Check out a version number or tag as a read-only view in place.
|
||||
def checkout(self, version: Union[int, str, datetime]):
|
||||
"""Check out a version number, tag, or timestamp as a read-only view in place.
|
||||
|
||||
A timestamp selects the highest retained version on this branch whose
|
||||
reported commit time is at or before the cutoff.
|
||||
|
||||
A tag must belong to this handle's current branch. To read a tag on
|
||||
another branch, first obtain that branch's handle with
|
||||
|
||||
@@ -11,7 +11,7 @@ import warnings
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from functools import cached_property
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
@@ -4290,7 +4290,7 @@ class Table(ABC):
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def checkout(self, version: Union[int, str]):
|
||||
def checkout(self, version: Union[int, str, datetime]):
|
||||
"""
|
||||
Checks out a specific version of the Table
|
||||
|
||||
@@ -4306,11 +4306,11 @@ class Table(ABC):
|
||||
|
||||
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.
|
||||
change permanent you can use [restore][lancedb.table.Table.restore].
|
||||
|
||||
Any operation that modifies the table will fail while the table is in a checked
|
||||
out state. To return the table to a normal state use
|
||||
`[Self::checkout_latest]`.
|
||||
[checkout_latest][lancedb.table.Table.checkout_latest].
|
||||
|
||||
For Enterprise tables, a tag must belong to this handle's current branch.
|
||||
To read a tag on another branch, first obtain that branch's handle with
|
||||
@@ -4320,9 +4320,37 @@ class Table(ABC):
|
||||
|
||||
Parameters
|
||||
----------
|
||||
version: int | str,
|
||||
The version to check out. A version number (`int`) or a tag
|
||||
(`str`) can be provided.
|
||||
version: int | str | datetime
|
||||
A version number, tag, or timestamp. For a timestamp, checkout uses
|
||||
the commit times reported by the backend in this branch's version
|
||||
history. It selects the highest retained version whose reported
|
||||
time is at or before the cutoff. A naive datetime uses the
|
||||
system's local time zone.
|
||||
|
||||
Some Enterprise servers report commit times in whole milliseconds.
|
||||
A commit later in the same millisecond as the cutoff can qualify.
|
||||
To reproduce a report exactly, record each input table's branch
|
||||
and version number after checkout. Reopen each table with
|
||||
`db.open_table(name, branch=branch, version=version)` on later runs.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If no retained version exists at or before the timestamp.
|
||||
|
||||
Examples
|
||||
--------
|
||||
Capture a cutoff before opening the tables needed for a report.
|
||||
|
||||
```python
|
||||
from datetime import datetime, timezone
|
||||
|
||||
cutoff = datetime.now(timezone.utc)
|
||||
orders = db.open_table("orders")
|
||||
items = db.open_table("items")
|
||||
orders.checkout(cutoff)
|
||||
items.checkout(cutoff)
|
||||
```
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
@@ -5003,7 +5031,7 @@ class LanceTable(Table):
|
||||
table._checkout_version = version
|
||||
return table
|
||||
|
||||
def checkout(self, version: Union[int, str]):
|
||||
def checkout(self, version: Union[int, str, datetime]):
|
||||
"""Checkout a version of the table. This is an in-place operation.
|
||||
|
||||
This allows viewing previous versions of the table. If you wish to
|
||||
@@ -5021,9 +5049,10 @@ class LanceTable(Table):
|
||||
|
||||
Parameters
|
||||
----------
|
||||
version: int | str,
|
||||
The version to check out. A version number (`int`) or a tag
|
||||
(`str`) can be provided.
|
||||
version: int | str | datetime
|
||||
A version number, tag, or timestamp. See
|
||||
[Table.checkout][lancedb.table.Table.checkout] for timestamp semantics
|
||||
and Enterprise timestamp precision.
|
||||
|
||||
Examples
|
||||
--------
|
||||
@@ -10154,7 +10183,7 @@ class AsyncTable:
|
||||
"""
|
||||
return AsyncTableDelta(await self._inner.delta(from_version, to_version))
|
||||
|
||||
async def checkout(self, version: int | str):
|
||||
async def checkout(self, version: int | str | datetime):
|
||||
"""
|
||||
Checks out a specific version of the Table
|
||||
|
||||
@@ -10170,11 +10199,11 @@ class AsyncTable:
|
||||
|
||||
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.
|
||||
change permanent you can use [restore][lancedb.table.AsyncTable.restore].
|
||||
|
||||
Any operation that modifies the table will fail while the table is in a checked
|
||||
out state. To return the table to a normal state use
|
||||
`[Self::checkout_latest]`.
|
||||
[checkout_latest][lancedb.table.AsyncTable.checkout_latest].
|
||||
|
||||
For Enterprise tables, a tag must belong to this handle's current branch.
|
||||
To read a tag on another branch, first obtain that branch's handle with
|
||||
@@ -10184,12 +10213,16 @@ class AsyncTable:
|
||||
|
||||
Parameters
|
||||
----------
|
||||
version: int | str,
|
||||
The version to check out. A version number (`int`) or a tag
|
||||
(`str`) can be provided.
|
||||
version: int | str | datetime
|
||||
A version number, tag, or timestamp. See
|
||||
[Table.checkout][lancedb.table.Table.checkout] for timestamp semantics
|
||||
and Enterprise timestamp precision.
|
||||
"""
|
||||
try:
|
||||
await self._inner.checkout(version)
|
||||
if isinstance(version, datetime):
|
||||
await self._inner.checkout_as_of(version.astimezone(timezone.utc))
|
||||
else:
|
||||
await self._inner.checkout(version)
|
||||
except RuntimeError as e:
|
||||
if "not found" in str(e):
|
||||
raise ValueError(
|
||||
|
||||
@@ -5,7 +5,7 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
import contextlib
|
||||
import copy
|
||||
from dataclasses import replace
|
||||
from datetime import timedelta
|
||||
from datetime import datetime, timedelta
|
||||
import http.server
|
||||
import io
|
||||
import inspect
|
||||
@@ -1071,6 +1071,34 @@ async def test_async_checkout():
|
||||
assert await table.count_rows() == 300
|
||||
|
||||
|
||||
def test_remote_checkout_timestamp():
|
||||
def handler(request):
|
||||
if request.path == "/v1/table/test/version/list/":
|
||||
# Two versions share the cutoff. The next commit is one nanosecond later.
|
||||
payload = {
|
||||
"versions": [
|
||||
{"version": 5, "timestamp": "2024-01-02T03:04:05.123456001Z"},
|
||||
{"version": 4, "timestamp": "2024-01-02T03:04:05.123456Z"},
|
||||
{"version": 3, "timestamp": "2024-01-02T03:04:05.123456Z"},
|
||||
]
|
||||
}
|
||||
else:
|
||||
assert request.path == "/v1/table/test/describe/"
|
||||
body = json.loads(request.rfile.read() or b"{}")
|
||||
payload = {"version": body.get("version") or 5, "schema": {"fields": []}}
|
||||
request.send_response(200)
|
||||
request.end_headers()
|
||||
request.wfile.write(json.dumps(payload).encode())
|
||||
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = db.open_table("test")
|
||||
cutoff = datetime.fromisoformat("2024-01-02T04:04:05.123456+01:00")
|
||||
table.checkout(cutoff)
|
||||
assert table.version == 4
|
||||
table.checkout(cutoff + timedelta(microseconds=1))
|
||||
assert table.version == 5
|
||||
|
||||
|
||||
def _branch_open_handler(request):
|
||||
if "/branches/list" in request.path:
|
||||
body = json.dumps(
|
||||
|
||||
@@ -13,7 +13,7 @@ import warnings
|
||||
import weakref
|
||||
from collections import UserDict
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import date, datetime, timedelta
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from decimal import Decimal, localcontext
|
||||
from time import sleep
|
||||
from types import MappingProxyType
|
||||
@@ -1493,6 +1493,39 @@ def test_lance_table_pickle_preserves_namespace_path(tmp_path):
|
||||
assert restored._conn._namespace_client_properties == {"root": str(tmp_path)}
|
||||
|
||||
|
||||
def test_checkout_two_tables_as_of_the_same_timestamp(mem_db: DBConnection):
|
||||
orders = mem_db.create_table("orders", data=[{"id": 1}])
|
||||
items = mem_db.create_table("items", data=[{"id": 1}])
|
||||
items.add([{"id": 2}])
|
||||
# Python displays commit times to microseconds. Use the next representable
|
||||
# instant so the cutoff includes all nanoseconds of the last initial commit.
|
||||
cutoff = items.list_versions()[-1]["timestamp"] + timedelta(microseconds=1)
|
||||
|
||||
orders.add([{"id": 2}])
|
||||
items.add([{"id": 3}])
|
||||
orders.checkout(cutoff)
|
||||
items.checkout(cutoff.astimezone(timezone.utc))
|
||||
|
||||
assert (orders.version, items.version) == (1, 2)
|
||||
assert (orders.count_rows(), items.count_rows()) == (1, 2)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_checkout_timestamp_pins_latest(mem_db_async: AsyncConnection):
|
||||
table = await mem_db_async.create_table("items", data=[{"id": 1}])
|
||||
writer = await mem_db_async.open_table("items")
|
||||
await table.checkout(datetime(2100, 1, 1))
|
||||
await writer.add([{"id": 2}])
|
||||
assert await table.count_rows() == 1
|
||||
|
||||
with pytest.raises(ValueError, match="No table version is available"):
|
||||
await table.checkout(datetime(2000, 1, 1, tzinfo=timezone.utc))
|
||||
assert await table.version() == 1
|
||||
|
||||
await table.checkout_latest()
|
||||
assert await table.count_rows() == 2
|
||||
|
||||
|
||||
def test_versioning(mem_db: DBConnection):
|
||||
table = mem_db.create_table(
|
||||
"test",
|
||||
|
||||
@@ -2087,6 +2087,16 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn checkout_as_of(
|
||||
self_: PyRef<'_, Self>,
|
||||
timestamp: chrono::DateTime<chrono::Utc>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner.checkout_as_of(timestamp).await.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn checkout_latest(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
|
||||
Reference in New Issue
Block a user