From c9ef03c61e3fca23cf65dd213b93ada68ac6aac5 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Wed, 2 Dec 2026 18:09:00 +0800 Subject: [PATCH] fix: refresh stale schema when listing indexes (#5345) ## Problem An Enterprise table handle can fail to list indexes after another client adds and indexes a column. The list response includes the new column while the first handle still has an older schema cached. ## Fix When the cached schema misses an index column or resolves it only by ignoring case, send one `describe` request with the original branch, version selector, and freshness bounds. For a latest read, use the list response version as a lower bound when available. Resolve every column before requesting legacy index stats. ## Validation The original SDK failed on the old handle with `Field path i not found in schema`. A fresh handle and a historical handle passed the same test. [Baseline CI](https://github.com/lancedb/lancedb/actions/runs/46821564282/job/143256287384) At `4c657f597`, the two-client Enterprise regression passed with a zero read consistency interval. Both mock cases passed and verified the `describe` and legacy stats request counts. [Enterprise CI](https://github.com/lancedb/lancedb/actions/runs/46831924124/job/143291095278) The current revision also covers `w` and `W` coexisting and checks that equivalent quoted paths use the warm cache. [Rust CI](https://github.com/lancedb/lancedb/actions/runs/46842846145) Tracks ENT-4843. --- rust/lancedb/src/remote/table.rs | 196 +++++++++++++++++++--- rust/lancedb/src/table.rs | 63 +++++++ rust/lancedb/src/test_utils/connection.rs | 41 ++++- 3 files changed, 271 insertions(+), 29 deletions(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3a2625e7b..f5dabee58 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1241,14 +1241,20 @@ impl RemoteTable { .await } - async fn schema_read_snapshot(&self, read_snapshot: ReadSnapshot) -> Result { + fn cached_schema_read_snapshot(&self, read_snapshot: ReadSnapshot) -> Option { if read_snapshot.freshness.is_current(&self.freshness) && let Some(schema) = self.schema_cache.try_get() && read_snapshot.freshness.is_current(&self.freshness) { - return Ok(schema); + return Some(schema); } + None + } + async fn describe_schema_read_snapshot( + &self, + read_snapshot: ReadSnapshot, + ) -> Result { let description = self.describe_read_snapshot(read_snapshot).await?; schema_from_description(description.schema) } @@ -2809,17 +2815,16 @@ impl RemoteTable { /// Parse the response from `/index/list/` into `IndexConfig` entries. /// - /// When the server returns `index_type` inline, all enriched fields are - /// used directly and no further requests are made. When `index_type` is - /// absent (legacy servers), a `/index/{name}/stats/` call is made for each + /// When the server returns `index_type` inline, no stats calls are needed. + /// For legacy responses, a `/index/{name}/stats/` call is made for each /// addressable index to retrieve the type. Unsafe legacy names are omitted /// because their type cannot be retrieved without changing the URL route. async fn parse_index_list_response( &self, body: &str, request_id: &str, - schema: &SchemaRef, read_snapshot: ReadSnapshot, + list_read_version: Option, ) -> Result> { use crate::index::IndexType; @@ -2847,7 +2852,7 @@ impl RemoteTable { type_url: Option, } - let response: ListIndicesResponse = + let mut response: ListIndicesResponse = serde_json::from_str(body).map_err(|err| Error::Http { source: format!( "Failed to parse list_indices response: {}, body: {}", @@ -2858,22 +2863,69 @@ impl RemoteTable { status_code: None, })?; - let mut futures = Vec::with_capacity(response.indexes.len()); - for entry in response.indexes { - if entry.index_type.is_none() && encode_index_name(&entry.index_name).is_err() { - // Legacy entries need a stats request to determine their type. - // Skip unaddressable names without failing the entire listing. - continue; - } - let columns = entry - .columns + // Legacy entries need an addressable name to look up their type. + response.indexes.retain(|entry| { + entry.index_type.is_some() || encode_index_name(&entry.index_name).is_ok() + }); + let resolve_columns = |schema: &SchemaRef| { + response + .indexes .iter() - .map(|column| { - resolve_arrow_field_path(schema, column) - .map(|(canonical_column, _)| canonical_column) + .map(|entry| { + entry + .columns + .iter() + .map(|column| { + resolve_arrow_field_path(schema, column) + .map(|(canonical_column, _)| canonical_column) + }) + .collect::>>() }) - .collect::>>()?; + .collect::>>() + }; + let columns_match_wire_paths = |columns: &[Vec]| { + use lance_core::datatypes::parse_field_path; + + response + .indexes + .iter() + .zip(columns) + .all(|(entry, columns)| { + entry.columns.iter().zip(columns).all(|(wire, resolved)| { + wire == resolved + || parse_field_path(wire) + .ok() + .zip(parse_field_path(resolved).ok()) + .is_some_and(|(wire, resolved)| wire == resolved) + }) + }) + }; + let cached = self + .cached_schema_read_snapshot(read_snapshot) + .map(|schema| resolve_columns(&schema).map(|columns| (schema, columns))); + let (schema, columns) = match cached { + Some(Ok((schema, columns))) if columns_match_wire_paths(&columns) => (schema, columns), + Some(Err(error)) if !matches!(error, Error::Schema { .. }) => return Err(error), + _ => { + // A cached schema can miss a new column or resolve it to a different + // column by case. Keep the original selector and use the list response + // version as a lower bound for latest reads. + let mut schema_snapshot = read_snapshot; + if schema_snapshot.version.is_none() { + schema_snapshot.freshness.min_read_version = schema_snapshot + .freshness + .min_read_version + .max(list_read_version); + } + let schema = self.describe_schema_read_snapshot(schema_snapshot).await?; + let columns = resolve_columns(&schema)?; + (schema, columns) + } + }; + + let mut futures = Vec::with_capacity(response.indexes.len()); + for (entry, columns) in response.indexes.into_iter().zip(columns) { let future = async move { if let Some(index_type) = entry.index_type { // Enriched response: all fields available, no stats call needed. @@ -5057,10 +5109,15 @@ impl BaseTable for RemoteTable { .send_with_freshness(request, true, read_snapshot.freshness) .await?; let response = self.check_table_response(&request_id, response).await?; + let list_read_version = response + .headers() + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version > 0); let body = response.text().await.err_to_http(request_id.clone())?; - let schema = self.schema_read_snapshot(read_snapshot).await?; - self.parse_index_list_response(&body, &request_id, &schema, read_snapshot) + self.parse_index_list_response(&body, &request_id, read_snapshot, list_read_version) .await } @@ -10668,6 +10725,99 @@ mod tests { assert_eq!(indices, expected); } + #[rstest] + #[case::legacy(false)] + #[case::enriched(true)] + #[tokio::test] + async fn test_list_indices_with_stale_schema( + #[case] enriched: bool, + #[values("i", "W")] new_column: &'static str, + ) { + let old_schema = Schema::new(vec![Field::new("w", DataType::Int32, false)]); + let initial_description = describe_response(&old_schema); + let new_schema = Schema::new(vec![ + Field::new("w", DataType::Int32, false), + Field::new(new_column, DataType::Int64, true), + ]); + let updated_description = describe_response(&new_schema); + let updated = Arc::new(AtomicBool::new(false)); + let requests = Arc::new(Mutex::new(Vec::new())); + let table = RemoteTable::new_mock_with_consistency_interval( + "my_table".into(), + { + let updated = updated.clone(); + let requests = requests.clone(); + move |request| { + let path = request.url().path(); + requests.lock().unwrap().push(path.to_string()); + assert!(request.headers().contains_key(MIN_TIMESTAMP_HEADER)); + let updated = updated.load(AtomicOrdering::Relaxed); + let mut response = http::Response::builder().status(200); + let body = match path { + "/v1/table/my_table/describe/" => { + assert!(updated, "warm index listing must not describe the table"); + let expected_version = if enriched { "3" } else { "1" }; + assert_eq!( + request.headers()[MIN_READ_VERSION_HEADER], + expected_version + ); + json!({"version": 3, "schema": JsonSchema::try_from(&new_schema).unwrap()}) + } + "/v1/table/my_table/index/list/" => { + let index = |name, column| { + let mut entry = json!({"index_name": name, "columns": [column]}); + if enriched { + entry["index_type"] = json!("BTREE"); + } + entry + }; + let mut indexes = vec![index("w_idx", "`w`")]; + if updated { + indexes.push(index("i_idx", new_column)); + if enriched { + response = response.header(VERSION_HEADER, "3"); + } + } + json!({"indexes": indexes}) + } + "/v1/table/my_table/index/w_idx/stats/" + | "/v1/table/my_table/index/i_idx/stats/" + if !enriched => + { + json!({"index_type": "BTREE", "num_indexed_rows": 1, "num_unindexed_rows": 0}) + } + _ => panic!("unexpected request: {path}"), + }; + response.body(body.to_string()).unwrap() + } + }, + Some(Duration::ZERO), + ); + + table.seed_schema(&initial_description); + assert_eq!(table.list_indices().await.unwrap()[0].columns, ["w"]); + assert_eq!(requests.lock().unwrap().len(), if enriched { 1 } else { 2 }); + + updated.store(true, AtomicOrdering::Relaxed); + requests.lock().unwrap().clear(); + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices.len(), 2); + assert_eq!(indices[0].columns, ["w"]); + assert_eq!(indices[1].columns, [new_column]); + { + let requests = requests.lock().unwrap(); + assert_eq!(requests.len(), if enriched { 2 } else { 4 }); + assert_eq!(requests[1], "/v1/table/my_table/describe/"); + } + + let fresh = table.with_branch(None); + fresh.seed_schema(&updated_description); + requests.lock().unwrap().clear(); + let fresh_indices = fresh.list_indices().await.unwrap(); + assert_eq!(fresh_indices[1].columns, [new_column]); + assert_eq!(requests.lock().unwrap().len(), if enriched { 1 } else { 3 }); + } + #[rstest] #[case::legacy(false)] #[case::enriched(true)] @@ -12388,7 +12538,7 @@ mod tests { seeded.invalidate_schema_cache(); assert_eq!( seeded - .schema_read_snapshot(seeded.snapshot_read_state().await) + .describe_schema_read_snapshot(seeded.snapshot_read_state().await) .await .unwrap(), visible_schema, diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 517d821aa..3b72f4c1d 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -6690,6 +6690,69 @@ mod tests { } } + #[tokio::test] + async fn test_list_indices_after_another_client_adds_indexed_column() { + let tc = new_test_connection().await.unwrap(); + let client = tc.reconnect(Duration::ZERO).await.unwrap(); + let table = client + .create_table( + "test", + arrow_array::record_batch!(("w", Int32, [1])).unwrap(), + ) + .execute() + .await + .unwrap(); + table + .create_index(&["w"], Index::Auto) + .name("w__btree".into()) + .execute() + .await + .unwrap(); + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices.len(), 1); + assert_eq!(indices[0].columns, ["w"]); + + let version = table.version().await.unwrap(); + let other_client = tc.reconnect(Duration::ZERO).await.unwrap(); + let historical = other_client.open_table("test").execute().await.unwrap(); + historical.checkout(version).await.unwrap(); + historical.schema().await.unwrap(); + + let writer = other_client.open_table("test").execute().await.unwrap(); + writer + .add_columns() + .transform(NewColumnTransform::SqlExpressions(vec![( + "i".into(), + "CAST(NULL AS BIGINT)".into(), + )])) + .execute() + .await + .unwrap(); + writer + .create_index(&["i"], Index::Auto) + .name("i__btree".into()) + .execute() + .await + .unwrap(); + + let fresh_client = tc.reconnect(Duration::ZERO).await.unwrap(); + let fresh = fresh_client.open_table("test").execute().await.unwrap(); + let fresh_indices = fresh.list_indices().await.unwrap(); + assert_eq!(fresh_indices.len(), 2); + assert!(fresh_indices.iter().any(|index| index.columns == ["i"])); + assert!(table.index_stats("i__btree").await.unwrap().is_some()); + + let historical_indices = historical.list_indices().await.unwrap(); + assert_eq!(historical_indices.len(), 1); + assert_eq!(historical_indices[0].columns, ["w"]); + assert_eq!(historical.version().await.unwrap(), version); + + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices.len(), 2); + assert!(indices.iter().any(|index| index.columns == ["i"])); + assert!(indices.iter().any(|index| index.columns == ["w"])); + } + fn some_sample_data() -> Box { let batch = RecordBatch::try_new( Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)])), diff --git a/rust/lancedb/src/test_utils/connection.rs b/rust/lancedb/src/test_utils/connection.rs index 0185f20c7..bbb12c5aa 100644 --- a/rust/lancedb/src/test_utils/connection.rs +++ b/rust/lancedb/src/test_utils/connection.rs @@ -6,6 +6,7 @@ use regex::Regex; use std::env; use std::process::Stdio; +use std::time::Duration; use tokio::io::{AsyncBufReadExt, BufReader}; use tokio::process::{Child, ChildStdout, Command}; use tokio::sync::mpsc; @@ -18,10 +19,29 @@ pub struct TestConnection { pub uri: String, pub connection: Connection, pub is_remote: bool, + host_override: Option, _temp_dir: Option, _process: Option, } +impl TestConnection { + pub async fn reconnect(&self, read_consistency_interval: Duration) -> Result { + let connection = match &self.host_override { + Some(host_override) => { + create_new_connection(&self.uri, host_override, Some(read_consistency_interval)) + .await? + } + None => { + connect(&self.uri) + .read_consistency_interval(read_consistency_interval) + .execute() + .await? + } + }; + Ok(connection) + } +} + struct TestProcess { child: Child, } @@ -124,30 +144,38 @@ async fn new_remote_connection(script_path: &str) -> Result { }; let uri = "db://test"; let host_override = format!("http://localhost:{}", port); - let connection = create_new_connection(uri, &host_override).await?; + let connection = create_new_connection(uri, &host_override, None).await?; Ok(TestConnection { uri: uri.to_string(), connection, is_remote: true, + host_override: Some(host_override), _temp_dir: Some(temp_dir), _process: Some(process), }) } #[cfg(feature = "remote")] -async fn create_new_connection(uri: &str, host_override: &str) -> crate::error::Result { - connect(uri) +async fn create_new_connection( + uri: &str, + host_override: &str, + read_consistency_interval: Option, +) -> crate::error::Result { + let mut builder = connect(uri) .region("us-east-1") .api_key("sk_localtest") - .host_override(host_override) - .execute() - .await + .host_override(host_override); + if let Some(interval) = read_consistency_interval { + builder = builder.read_consistency_interval(interval); + } + builder.execute().await } #[cfg(not(feature = "remote"))] async fn create_new_connection( _uri: &str, _host_override: &str, + _read_consistency_interval: Option, ) -> crate::error::Result { panic!("remote feature not supported"); } @@ -160,6 +188,7 @@ async fn new_local_connection() -> Result { uri: uri.to_string(), connection, is_remote: false, + host_override: None, _temp_dir: Some(temp_dir), _process: None, })