From d9db83de65a94bcac2563d180f51754571b1ed1e Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:51:19 +0800 Subject: [PATCH] fix!: guard remote index routes against dot segments (#5013) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BREAKING CHANGE: Older Enterprise index listings that require per-index statistics now omit historical entries with empty names, `.` or `..`. Remote index operations reject these unaddressable names. Operators needing to remove such entries can use server-side maintenance; direct native access also supports cleanup. Ordinary index names and `exist_ok=True` reuse require no migration. Fixes #5007 Remote index URLs previously allowed `.` and `..` as path segments. Reqwest normalizes them, so dropping an index named `..` could send the table-level drop request and delete the table. Guard the remote statistics, prewarm, and drop routes against empty names, `.` and `..`, then percent-encode all other names. Index creation retains its existing name policy on both backends, including names such as `Customer lookup` and `café_idx` and reuse through `exist_ok=True`. The same remote guard applies on checked-out branches. Enriched Enterprise listings retain these entries without issuing stats requests. Native cleanup is covered by a regression test. API documentation explains these limits, and website release guidance remains a non-rendering draft. Validation: - Before the review fix, 12 of 15 focused regressions failed, reproducing valid-name rejection, generated-name reuse failure, and mixed legacy-list failure. - 60 focused Rust tests passed, covering unsafe routes, encoded names, mixed legacy/enriched listings, generated names, native and Enterprise lifecycles, checked-out branches, and `exist_ok` preservation of index identity, definition, and table version. - Rebuilt the Python extension in the uv-managed environment from `python/uv.lock`; all 28 targeted Python tests passed, including both names and synchronous/asynchronous `exist_ok` reuse. - Node native build, TypeScript type checking, lint/format checks, four targeted index tests, and generated API documentation passed. - Rust formatting, Clippy (`remote`, tests and examples), Python formatting/lint, repository-wide Typos 1.26.0, and `git diff --check` passed. Native builds used the repository `ci` profile with `remote,lancedb/metrics-otel` enabled for Python and Node. - Repository-root Ruff lint reports 59 existing errors in unchanged `docs/web-tests`; Python-package lint passes. ## Change walkthrough ```mermaid flowchart TD entry["Listed index"] --> typed{"Type available?"} typed -->|Yes| include["Include index"] typed -->|No| safe{"Addressable name?"} safe -->|No| omit["Omit entry"] safe -->|Yes| stats["Encode and fetch stats"] stats --> include ``` Creation preserves existing name support; remote routes reject only empty names, `.` and `..`. **Read:** [Route guard](https://github.com/lancedb/lancedb/blob/6b25e10810ea1d11a4ef56be63c4ef50225f65d6/rust/lancedb/src/remote/table.rs#L102-L112) → [Listing fallback](https://github.com/lancedb/lancedb/blob/6b25e10810ea1d11a4ef56be63c4ef50225f65d6/rust/lancedb/src/remote/table.rs#L2534-L2596) → [Index-preservation regression](https://github.com/lancedb/lancedb/blob/6b25e10810ea1d11a4ef56be63c4ef50225f65d6/rust/lancedb/src/table/create_index.rs#L1431-L1481). Snapshot: [6b25e10](https://github.com/lancedb/lancedb/commit/6b25e10810ea1d11a4ef56be63c4ef50225f65d6) --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- docs/src/js/classes/Table.md | 8 +- docs/src/js/interfaces/IndexOptions.md | 4 + docs/web/indexing/vector-index.mdx | 12 + nodejs/lancedb/indices.ts | 4 + nodejs/lancedb/table.ts | 8 +- python/python/lancedb/table.py | 18 ++ python/python/tests/test_index.py | 24 ++ rust/lancedb/src/remote/table.rs | 356 +++++++++++++++++++++---- rust/lancedb/src/table.rs | 14 +- rust/lancedb/src/table/create_index.rs | 83 ++++++ 10 files changed, 472 insertions(+), 59 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 01258aa4a..282b9d659 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -425,8 +425,9 @@ Indices on vector columns will speed up vector searches. Indices on scalar columns will speed up filtering (in both vector and non-vector searches) -We currently don't support custom named indexes. -The index name will always be `${column}_idx`. +The index name defaults to `${column}_idx`. Set [IndexOptions.name](../interfaces/IndexOptions.md#name) +to use a custom name. +See [IndexOptions.name](../interfaces/IndexOptions.md#name) for legacy-name cleanup guidance. On LanceDB Embedded tables the index is built before the returned promise resolves. On LanceDB Enterprise tables it resolves once the build is @@ -1185,6 +1186,9 @@ abstract listIndices(): Promise List all indices that have been created with [Table.createIndex](Table.md#createindex) +On older Enterprise servers, this method omits indices named `.`, `..` or +the empty string because their statistics cannot be requested safely. + On LanceDB Enterprise tables, an index whose build hasn't finished may be missing (vector indices) or listed with 0 indexed rows (scalar and FTS indices), and `numUnindexedRows` may be undefined. Use diff --git a/docs/src/js/interfaces/IndexOptions.md b/docs/src/js/interfaces/IndexOptions.md index e0990fc8d..f119a178a 100644 --- a/docs/src/js/interfaces/IndexOptions.md +++ b/docs/src/js/interfaces/IndexOptions.md @@ -35,6 +35,10 @@ optional name: string; Optional custom name for the index. If not provided, a default name will be generated based on the column name. +Existing and generated names remain addressable through index operations, +except that remote tables reject empty names, `.` and `..` to prevent URL +path normalization. Existing `.` or `..` indices on managed tables require +server-side cleanup, or a native connection with direct dataset access. *** diff --git a/docs/web/indexing/vector-index.mdx b/docs/web/indexing/vector-index.mdx index 2800463af..5023b1e27 100644 --- a/docs/web/indexing/vector-index.mdx +++ b/docs/web/indexing/vector-index.mdx @@ -341,6 +341,18 @@ These fields are populated for LanceDB Embedded tables. In LanceDB Enterprise, ` The `{column}_idx` suffix is the default naming convention. Pass `name=...` to `create_index()` to override it. Once set, the custom name will be reflected in `list_indices()`, `index_stats(name)`, and `wait_for_index([name])`. +{/* +Draft for the Enterprise index-route safety fix (#5007). Publish this guidance +after the SDK changes ship. + +Remote tables reject empty names, `.` and `..` in index operations to prevent +URL path normalization. Existing indexes named `.` or `..` require +server-side cleanup on managed tables, or a native connection with direct +access to the dataset. Other existing names remain usable. On older Enterprise +servers, index listings omit these unaddressable entries so they do not prevent +listing or waiting for other indices. +*/} + {VectorIndexCustomName} diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts index 4d91ffc8f..b4bdf1a9e 100644 --- a/nodejs/lancedb/indices.ts +++ b/nodejs/lancedb/indices.ts @@ -1112,6 +1112,10 @@ export interface IndexOptions { * Optional custom name for the index. * * If not provided, a default name will be generated based on the column name. + * Existing and generated names remain addressable through index operations, + * except that remote tables reject empty names, `.` and `..` to prevent URL + * path normalization. Existing `.` or `..` indices on managed tables require + * server-side cleanup, or a native connection with direct dataset access. */ name?: string; diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 1dad81719..5dc1c445e 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -597,8 +597,9 @@ export abstract class Table { * Indices on scalar columns will speed up filtering (in both * vector and non-vector searches) * - * We currently don't support custom named indexes. - * The index name will always be `${column}_idx`. + * The index name defaults to `${column}_idx`. Set {@link IndexOptions.name} + * to use a custom name. + * See {@link IndexOptions.name} for legacy-name cleanup guidance. * * On LanceDB Embedded tables the index is built before the returned promise * resolves. On LanceDB Enterprise tables it resolves once the build is @@ -1666,6 +1667,9 @@ export abstract class Table { /** * List all indices that have been created with {@link Table.createIndex} * + * On older Enterprise servers, this method omits indices named `.`, `..` or + * the empty string because their statistics cannot be requested safely. + * * On LanceDB Enterprise tables, an index whose build hasn't finished may be * missing (vector indices) or listed with 0 indexed rows (scalar and FTS * indices), and `numUnindexedRows` may be undefined. Use diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index b930b77d6..3d950ce7b 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2315,6 +2315,11 @@ class Table(ABC): Use [list_indices][lancedb.table.Table.list_indices] to find the names of the indices. + + Remote tables reject empty names, ``.`` and ``..`` to prevent URL path + normalization. Existing indices named ``.`` or ``..`` require server-side + cleanup on managed tables, or a native connection with direct access to + the dataset. Other existing and generated names remain addressable. """ raise NotImplementedError("drop_index is not supported for this table type") @@ -3471,6 +3476,10 @@ class Table(ABC): List all indices that have been created with [Table.create_index][lancedb.table.Table.create_index] + On older Enterprise servers, this method omits indices named ``.``, + ``..`` or the empty string because their statistics cannot be requested + safely. + On LanceDB Enterprise tables, an index whose build hasn't finished may be missing (vector indices) or listed with 0 indexed rows (scalar and FTS indices), and ``num_unindexed_rows`` may be ``None``. Use @@ -8249,6 +8258,11 @@ class AsyncTable: Use [list_indices][lancedb.table.AsyncTable.list_indices] to find the names of the indices. + + Remote tables reject empty names, ``.`` and ``..`` to prevent URL path + normalization. Existing indices named ``.`` or ``..`` require server-side + cleanup on managed tables, or a native connection with direct access to + the dataset. Other existing and generated names remain addressable. """ await self._inner.drop_index(name) @@ -10596,6 +10610,10 @@ class AsyncTable: """ List all indices that have been created with Self::create_index + On older Enterprise servers, this method omits indices named ``.``, + ``..`` or the empty string because their statistics cannot be requested + safely. + On LanceDB Enterprise tables, an index whose build hasn't finished may be missing (vector indices) or listed with 0 indexed rows (scalar and FTS indices), and ``num_unindexed_rows`` may be ``None``. Use diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index c38948eb2..c3bd5c62a 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -1176,3 +1176,27 @@ async def test_named_index_exist_ok_checks_before_column_validation( await result.wait() assert await some_table.version() == version assert [index.name for index in await some_table.list_indices()] == ["kept"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("name", ["Customer lookup", "café_idx"]) +@pytest.mark.parametrize("background", [False, True]) +async def test_custom_index_names_preserve_exist_ok(some_table, name, background): + method = some_table.create_index_async if background else some_table.create_index + job = await method("id", config=BTree(), name=name, exist_ok=True) + if background: + await job.wait() + version = await some_table.version() + original = await some_table.list_indices() + # A second call keeps the existing definition and version. + job = await method("id", config=Bitmap(), name=name, exist_ok=True) + if background: + await job.wait() + assert await some_table.version() == version + indices = await some_table.list_indices() + assert len(indices) == 1 + assert indices[0].name == name + assert indices[0].index_type == original[0].index_type == "BTree" + assert (await some_table.index_stats(name)).num_indexed_rows == NROWS + await some_table.drop_index(name) + assert await some_table.list_indices() == [] diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 2d576887e..6198dcfdc 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -87,6 +87,7 @@ use lance_core::datatypes::Schema as LanceSchema; use lance_datafusion::exec::{OneShotExec, execute_plan}; use reqwest::{RequestBuilder, Response}; use serde::{Deserialize, Serialize}; +use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use std::io::Cursor; use std::pin::Pin; @@ -102,6 +103,18 @@ const MIN_READ_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-m const VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-version"); const QUERY_SNAPSHOT_HEADER: &str = "x-lancedb-query-snapshot"; +/// Encode an index name as one safe path segment. +fn encode_index_name(name: &str) -> Result> { + // Percent-encoding preserves dot segments, which URL parsing would normalize + // into another route. All other name characters are safe after encoding. + if matches!(name, "" | "." | "..") { + return Err(Error::InvalidInput { + message: format!("Illegal index name '{name}' in remote route."), + }); + } + Ok(urlencoding::encode(name)) +} + fn valid_query_snapshot_identity(value: &str) -> bool { value.strip_prefix("v1:").is_some_and(|digest| { digest.len() == 64 @@ -2704,7 +2717,8 @@ impl RemoteTable { index_name: &str, read_snapshot: ReadSnapshot, ) -> Result> { - let encoded_name = urlencoding::encode(index_name); + // This also guards the stats requests made while listing indices on legacy servers. + let encoded_name = encode_index_name(index_name)?; let mut body = serde_json::json!({ "version": read_snapshot.version }); self.apply_branch_body(&mut body); let request = self @@ -2736,7 +2750,8 @@ impl RemoteTable { /// 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 - /// index to retrieve the type. + /// 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, @@ -2783,6 +2798,11 @@ impl RemoteTable { 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 .iter() @@ -4981,7 +5001,7 @@ impl BaseTable for RemoteTable { } async fn drop_index(&self, index_name: &str) -> Result<()> { - let encoded_name = urlencoding::encode(index_name); + let encoded_name = encode_index_name(index_name)?; let request = self.apply_branch_query(self.client.post(&format!( "/v1/table/{}/index/{encoded_name}/drop/", self.identifier @@ -4997,7 +5017,7 @@ impl BaseTable for RemoteTable { } async fn prewarm_index(&self, index_name: &str) -> Result<()> { - let encoded_name = urlencoding::encode(index_name); + let encoded_name = encode_index_name(index_name)?; let request = self.apply_branch_query(self.client.post(&format!( "/v1/table/{}/index/{encoded_name}/prewarm/", self.identifier @@ -9579,7 +9599,7 @@ mod tests { } #[tokio::test] - async fn test_create_index_forwards_replace_false_on_existing_route() { + async fn test_create_index_forwards_name_and_replace_false_on_existing_route() { let table = Table::new_with_handler("my_table", move |request| { assert_eq!(request.method(), "POST"); match request.url().path() { @@ -9594,6 +9614,7 @@ mod tests { let body = request.body().unwrap().as_bytes().unwrap(); let body: serde_json::Value = serde_json::from_slice(body).unwrap(); assert_eq!(body["replace"], json!(false)); + assert_eq!(body["name"], json!("a_idx-1..v2")); http::Response::builder() .status(200) @@ -9607,6 +9628,7 @@ mod tests { table .create_index(&["a"], Index::BTree(Default::default())) .replace(false) + .name("a_idx-1..v2".to_string()) .execute() .await .unwrap(); @@ -14576,36 +14598,45 @@ mod tests { assert!(error.to_string().contains("SQL")); } + #[rstest] + #[case("my_index", "my_index")] + #[case("café_idx", "caf%C3%A9_idx")] // spellchecker:disable-line + #[case("my/index", "my%2Findex")] #[tokio::test] - async fn test_prewarm_index_sends_the_checked_out_branch() { + async fn test_prewarm_index_sends_the_checked_out_branch( + #[case] index_name: &str, + #[case] encoded_name: &str, + ) { use lance::dataset::refs::Ref; - let table = - Table::new_with_handler_version("my_table", semver::Version::new(0, 5, 0), |request| { - match request.url().path() { - "/v1/table/my_table/branches/create/" => { - http::Response::builder().status(200).body("{}").unwrap() - } - "/v1/table/my_table/index/my_index/prewarm/" => { - let branch = request - .url() - .query_pairs() - .find(|(key, _)| key == "branch") - .map(|(_, value)| value.into_owned()); - assert_eq!(branch.as_deref(), Some("feature/dev")); - http::Response::builder() - .status(202) - .body(r#"{"job_id":"prewarm-job"}"#) - .unwrap() - } - path => panic!("unexpected request path: {path}"), + let expected_path = format!("/v1/table/my_table/index/{encoded_name}/prewarm/"); + let table = Table::new_with_handler_version( + "my_table", + semver::Version::new(0, 5, 0), + move |request| match request.url().path() { + "/v1/table/my_table/branches/create/" => { + http::Response::builder().status(200).body("{}").unwrap() } - }); + path if path == expected_path => { + let branch = request + .url() + .query_pairs() + .find(|(key, _)| key == "branch") + .map(|(_, value)| value.into_owned()); + assert_eq!(branch.as_deref(), Some("feature/dev")); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"prewarm-job"}"#) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + }, + ); let branch = table .create_branch("feature/dev", Ref::Version(None, None)) .await .unwrap(); - branch.prewarm_index("my_index").await.unwrap(); + branch.prewarm_index(index_name).await.unwrap(); } #[tokio::test] @@ -14637,39 +14668,258 @@ mod tests { assert!(matches!(e, Error::IndexNotFound { .. })); } - /// Index names are unvalidated, so reserved characters must be - /// percent-encoded or they restructure the request path. #[tokio::test] - async fn test_per_index_paths_encode_reserved_characters() { - const NAME: &str = "my/index?a#b c"; - const PREFIX: &str = "/v1/table/my_table/index/my%2Findex%3Fa%23b%20c"; + async fn test_generated_index_name_remains_addressable() { + let conn = crate::connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("café", Int32, [1])).unwrap(); + let schema = batch.schema(); + let native = conn + .create_table("my_table", batch) + .execute() + .await + .unwrap(); + native + .create_index(&["café"], Index::Auto) + .execute() + .await + .unwrap(); + let generated_name = native.list_indices().await.unwrap()[0].name.clone(); + assert_eq!(generated_name, "café_idx"); + let version = native.version().await.unwrap(); + native + .create_index(&["café"], Index::Auto) + .name(generated_name.clone()) + .exist_ok(true) + .execute() + .await + .unwrap(); + assert_eq!(native.version().await.unwrap(), version); - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.url().path(), format!("{PREFIX}/stats/")); - let body = serde_json::json!({ - "num_indexed_rows": 1, - "num_unindexed_rows": 0, - "index_type": "IVF_PQ", - "distance_type": "l2" + for enriched in [true, false] { + let schema = schema.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let body = match request.url().path() { + "/v1/table/my_table/describe/" => describe_response(&schema), + "/v1/table/my_table/create_index/" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert!(body.get("name").is_none()); + "{}".to_string() + } + "/v1/table/my_table/index/list/" => { + let mut entry = json!({"index_name": "café_idx", "columns": ["café"]}); + if enriched { + entry["index_type"] = json!("BTREE"); + } + json!({"indexes": [entry]}).to_string() + } + "/v1/table/my_table/index/caf%C3%A9_idx/stats/" => json!({ + "num_indexed_rows": 1, + "num_unindexed_rows": 0, + "index_type": "BTREE" + }) + .to_string(), + "/v1/table/my_table/index/caf%C3%A9_idx/drop/" + | "/v1/table/my_table/index/caf%C3%A9_idx/prewarm/" => "{}".to_string(), + path => panic!("Unexpected request: {path}"), + }; + http::Response::builder().status(200).body(body).unwrap() }); + table + .create_index(&["café"], Index::Auto) + .execute() + .await + .unwrap(); + assert_eq!(table.list_indices().await.unwrap()[0].name, generated_name); + assert!(table.index_stats(&generated_name).await.unwrap().is_some()); + table.prewarm_index(&generated_name).await.unwrap(); + table + .wait_for_index(&[&generated_name], Duration::from_secs(1)) + .await + .unwrap(); + table.drop_index(&generated_name).await.unwrap(); + } + } + + #[tokio::test] + async fn test_unsafe_index_paths_never_send_requests() { + let table = Table::new_with_handler("my_table", |request| -> http::Response { + panic!("Unsafe index name sent a request to {}", request.url()); + }); + + for name in ["..", ".", ""] { + for result in [ + table.drop_index(name).await, + table.prewarm_index(name).await, + table.index_stats(name).await.map(|_| ()), + ] { + assert!( + matches!(result, Err(Error::InvalidInput { .. })), + "Expected invalid input for {name:?}, got {result:?}" + ); + } + } + } + + #[rstest] + #[case("..", false)] + #[case(".", false)] + #[case("", false)] + #[case("..", true)] + #[case(".", true)] + #[case("", true)] + #[tokio::test] + async fn test_list_indices_with_legacy_index_name( + #[case] legacy_name: &'static str, + #[case] enriched: bool, + ) { + let table = Table::new_with_handler("my_table", move |request| { + let body = match request.url().path() { + "/v1/table/my_table/describe/" => { + let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); + describe_response(&schema) + } + "/v1/table/my_table/index/list/" => { + let mut entries = vec![ + json!({"index_name": legacy_name, "columns": ["a"]}), + json!({"index_name": "Customer lookup", "columns": ["a"]}), + json!({"index_name": "café_idx", "columns": ["a"]}), + ]; + if enriched { + for entry in &mut entries { + entry["index_type"] = json!("BTREE"); + } + } + json!({"indexes": entries}).to_string() + } + "/v1/table/my_table/index/Customer%20lookup/stats/" + | "/v1/table/my_table/index/caf%C3%A9_idx/stats/" => json!({ + "num_indexed_rows": 1, + "num_unindexed_rows": 0, + "index_type": "BTREE" + }) + .to_string(), + path => panic!("Legacy index name caused an unexpected request to {path}"), + }; + http::Response::builder().status(200).body(body).unwrap() + }); + let indices = table.list_indices().await.unwrap(); + let expected = if enriched { + vec![legacy_name, "Customer lookup", "café_idx"] + } else { + vec!["Customer lookup", "café_idx"] + }; + assert_eq!( + indices + .iter() + .map(|index| index.name.as_str()) + .collect::>(), + expected + ); + table + .wait_for_index(&["Customer lookup", "café_idx"], Duration::from_secs(1)) + .await + .unwrap(); + } + + #[rstest] + #[case("Customer lookup", "Customer%20lookup", false)] + #[case("Customer lookup", "Customer%20lookup", true)] + #[case("café_idx", "caf%C3%A9_idx", false)] // spellchecker:disable-line + #[case("café_idx", "caf%C3%A9_idx", true)] // spellchecker:disable-line + #[tokio::test] + async fn test_custom_index_names_remote_lifecycle( + #[case] name: &'static str, + #[case] encoded_name: &str, + #[case] background: bool, + ) { + let prefix = format!("/v1/table/my_table/index/{encoded_name}"); + let table = Table::new_with_handler("my_table", move |request| { + let body = match request.url().path() { + "/v1/table/my_table/describe/" => { + describe_response(&Schema::new(vec![Field::new("a", DataType::Int32, false)])) + } + "/v1/table/my_table/create_index/" => { + let body = request_body_json(&request); + assert_eq!(body["name"], name); + assert_eq!(body["replace"], false); + assert_eq!(request.url().query(), Some("exist_ok=true")); + "{}".to_string() + } + "/v1/table/my_table/index/list/" => json!({"indexes": [{ + "index_name": name, "columns": ["a"], "index_type": "BTREE" + }]}) + .to_string(), + path if path == format!("{prefix}/stats/") => json!({ + "num_indexed_rows": 1, "num_unindexed_rows": 0, "index_type": "BTREE" + }) + .to_string(), + path if path == format!("{prefix}/drop/") + || path == format!("{prefix}/prewarm/") => + { + "{}".to_string() + } + path => panic!("Unexpected index route: {path}"), + }; + http::Response::builder().status(200).body(body).unwrap() + }); + for _ in 0..2 { + let builder = table + .create_index(&["a"], Index::Auto) + .name(name.to_string()) + .exist_ok(true); + if background { + builder.execute_async().await.unwrap().wait().await.unwrap(); + } else { + builder.execute().await.unwrap(); + } + } + assert_eq!(table.list_indices().await.unwrap()[0].name, name); + assert!(table.index_stats(name).await.unwrap().is_some()); + table.prewarm_index(name).await.unwrap(); + table + .wait_for_index(&[name], Duration::from_secs(1)) + .await + .unwrap(); + table.drop_index(name).await.unwrap(); + } + + #[rstest] + #[case("my_index-1..v2", "my_index-1..v2")] + #[case("café_idx", "caf%C3%A9_idx")] // spellchecker:disable-line + #[case("my/index", "my%2Findex")] + #[case("my\\index", "my%5Cindex")] + #[case("%2e%2e", "%252e%252e")] + #[case("my/index?a#b c", "my%2Findex%3Fa%23b%20c")] + #[tokio::test] + async fn test_per_index_paths_preserve_existing_names( + #[case] name: &str, + #[case] encoded_name: &str, + ) { + let prefix = format!("/v1/table/my_table/index/{encoded_name}"); + let table = Table::new_with_handler("my_table", move |request| { + let path = request.url().path(); + let suffix = path + .strip_prefix(&prefix) + .unwrap_or_else(|| panic!("Unexpected index route: {path}")); + let body = match suffix { + "/stats/" => json!({ + "num_indexed_rows": 1, + "num_unindexed_rows": 0, + "index_type": "BTREE" + }), + "/drop/" | "/prewarm/" => json!({}), + _ => panic!("Unexpected index route: {path}"), + }; http::Response::builder() .status(200) - .body(serde_json::to_string(&body).unwrap()) + .body(body.to_string()) .unwrap() }); - assert!(table.index_stats(NAME).await.unwrap().is_some()); - - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.url().path(), format!("{PREFIX}/drop/")); - http::Response::builder().status(200).body("{}").unwrap() - }); - table.drop_index(NAME).await.unwrap(); - - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.url().path(), format!("{PREFIX}/prewarm/")); - http::Response::builder().status(200).body("{}").unwrap() - }); - table.prewarm_index(NAME).await.unwrap(); + assert!(table.index_stats(name).await.unwrap().is_some()); + table.prewarm_index(name).await.unwrap(); + table.drop_index(name).await.unwrap(); } #[tokio::test] diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 3889b1cf6..517d821aa 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -3170,7 +3170,11 @@ impl Table { self.inner.list_versions().await } - /// List all indices that have been created with [`Self::create_index`] + /// List all indices that have been created with [`Self::create_index`]. + /// + /// On older remote servers, indices named `.`, `..` or the empty string are + /// omitted because their statistics cannot be requested safely. Enriched + /// listings include these entries without requesting their statistics. pub async fn list_indices(&self) -> Result> { self.inner.list_indices().await } @@ -3341,6 +3345,7 @@ impl Table { /// Get statistics about an index. /// Returns None if the index does not exist. + /// Remote tables reject empty names, `.` and `..` to prevent URL normalization. pub async fn index_stats( &self, index_name: impl AsRef, @@ -3350,7 +3355,11 @@ impl Table { /// Drop an index from the table. /// - /// Note: This is not yet available in LanceDB Enterprise. + /// Remote tables reject empty names, `.` and `..` to prevent URL normalization. + /// Legacy indices named `.` or `..` can still be dropped through a native + /// connection with direct access to the dataset. On managed remote tables, + /// these indices require server-side cleanup. Other existing and generated + /// names remain addressable. /// /// This does not delete the index from disk, it just removes it from the table. /// To delete the index, run [`Self::optimize()`] after dropping the index. @@ -3374,6 +3383,7 @@ impl Table { /// indices will silently ignore the request. /// /// Use [`Self::list_indices()`] to find the names of the indices. + /// Remote tables reject empty names, `.` and `..` to prevent URL normalization. pub async fn prewarm_index(&self, name: &str) -> Result<()> { self.inner.prewarm_index(name).await } diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index 28e19d292..ef59e165b 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -1444,6 +1444,89 @@ mod tests { assert_eq!(stats.distance_type, Some(crate::DistanceType::L2)); } + #[rstest::rstest] + #[case("Customer lookup", false)] + #[case("Customer lookup", true)] + #[case("café_idx", false)] + #[case("café_idx", true)] + #[tokio::test] + async fn test_custom_index_names_preserve_exist_ok( + #[case] name: &str, + #[case] background: bool, + ) { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("i", Int32, [1])).unwrap(); + let table = conn + .create_table("my_table", batch) + .execute() + .await + .unwrap(); + + let builder = table + .create_index(&["i"], Index::Auto) + .name(name.to_string()) + .exist_ok(true); + if background { + builder.execute_async().await.unwrap().wait().await.unwrap(); + } else { + builder.execute().await.unwrap(); + } + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices.len(), 1); + assert_eq!(indices[0].name, name); + let version = table.version().await.unwrap(); + let identity = indices[0].index_uuid.clone(); + // A second call with a different definition must preserve the index. + let builder = table + .create_index(&["i"], Index::Bitmap(Default::default())) + .name(name.to_string()) + .exist_ok(true); + if background { + builder.execute_async().await.unwrap().wait().await.unwrap(); + } else { + builder.execute().await.unwrap(); + } + assert_eq!(table.version().await.unwrap(), version); + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices[0].index_uuid, identity); + assert_eq!(indices[0].index_type, crate::index::IndexType::BTree); + assert!(table.index_stats(name).await.unwrap().is_some()); + table.drop_index(name).await.unwrap(); + assert!(table.list_indices().await.unwrap().is_empty()); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + } + + #[tokio::test] + async fn test_drop_index_with_legacy_index_names() { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("i", Int32, [1])).unwrap(); + let table = conn + .create_table("my_table", batch) + .execute() + .await + .unwrap(); + let native = table.as_native().unwrap(); + let params = lance_index::scalar::ScalarIndexParams::for_builtin( + lance_index::scalar::BuiltinIndexType::BTree, + ); + + for name in [".", "..", "old/index", "old\\index"] { + // Simulate an index written before LanceDB validated custom names. + let mut dataset = (*native.dataset.get().await.unwrap()).clone(); + dataset + .create_index_builder(&["i"], lance_index::IndexType::Scalar, ¶ms) + .name(name.to_string()) + .await + .unwrap(); + native.dataset.update(dataset); + + assert_eq!(table.list_indices().await.unwrap()[0].name, name); + table.drop_index(name).await.unwrap(); + assert!(table.list_indices().await.unwrap().is_empty()); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + } + } + #[tokio::test] async fn test_create_btree_on_binary() { let conn = connect("memory://").execute().await.unwrap();