diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index d07b7d3fb..6667b4e98 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -1710,6 +1710,24 @@ First, let's see all the versions we've created: +{/* +Draft for the Python timestamp checkout release. + +In Python, pass a `datetime` to `table.checkout(cutoff)` to read a table as of +that instant. The backend reports the commit times in the current branch's +version history. Checkout selects the highest retained version whose reported +time is at or before the cutoff. To read several tables as of the same time, +capture one cutoff with `datetime.now(timezone.utc)` and pass it to each table. +If no retained version qualifies, `checkout()` raises `ValueError`. + +Some Enterprise servers report commit times in whole milliseconds. Two commits +on opposite sides of the cutoff can then share a timestamp, and `checkout()` +selects the higher version. For reproducible reports, record +`table.current_branch()` and `table.version` for each input after checkout. +To read the same snapshot again, pass both values to +`db.open_table(name, branch=branch, version=version)`. +*/} + #### Restore a Version Snapshot {#versioning-restore-a-version-snapshot} Now let's restore a captured version snapshot: diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 0468d9033..853c15b0b 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -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]: ... diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index eee954345..1d462f082 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -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 diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 5dc627eb3..b930b77d6 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -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( diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 684702d78..6342dcaab 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -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( diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 2bed6beb6..b99a90df3 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -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", diff --git a/python/src/table.rs b/python/src/table.rs index 816594af3..d4174e591 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2087,6 +2087,16 @@ impl Table { }) } + pub fn checkout_as_of( + self_: PyRef<'_, Self>, + timestamp: chrono::DateTime, + ) -> PyResult> { + 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> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 1037fd701..2d576887e 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3153,13 +3153,6 @@ impl BaseTable for RemoteTable { } async fn list_versions(&self) -> Result> { - let request = self.apply_branch_query( - self.client - .post(&format!("/v1/table/{}/version/list/", self.identifier)), - ); - let (request_id, response) = self.send(request, true).await?; - let response = self.check_table_response(&request_id, response).await?; - // Servers report the creation time either as an RFC 3339 `timestamp` // (direct-table path) or as `timestamp_millis` in milliseconds since // epoch (namespace-backed path), and may omit `metadata`. @@ -3176,23 +3169,30 @@ impl BaseTable for RemoteTable { #[derive(Deserialize)] struct ListVersionsResponse { versions: Vec, + page_token: Option, } - let body = response.text().await.err_to_http(request_id.clone())?; - let body: ListVersionsResponse = - serde_json::from_str(&body).map_err(|err| Error::Http { - source: format!( - "Failed to parse list_versions response: {}, body: {}", - err, body - ) - .into(), - request_id: request_id.clone(), - status_code: None, - })?; + let path = format!("/v1/table/{}/version/list/", self.identifier); + let mut versions = Vec::new(); + let mut page_token: Option = None; + let mut seen_tokens = HashSet::new(); + loop { + let mut request = self.apply_branch_query(self.client.post(&path)); + if let Some(token) = &page_token { + request = request.query(&[("page_token", token)]); + } + let (request_id, response) = self.send(request, true).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let page: ListVersionsResponse = + serde_json::from_str(&body).map_err(|err| Error::Http { + source: format!("Failed to parse list_versions response: {err}, body: {body}") + .into(), + request_id: request_id.clone(), + status_code: None, + })?; - body.versions - .into_iter() - .map(|entry| { + for entry in page.versions { let timestamp = entry .timestamp .or_else(|| { @@ -3210,14 +3210,26 @@ impl BaseTable for RemoteTable { request_id: request_id.clone(), status_code: None, })?; - Ok(Version { + versions.push(Version { version: entry.version, timestamp, metadata: entry.metadata, manifest_size: entry.manifest_size, - }) - }) - .collect() + }); + } + + let Some(next) = page.page_token.filter(|token| !token.is_empty()) else { + return Ok(versions); + }; + if !seen_tokens.insert(next.clone()) { + return Err(Error::Http { + source: "list_versions response repeated a page_token".into(), + request_id, + status_code: None, + }); + } + page_token = Some(next); + } } async fn schema(&self) -> Result { @@ -10991,6 +11003,95 @@ mod tests { assert_eq!(versions[1].manifest_size, None); } + #[tokio::test] + async fn test_checkout_as_of_paginated_history() { + const TOKEN: &str = "page/2+?"; + let pages = Arc::new(AtomicUsize::new(0)); + let list_requests = pages.clone(); + let table = RemoteTable::new_mock( + "my_table".into(), + move |request| { + assert_eq!(request.method(), "POST"); + let response = match request.url().path() { + "/v1/table/my_table/version/list/" => { + let query: HashMap<_, _> = request.url().query_pairs().collect(); + assert_eq!(query.get("branch").map(|v| v.as_ref()), Some("exp")); + let token = query.get("page_token").map(|v| v.as_ref()); + match list_requests.fetch_add(1, Ordering::SeqCst) { + 0 => { + assert_eq!(token, None); + json!({ + "versions": [{"version": 1, "timestamp_millis": 1000}], + "page_token": TOKEN + }) + } + 1 => { + assert_eq!(token, Some(TOKEN)); + json!({ + "versions": [{"version": 2, "timestamp_millis": 2000}], + "page_token": "" + }) + } + _ => panic!("unexpected version-list request"), + } + } + "/v1/table/my_table/describe/" => { + let body = request_body_json(&request); + assert_eq!(body["branch"], "exp"); + assert_eq!(body["version"], 2); + json!({"version": 2, "schema": {"fields": []}}) + } + path => panic!("unexpected path: {path}"), + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }, + None, + ) + .with_branch(Some("exp".into())); + + let cutoff = DateTime::from_timestamp_millis(2500).unwrap(); + table.checkout_as_of(cutoff).await.unwrap(); + assert_eq!(table.version().await.unwrap(), 2); + assert_eq!(pages.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn test_list_versions_rejects_repeated_page_token() { + let pages = Arc::new(AtomicUsize::new(0)); + let list_requests = pages.clone(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/version/list/"); + let query: HashMap<_, _> = request.url().query_pairs().collect(); + let token = query.get("page_token").map(|v| v.as_ref()); + let response = match list_requests.fetch_add(1, Ordering::SeqCst) { + 0 => { + assert_eq!(token, None); + json!({ + "versions": [{"version": 1, "timestamp_millis": 1000}], + "page_token": "second" + }) + } + 1 => { + assert_eq!(token, Some("second")); + json!({"versions": [], "page_token": "third"}) + } + 2 => { + assert_eq!(token, Some("third")); + json!({"versions": [], "page_token": "third"}) + } + _ => panic!("requested a page after its token was repeated"), + }; + http::Response::new(response.to_string()) + }); + + let err = table.list_versions().await.unwrap_err(); + assert!(err.to_string().contains("repeated a page_token"), "{err}"); + assert_eq!(pages.load(Ordering::SeqCst), 3); + } + /// Namespace-backed servers report `timestamp_millis` instead of /// `timestamp`, and may omit `metadata` entirely. #[tokio::test] diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 280e9a5c4..3889b1cf6 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -7,6 +7,7 @@ use crate::blob::{BlobDescriptor, BlobFile}; use arrow_array::{LargeBinaryArray, RecordBatch, RecordBatchReader}; use arrow_schema::{Schema, SchemaRef}; use async_trait::async_trait; +use chrono::{DateTime, Utc}; use datafusion_execution::TaskContext; use datafusion_expr::Expr; use datafusion_physical_plan::ExecutionPlan; @@ -576,6 +577,17 @@ pub fn tokenize(query: &str, params: &InvertedIndexParams) -> Result, timestamp: DateTime) -> Result { + versions + .into_iter() + .filter(|v| v.timestamp <= timestamp) + .map(|v| v.version) + .max() + .ok_or_else(|| Error::InvalidInput { + message: format!("No table version is available at or before {timestamp}"), + }) +} + /// A trait for anything "table-like". This is used for both native tables (which target /// Lance datasets) and remote tables (which target LanceDB Enterprise) /// @@ -1115,6 +1127,13 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { } /// Checkout a specific version of the table. async fn checkout(&self, version: u64) -> Result<()>; + /// Checkout the highest retained version whose backend-reported commit time is at + /// or before the timestamp. + /// Backends with a mutable branch must resolve and pin on the same branch. + async fn checkout_as_of(&self, timestamp: DateTime) -> Result<()> { + let version = version_as_of(self.list_versions().await?, timestamp)?; + self.checkout(version).await + } /// Checkout a table version referenced by a tag. /// Tags provide a human-readable way to reference specific versions of the table. async fn checkout_tag(&self, tag: &str) -> Result<()>; @@ -3071,6 +3090,29 @@ impl Table { self.inner.checkout(version).await } + /// Pin this table to the highest retained version on its branch whose commit time + /// is at or before `timestamp`. The lookup uses the commit times reported by the + /// backend in the branch's version history and returns an error if none qualifies. + /// Use [`Self::checkout_latest`] to resume reading the latest version. + /// + /// Some Enterprise servers report commit times in whole milliseconds. A commit + /// later in the cutoff millisecond can qualify. To read the same snapshot again, + /// record both [`Self::current_branch`] and [`Self::version`] after checkout + /// and reopen that branch at the recorded version. + /// + /// ``` + /// use chrono::{DateTime, Utc}; + /// use lancedb::Table; + /// + /// # async fn read_as_of(table: &Table, cutoff: DateTime) -> lancedb::Result<()> { + /// table.checkout_as_of(cutoff).await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn checkout_as_of(&self, timestamp: DateTime) -> Result<()> { + self.inner.checkout_as_of(timestamp).await + } + /// Checks out a specific version of the Table by tag /// /// On Enterprise tables, the tag must belong to this handle's branch. Use @@ -4503,6 +4545,10 @@ impl BaseTable for NativeTable { self.dataset.as_time_travel(version).await } + async fn checkout_as_of(&self, timestamp: DateTime) -> Result<()> { + self.dataset.as_of(timestamp).await + } + async fn checkout_tag(&self, tag: &str) -> Result<()> { self.dataset.as_time_travel(tag).await } @@ -6205,6 +6251,13 @@ mod tests { let exp_fork = branch.version().await.unwrap(); // exp's shallow-clone version branch.add(sample_rows(vec![1])).execute().await.unwrap(); // exp: {0, 1} let exp_v2 = branch.version().await.unwrap(); + let exp_v2_time = branch + .list_versions() + .await + .unwrap() + .last() + .unwrap() + .timestamp; branch.add(sample_rows(vec![2])).execute().await.unwrap(); // exp HEAD: {0, 1, 2} // main's own commit reaches the SAME version number with different data @@ -6250,6 +6303,11 @@ mod tests { assert_eq!(pinned_direct.current_branch().as_deref(), Some("exp")); assert_eq!(pinned_direct.count_rows(None).await.unwrap(), 2); + branch.checkout_as_of(exp_v2_time).await.unwrap(); + assert_eq!(branch.current_branch().as_deref(), Some("exp")); + assert_eq!(branch.version().await.unwrap(), exp_v2); + assert_eq!(branch.count_rows(None).await.unwrap(), 2); + // the HEADs are unaffected let head = conn .open_table("my_table") @@ -6340,6 +6398,68 @@ mod tests { assert_eq!(pinned.count_rows(None).await.unwrap(), 4); // writable again } + #[test] + fn test_branch_version_checkout_during_timestamp_lookup() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .max_blocking_threads(1) + .build() + .unwrap(); + runtime.block_on(async { + let dir = tempdir().unwrap(); + let db = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = db + .create_table("items", sample_rows(vec![0])) + .execute() + .await + .unwrap(); + let branch = table.create_branch("exp", 1u64).await.unwrap(); + table.add(sample_rows(vec![1])).execute().await.unwrap(); + let cutoff = table + .list_versions() + .await + .unwrap() + .pop() + .unwrap() + .timestamp; + // At the cutoff main was at v2 and exp was at v1. + table.add(sample_rows(vec![4])).execute().await.unwrap(); + branch.add(sample_rows(vec![2])).execute().await.unwrap(); + branch.add(sample_rows(vec![3])).execute().await.unwrap(); + branch + .tags() + .await + .unwrap() + .create("exp-head", 3) + .await + .unwrap(); + + // Hold the filesystem worker so the first poll snapshots main and + // suspends in its version lookup. Keep that future unpolled while + // the tag checkout changes the same handle's branch. + let (entered, ready) = tokio::sync::oneshot::channel(); + let (release, wait) = std::sync::mpsc::channel::<()>(); + let worker = tokio::task::spawn_blocking(move || { + entered.send(()).unwrap(); + let _ = wait.recv(); + }); + ready.await.unwrap(); + let mut checkout = std::pin::pin!(table.checkout_as_of(cutoff)); + assert!(futures::poll!(checkout.as_mut()).is_pending()); + drop(release); + worker.await.unwrap(); + table.checkout_tag("exp-head").await.unwrap(); + checkout.await.unwrap(); + + assert_eq!(table.current_branch().as_deref(), Some("exp")); + assert_eq!(table.version().await.unwrap(), 1); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + }); + } + #[tokio::test] async fn test_branch_version_two_branches() { let tmp_dir = tempdir().unwrap(); diff --git a/rust/lancedb/src/table/dataset.rs b/rust/lancedb/src/table/dataset.rs index 2a1deb44d..457ca6cb0 100644 --- a/rust/lancedb/src/table/dataset.rs +++ b/rust/lancedb/src/table/dataset.rs @@ -6,9 +6,11 @@ use std::{ time::Duration, }; +use chrono::{DateTime, Utc}; use lance::{Dataset, dataset::refs}; use tokio::sync::OnceCell; +use super::version_as_of; use crate::table::merge::lsm::ShardWriterCache; use crate::{Error, error::Result, utils::background_cache::BackgroundCache}; @@ -44,6 +46,14 @@ struct DatasetState { query_snapshot: bool, } +impl DatasetState { + fn pin(&mut self, dataset: Dataset) { + self.pinned_version = Some(dataset.version().version); + self.dataset = Arc::new(dataset); + self.query_snapshot = false; + } +} + #[derive(Debug, Clone)] enum ConsistencyMode { /// Only update table state when explicitly asked. @@ -417,15 +427,25 @@ impl DatasetConsistencyWrapper { .get_or_try_init(|| dataset.branch_identifier()) .await?; let new_dataset = dataset.checkout_version(target_ref).await?; - let version_value = new_dataset.version().version; - - let mut state = self.state.lock()?; - state.dataset = Arc::new(new_dataset); - state.pinned_version = Some(version_value); - state.query_snapshot = false; + self.state.lock()?.pin(new_dataset); Ok(()) } + pub(super) async fn as_of(&self, timestamp: DateTime) -> Result<()> { + loop { + let dataset = self.state.lock()?.dataset.clone(); + let version = version_as_of(dataset.versions().await?, timestamp)?; + let snapshot = dataset.checkout_version(version).await?; + + let mut state = self.state.lock()?; + // A tag may have moved this handle to another branch during the lookup. + if state.dataset.manifest().branch == dataset.manifest().branch { + state.pin(snapshot); + return Ok(()); + } + } + } + pub async fn reload(&self) -> Result<()> { let (dataset, pinned_version) = { let state = self.state.lock()?;