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:
@@ -3153,13 +3153,6 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
}
|
||||
|
||||
async fn list_versions(&self) -> Result<Vec<Version>> {
|
||||
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<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
#[derive(Deserialize)]
|
||||
struct ListVersionsResponse {
|
||||
versions: Vec<VersionEntry>,
|
||||
page_token: Option<String>,
|
||||
}
|
||||
|
||||
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<String> = 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<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
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<SchemaRef> {
|
||||
@@ -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]
|
||||
|
||||
@@ -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<Vec<FtsToke
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn version_as_of(versions: Vec<Version>, timestamp: DateTime<Utc>) -> Result<u64> {
|
||||
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<Utc>) -> 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<Utc>) -> lancedb::Result<()> {
|
||||
/// table.checkout_as_of(cutoff).await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn checkout_as_of(&self, timestamp: DateTime<Utc>) -> 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<Utc>) -> 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();
|
||||
|
||||
@@ -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<Utc>) -> 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()?;
|
||||
|
||||
Reference in New Issue
Block a user