fix: validate remote tag checkout branch and version (#4853)

Remote tag checkout discarded the tag's branch and pinned its version on
the handle's own branch without checking that the version existed. This
could read a different snapshot or leave the handle pinned to a
nonexistent version.

Resolve the complete tag reference and reject cross-branch tags with an
error naming both branches. For a tag on the handle's branch, reuse
numeric checkout to validate the version before committing the selector
and freshness state. This also protects Python's
`open_table(version=tag)`, which delegates to tag checkout. To read a
tag on another branch, obtain that branch's handle first with
`checkout_branch` in Rust or `table.branches.checkout(...)` in Python.
The Python checkout docstrings and tag-based versioning guide document
this requirement.

Add 17 regression cases covering cross-branch tags in both directions,
main-branch aliases, same-branch reads, and failed validation on
writable and pinned handles. Twelve cases failed against the original
implementation. Update the existing freshness and schema-cache tests for
the validation request.

Validation:

- `cargo test --locked --profile ci --features remote -p lancedb --lib
remote:: -- --quiet` — 921 tests passed using mocked remote endpoints.
- `cargo fmt --all` — passed.
- `cargo clippy --locked --profile ci --features remote -p lancedb
--tests --examples` — passed.
- Python documentation: Ruff lint and formatting checks passed for the
Python tree, using Ruff 0.15.20 from `python/uv.lock`. Python syntax
checks passed; executable ASTs are unchanged. Repository-wide `ruff
check .` reports 59 pre-existing errors in six unchanged
`docs/web-tests` files; unrelated formatter changes were excluded.

Fixes #4843

<!-- lance-gatekeeper-fix:v1 agent=2253a7bdebba53465089b95bce66cb12
generation=1 -->


<!-- gatefixer-walkthrough:v1
head=35f8db881e36b83b9aab478cb5db72e485c9eca7 -->
## Change walkthrough

```mermaid
flowchart TD
    resolve["Resolve tag reference"] --> branch{"Same branch?"}
    branch -->|No| reject["Return branch error"]
    branch -->|Yes| validate["Describe tag version"]
    validate -->|Error| error["Return version error"]
    validate -->|Success| pin["Pin validated snapshot"]
```

The selector and freshness state commit together under the version lock.

**Read:** [branch
guard](https://github.com/lancedb/lancedb/blob/35f8db881e36b83b9aab478cb5db72e485c9eca7/rust/lancedb/src/remote/table.rs#L4075-L4092)
→ [validation and
commit](https://github.com/lancedb/lancedb/blob/35f8db881e36b83b9aab478cb5db72e485c9eca7/rust/lancedb/src/remote/table.rs#L2865-L2893)
→ [tag and branch
guidance](https://github.com/lancedb/lancedb/blob/35f8db881e36b83b9aab478cb5db72e485c9eca7/docs/web/management/table.mdx#L1745-L1755).

<sub>Snapshot:
[35f8db8](https://github.com/lancedb/lancedb/commit/35f8db881e36b83b9aab478cb5db72e485c9eca7)</sub>
<!-- gatefixer-walkthrough:end -->

---------

Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com>
This commit is contained in:
lancedb-gatefixer[bot]
2026-11-27 15:50:20 +08:00
committed by GitHub
parent e38d8bef56
commit a663417fa9
5 changed files with 281 additions and 28 deletions
+7
View File
@@ -1736,6 +1736,13 @@ page).
The tags API supports the standard CRUD operations (create, list, update, delete),
plus checking out by tag name.
A tag identifies both a branch and a version. On Enterprise tables, a tag must belong
to the handle's current branch; checking out a tag on another branch raises an
error without changing the current selection. Obtain a handle for the tag's
branch first: in Python, use `branch_table = table.branches.checkout("exp")`, then
`branch_table.checkout("baseline")` to read a tag named `baseline` on `exp`.
See [Branches](/tables/branching) for more on branch handles.
In Python, `tags.create()` accepts an optional `version`. If you omit it, the
tag uses the version the table handle currently shows. That includes a handle
checked out to an older version, so pass `version` explicitly when the tag must
+10
View File
@@ -332,6 +332,16 @@ class RemoteTable(Table):
)
def checkout(self, version: Union[int, str]):
"""Check out a version number or tag as a read-only view in place.
A tag must belong to this handle's current branch. To read a tag on
another branch, first obtain that branch's handle with
`table.branches.checkout("branch_name")`, then call `checkout(tag)` on
that handle. A tag on another branch raises an error without changing
the current selection.
Call `checkout_latest()` to return to the latest version of this branch.
"""
result = LOOP.run(self._table.checkout(version))
self._checkout_version = self.version
return result
+12
View File
@@ -4247,6 +4247,12 @@ class Table(ABC):
out state. To return the table to a normal state use
`[Self::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
`table.branches.checkout("branch_name")`, then call `checkout(tag)` on
that handle. A tag on another branch raises an error without changing
the current selection.
Parameters
----------
version: int | str,
@@ -10036,6 +10042,12 @@ class AsyncTable:
out state. To return the table to a normal state use
`[Self::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
`await table.branches.checkout("branch_name")`, then call
`await branch_table.checkout(tag)` on that handle. A tag on another
branch raises an error without changing the current selection.
Parameters
----------
version: int | str,
+248 -28
View File
@@ -1269,7 +1269,7 @@ impl<S: HttpSend> RemoteTable<S> {
}
/// Resolve a tag to its `(branch, version)` coordinate via the `tags/version`
/// endpoint, since the `/branches/create` contract accepts no `from_tag`.
/// endpoint.
async fn resolve_tag_ref(&self, tag: &str) -> Result<(Option<String>, u64)> {
let request = self
.client
@@ -4286,22 +4286,19 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
// Resolve the tag without attaching freshness headers; a stale
// `min_version` from a previous write should not ride along on an
// explicit time-travel request.
let request = self
.client
.post(&format!("/v1/table/{}/tags/version/", self.identifier));
let version = self
.resolve_tag_version_with_request(tag, request, false)
.await?;
let (branch, version) = self.resolve_tag_ref(tag).await?;
if branch != self.branch {
return Err(Error::InvalidInput {
message: format!(
"Tag '{tag}' belongs to branch '{}', but this table handle is scoped to branch '{}'. Check out the tag's branch first.",
branch.as_deref().unwrap_or("main"),
self.branch.as_deref().unwrap_or("main"),
),
});
}
let mut write_guard = self.version.write().await;
// Commit the selector and its freshness mode while holding the selector
// write lock, with no cancellation point between the two updates.
self.reset_freshness(None, true);
*write_guard = Some(version);
self.invalidate_schema_cache();
drop(write_guard);
Ok(())
// Validate the version before pinning the handle.
self.checkout(version).await
}
/// Only `OptimizeAction::Compact` with supported `options` and no custom
/// `remap_options` is supported remotely: it submits a durable
@@ -16191,12 +16188,13 @@ mod tests {
.checkout_tag("v2")
.await
.expect("checkout_tag should succeed");
assert_eq!(call_count.load(Ordering::SeqCst), 2);
// Schema call after checkout_tag should re-fetch (cache was invalidated)
let schema3 = table.schema().await.unwrap();
assert_eq!(
call_count.load(Ordering::SeqCst),
2,
3,
"Cache should have been invalidated and re-fetched"
);
assert_ne!(
@@ -18130,12 +18128,13 @@ mod tests {
}
#[tokio::test]
async fn test_freshness_checkout_tag_resolve_sends_no_min_version() {
// Same invariant for checkout_tag: the tag-resolve request must not
// pick up a stale min_version from a prior write.
async fn test_freshness_checkout_tag_validation_sends_no_min_version() {
// Neither the tag lookup nor the version validation should pick up a
// stale min_version from a prior write.
let (handler, captured) = path_capturing_handler(|path| match path {
"/v1/table/my_table/update/" => r#"{"rows_updated":1,"version":7}"#.to_string(),
"/v1/table/my_table/tags/version/" => r#"{"version":5}"#.to_string(),
"/v1/table/my_table/describe/" => r#"{"version":5,"schema":{"fields":[]}}"#.to_string(),
_ => panic!("unexpected path: {}", path),
});
let table = Table::new_with_handler("my_table", handler);
@@ -18144,14 +18143,20 @@ mod tests {
table.checkout_tag("v_initial").await.unwrap();
let captured = captured.lock().unwrap();
let resolve_headers = captured
.get("/v1/table/my_table/tags/version/")
.expect("tags/version should have been called by checkout_tag");
assert!(
!resolve_headers.contains_key("x-lancedb-min-version"),
"checkout_tag resolve must not carry stale min_version",
);
assert!(!resolve_headers.contains_key("x-lancedb-min-timestamp"));
for path in [
"/v1/table/my_table/tags/version/",
"/v1/table/my_table/describe/",
] {
let headers = captured
.get(path)
.expect("checkout_tag should call endpoint");
assert!(
!headers.contains_key("x-lancedb-min-version"),
"{path} must not carry stale min_version",
);
assert!(!headers.contains_key("x-lancedb-min-timestamp"));
assert!(!headers.contains_key("x-lancedb-min-read-version"));
}
}
#[tokio::test]
@@ -19017,6 +19022,221 @@ mod tests {
}
}
#[rstest]
#[case(None, Some("exp"))]
#[case(Some("exp"), None)]
#[case(Some("exp"), Some("main"))]
#[case(Some("exp"), Some("other"))]
#[tokio::test]
async fn test_checkout_tag_rejects_other_branch(
#[case] handle_branch: Option<&'static str>,
#[case] tag_branch: Option<&'static str>,
#[values(None, Some(1))] initial_version: Option<u64>,
) {
let table = RemoteTable::new_mock(
"my_table".to_string(),
move |request| {
let body = request_body_json(&request);
let response = match request.url().path() {
"/v1/table/my_table/tags/version/" => {
assert_eq!(body, json!({"tag": "cross_branch"}));
json!({"branch": tag_branch, "version": 2}).to_string()
}
"/v1/table/my_table/describe/" => {
assert_eq!(body["branch"].as_str(), handle_branch);
assert_eq!(body["version"].as_u64(), initial_version);
json!({"version": initial_version.unwrap_or(7), "schema": {"fields": []}})
.to_string()
}
"/v1/table/my_table/count_rows/" => {
assert_eq!(body["branch"].as_str(), handle_branch);
assert_eq!(body["version"].as_u64(), initial_version);
"3".to_string()
}
path => panic!("unexpected request: {path}"),
};
http::Response::builder()
.status(200)
.body(response)
.unwrap()
},
None,
)
.with_branch(handle_branch.map(String::from));
if let Some(version) = initial_version {
table.checkout(version).await.unwrap();
} else {
table.checkout_latest().await.unwrap();
}
let schema = table.schema().await.unwrap();
let before = table.snapshot_read_state().await;
let error = table.checkout_tag("cross_branch").await.unwrap_err();
assert!(matches!(error, Error::InvalidInput { .. }), "{error:?}");
let message = error.to_string();
assert!(message.contains("cross_branch"), "{message}");
assert!(message.contains(tag_branch.unwrap_or("main")), "{message}");
assert!(
message.contains(handle_branch.unwrap_or("main")),
"{message}"
);
let after = table.snapshot_read_state().await;
assert_eq!(after.version, before.version);
assert_eq!(
after.freshness_state.generation,
before.freshness_state.generation
);
assert_eq!(after.freshness_state.pinned, before.freshness_state.pinned);
assert_eq!(
after.freshness_state.min_version,
before.freshness_state.min_version
);
assert_eq!(
after.freshness_state.min_read_version,
before.freshness_state.min_read_version
);
assert_eq!(
after.freshness_state.checkout_baseline,
before.freshness_state.checkout_baseline
);
assert_eq!(table.current_branch().as_deref(), handle_branch);
assert!(Arc::ptr_eq(&schema, &table.schema().await.unwrap()));
assert_eq!(table.count_rows(None).await.unwrap(), 3);
}
#[rstest]
#[case(None, None)]
#[case(None, Some("main"))]
#[case(None, Some(""))]
#[case(None, Some(" main "))]
#[case(Some("exp"), Some("exp"))]
#[tokio::test]
async fn test_checkout_tag_on_same_branch(
#[case] handle_branch: Option<&'static str>,
#[case] tag_branch: Option<&'static str>,
) {
let table = RemoteTable::new_mock(
"my_table".to_string(),
move |request| {
let body = request_body_json(&request);
let response = match request.url().path() {
"/v1/table/my_table/tags/version/" => {
assert_eq!(body, json!({"tag": "snapshot"}));
json!({"branch": tag_branch, "version": 2}).to_string()
}
"/v1/table/my_table/describe/" => {
assert_eq!(body["branch"].as_str(), handle_branch);
assert_eq!(body["version"], 2);
for header in [
MIN_VERSION_HEADER,
MIN_READ_VERSION_HEADER,
MIN_TIMESTAMP_HEADER,
] {
assert!(!request.headers().contains_key(header));
}
r#"{"version":2,"schema":{"fields":[]}}"#.to_string()
}
"/v1/table/my_table/count_rows/" => {
assert_eq!(body["branch"].as_str(), handle_branch);
if body["version"].is_null() {
"4".to_string()
} else {
assert_eq!(body["version"], 2);
"3".to_string()
}
}
path => panic!("unexpected request: {path}"),
};
http::Response::builder()
.status(200)
.body(response)
.unwrap()
},
None,
)
.with_branch(handle_branch.map(String::from));
table.checkout_latest().await.unwrap();
table.checkout_tag("snapshot").await.unwrap();
assert_eq!(table.count_rows(None).await.unwrap(), 3);
assert_eq!(table.current_branch().as_deref(), handle_branch);
table.checkout_latest().await.unwrap();
assert_eq!(table.count_rows(None).await.unwrap(), 4);
assert_eq!(table.current_branch().as_deref(), handle_branch);
}
#[rstest]
#[case(None)]
#[case(Some("exp"))]
#[tokio::test]
async fn test_checkout_tag_missing_version_leaves_handle_unchanged(
#[case] branch: Option<&'static str>,
#[values(None, Some(1))] initial_version: Option<u64>,
) {
let table = RemoteTable::new_mock(
"my_table".to_string(),
move |request| {
let body = request_body_json(&request);
if request.url().path() == "/v1/table/my_table/tags/version/" {
return http::Response::builder()
.status(200)
.body(json!({"branch": branch, "version": 99}).to_string())
.unwrap();
}
assert_eq!(body["branch"].as_str(), branch);
if body["version"] == 99 {
assert_eq!(request.url().path(), "/v1/table/my_table/describe/");
return http::Response::builder()
.status(404)
.body("not found".to_string())
.unwrap();
}
assert_eq!(body["version"].as_u64(), initial_version);
let response = match request.url().path() {
"/v1/table/my_table/describe/" => {
json!({"version": initial_version.unwrap_or(7), "schema": {"fields": []}})
.to_string()
}
"/v1/table/my_table/count_rows/" => "3".to_string(),
path => panic!("unexpected request: {path}"),
};
http::Response::builder()
.status(200)
.body(response)
.unwrap()
},
None,
)
.with_branch(branch.map(String::from));
if let Some(version) = initial_version {
table.checkout(version).await.unwrap();
} else {
table.checkout_latest().await.unwrap();
}
let schema = table.schema().await.unwrap();
let before = table.snapshot_read_state().await;
let error = table.checkout_tag("missing_version").await.unwrap_err();
assert!(matches!(error, Error::TableNotFound { .. }), "{error:?}");
assert!(error.to_string().contains("version: 99"));
let after = table.snapshot_read_state().await;
assert_eq!(after.version, before.version);
assert_eq!(
after.freshness_state.generation,
before.freshness_state.generation
);
assert_eq!(
after.freshness_state.checkout_baseline,
before.freshness_state.checkout_baseline
);
// HTTP errors invalidate the schema cache, but the refreshed schema
// must still come from the original selector.
assert_eq!(schema, table.schema().await.unwrap());
assert_eq!(table.current_branch().as_deref(), branch);
assert_eq!(table.count_rows(None).await.unwrap(), 3);
}
#[tokio::test]
async fn test_checkout_branch_validates_via_list() {
let table = Table::new_with_handler("my_table", |request| {
+4
View File
@@ -3075,6 +3075,10 @@ impl Table {
/// Checks out a specific version of the Table by tag
///
/// On Enterprise tables, the tag must belong to this handle's branch. Use
/// [`Self::checkout_branch`] to obtain a handle for another branch first.
/// A failed Enterprise tag checkout leaves the handle unchanged.
///
/// Any read operation on the table will now access the data at the version referenced by the tag.
/// As a consequence, calling this method will disable any read consistency interval
/// that was previously set.