diff --git a/docs/web/search/vector-search.mdx b/docs/web/search/vector-search.mdx index bdad76889..205228343 100644 --- a/docs/web/search/vector-search.mdx +++ b/docs/web/search/vector-search.mdx @@ -323,6 +323,28 @@ Prefer choosing either effort or a fixed count. If both are set, explicit `search_effort` overrides `nprobes`. Explicit min/max bounds still apply; setting them equal fixes the count. +#### Set partition-search concurrency {#partition-search-concurrency} + +In Rust, use `VectorQuery::query_parallelism` to control how many selected IVF +partitions can be searched concurrently within each Embedded IVF index segment. +Separate segments may be searched at the same time: + +```rust +let results = table.query().nearest_to(query_vector)? + .query_parallelism(4)?.limit(10).execute().await?; +``` + +The default is unset, preserving Lance's automatic policy. `0` explicitly selects +Auto, `1` searches partitions sequentially, `-1` uses the available CPU pool, and +larger positive values cap concurrency at that count and the execution CPU budget. +Values below `-1` are invalid. Pass `None` to reset the setting. + +This setting changes concurrency, not the probe budget. It does not control +brute-force scans without an IVF index. Benchmark latency and throughput together: +giving one query more CPU can reduce capacity for concurrent queries. Enterprise, shared batch IVF search, and RTE vector search return +`NotSupported` for any explicit value, including `0`. Leave the option unset +to use their default scheduling. + #### Check result quality {#measure-auto-probe-recall} Auto was tuned toward roughly **95% average recall** in benchmark tests. That diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index f151e7c9c..222ec363b 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -1329,6 +1329,9 @@ pub struct VectorQueryRequest { /// None preserves Auto and fixed `nprobes`; any explicit value overrides /// `nprobes` while retaining explicit minimum and maximum bounds. pub search_effort: Option, + /// IVF partition-search concurrency. None preserves Lance's default. + /// See [`VectorQuery::query_parallelism`] for supported values. + pub query_parallelism: Option, /// The lower bound (inclusive) of the distance to search for. pub lower_bound: Option, /// The upper bound (exclusive) of the distance to search for. @@ -1356,6 +1359,7 @@ impl Default for VectorQueryRequest { minimum_nprobes: None, maximum_nprobes: None, search_effort: None, + query_parallelism: None, lower_bound: None, upper_bound: None, ef: None, @@ -1394,6 +1398,17 @@ impl VectorQueryRequest { Ok(()) } + pub(crate) fn validate_query_parallelism(&self) -> Result<()> { + if let Some(parallelism) = self.query_parallelism + && parallelism < -1 + { + return Err(Error::InvalidInput { + message: format!("query_parallelism must be >= -1, got {parallelism}"), + }); + } + Ok(()) + } + pub(crate) fn validate_search_effort(&self) -> Result<()> { if let Some(effort) = self.search_effort && (!effort.is_finite() || !(0.0..=1.0).contains(&effort)) @@ -1664,6 +1679,35 @@ impl VectorQuery { self } + /// Set partition-search concurrency within each Embedded IVF index segment. + /// + /// `None` preserves Lance's default. `0` selects its automatic policy, which + /// may choose sequential execution depending on the index. `-1` uses the CPU + /// pool size; `1` selects sequential partition search; values greater than + /// `1` enable partition-parallel search, capped by the execution CPU budget. + /// Values below `-1` are rejected. + /// + /// This controls how selected IVF partitions are searched, not how many are + /// probed. It does not set the thread count for a brute-force scan without an + /// index. More concurrency may reduce latency but increase resource use. + /// Separate index segments can run concurrently. Enterprise, the shared batch IVF + /// plan, and RTE vector search return `NotSupported` for any explicit value. + /// + /// ```no_run + /// # use lancedb::{Table, Result}; + /// # use lancedb::query::{QueryBase, ExecutableQuery}; + /// # async fn search(table: &Table, vector: &[f32]) -> Result<()> { + /// let results = table.query().nearest_to(vector)? + /// .query_parallelism(4)?.limit(10).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn query_parallelism(mut self, parallelism: impl Into>) -> Result { + self.request.query_parallelism = parallelism.into(); + self.request.validate_query_parallelism()?; + Ok(self) + } + /// A multiplier to control how many additional rows are taken during the refine step /// /// This argument is only used when the vector column has an IVF PQ index. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 7e42239b2..2f930ad7d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1663,12 +1663,23 @@ impl RemoteTable { Ok(()) } + fn validate_vector_query_options(query: &VectorQueryRequest) -> Result<()> { + query.validate_search_effort()?; + query.validate_query_parallelism()?; + if query.query_parallelism.is_some() { + return Err(Error::NotSupported { + message: "Enterprise vector search does not support query_parallelism".into(), + }); + } + Ok(()) + } + fn apply_vector_query_params( &self, mut body: serde_json::Value, query: &VectorQueryRequest, ) -> Result> { - query.validate_search_effort()?; + Self::validate_vector_query_options(query)?; self.apply_query_params(&mut body, &query.base)?; // Apply general parameters, before we dispatch based on number of query vectors. @@ -1923,6 +1934,8 @@ impl RemoteTable { && query.base.reranker.is_some() && query.base.full_text_search.is_none() { + // Reject unsupported options before fetching the vector column schema. + Self::validate_vector_query_options(query)?; // Older servers execute one independent search per vector. query.validate_rerank_batch(!self.server_version.support_multivector())?; let schema = self.schema().await?; @@ -8532,6 +8545,112 @@ mod tests { if message.contains("search_effort must be finite and in [0, 1]"))); } + #[rstest] + #[case(-1)] + #[case(0)] + #[case(1)] + #[case(4)] + #[tokio::test] + async fn test_explicit_query_parallelism_is_unsupported_on_enterprise( + #[case] parallelism: i32, + ) { + let table = + Table::new_with_handler::<&str>("my_table", |_| panic!("unsupported query sent")); + let error = table + .query() + .nearest_to(vec![0.1, 0.2]) + .unwrap() + .query_parallelism(parallelism) + .unwrap() + .execute() + .await + .err() + .unwrap(); + assert!( + matches!(error, Error::NotSupported { message } if message.contains("query_parallelism")) + ); + } + + #[tokio::test] + async fn test_query_parallelism_with_reranking_is_rejected_before_enterprise_schema_lookup() { + let table = Table::new_with_handler_version::<&str>( + "my_table", + semver::Version::new(0, 2, 0), + |request| { + panic!( + "unsupported query sent a request to {}", + request.url().path() + ) + }, + ); + let query = table + .query() + .nearest_to(vec![0.1, 0.2]) + .unwrap() + .add_query_vector(vec![0.3, 0.4]) + .unwrap() + .query_parallelism(1) + .unwrap() + .rerank(Arc::new(crate::rerankers::rrf::RRFReranker::default())); + let error = query.execute().await.err().unwrap(); + assert!( + matches!(error, Error::NotSupported { message } if message.contains("query_parallelism")) + ); + } + + #[tokio::test] + async fn test_unset_query_parallelism_on_enterprise() { + let table = Table::new_with_handler("my_table", |request| { + assert!( + request_body_json(&request) + .get("query_parallelism") + .is_none() + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from(vec![1]))], + ) + .unwrap(); + http::Response::builder() + .status(200) + .header(CONTENT_TYPE, ARROW_FILE_CONTENT_TYPE) + .body(write_ipc_file(&batch)) + .unwrap() + }); + let batches: Vec<_> = table + .query() + .nearest_to(vec![0.1, 0.2]) + .unwrap() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(batches[0].num_rows(), 1); + } + + #[tokio::test] + async fn test_query_parallelism_invalid_request_never_reaches_remote() { + let table = Table::new_with_handler::<&str>("my_table", |_| panic!("invalid request sent")); + let mut request = table + .query() + .nearest_to(vec![0.1, 0.2]) + .unwrap() + .into_request(); + request.query_parallelism = Some(-2); + let error = table + .base_table() + .create_plan(&AnyQuery::VectorQuery(request), Default::default()) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("query_parallelism must be >= -1") + ); + } + #[tokio::test] async fn test_query_vector_all_params() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index af9b998d0..4c7b39def 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -24,6 +24,7 @@ use arrow::array::{AsArray, FixedSizeListBuilder, Float32Builder}; use arrow::datatypes::{Float32Type, UInt8Type}; use arrow_array::Array; use arrow_schema::{DataType, Schema}; +use datafusion_common::tree_node::TreeNode; use datafusion_common::{Column, DataFusionError, ScalarValue, SchemaError}; use datafusion_expr::Operator; use datafusion_physical_expr::expressions::{BinaryExpr, Column as PhysicalColumn, Literal}; @@ -122,10 +123,10 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R fn requires_local_namespace_execution(query: &AnyQuery) -> bool { // The namespace QueryTable request cannot represent approx_mode, search_effort, - // use_rte, order_by or scan_in_order. For use_rte that is worse than a tuning miss: - // RTE read routing lives only in `create_plan`, so a pushed-down query would return - // stale base-only data. A dropped order_by would return the wrong top-K rows, and a - // dropped ordered scan would silently stop guaranteeing manifest order. + // query_parallelism, use_rte, order_by or scan_in_order. RTE read routing lives + // only in `create_plan`, so a pushed-down query would return stale base-only data. + // Dropping order_by changes the top-K rows, and dropping scan_in_order loses + // the guarantee of manifest order. if subquery_filter::predicate(query.base().filter.as_ref()).is_some() || query.base().use_rte.is_some() || query.base().has_take() @@ -162,6 +163,7 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool { AnyQuery::VectorQuery(vector_query) if vector_query.approx_mode.is_some() || vector_query.search_effort.is_some() + || vector_query.query_parallelism.is_some() ) } @@ -278,6 +280,7 @@ pub async fn create_plan( }; query.base.check_filter()?; query.validate_search_effort()?; + query.validate_query_parallelism()?; let ds_ref = match &query.base.prepared_subquery { Some(prepared) => prepared.dataset.clone(), @@ -448,6 +451,9 @@ pub async fn create_plan( if let Some(ef) = query.ef { scanner.ef(ef); } + if let Some(parallelism) = query.query_parallelism { + scanner.query_parallelism(parallelism); + } scanner.distance_range(query.lower_bound, query.upper_bound); scanner.use_index(query.use_index); @@ -567,6 +573,11 @@ async fn create_scanner_plan( .create_plan() .await .map_err(|error| enrich_lance_field_not_found(error, schema))?; + if query.query_parallelism.is_some() && plan.exists(|node| Ok(node.is::()))? { + return Err(Error::NotSupported { + message: "query_parallelism is unsupported by the batch IVF search plan".into(), + }); + } let normalized_l2_indices = normalized_l2_ann_indices(plan.as_ref()).await?; if !normalized_l2_indices.is_empty() { // Rebuild only the affected ANN nodes with internal normalized squared-L2 @@ -1090,6 +1101,11 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { }; // Check for unsupported features + if vq.query_parallelism.is_some() { + return Err(Error::NotSupported { + message: "namespace QueryTable does not support query_parallelism; execute the query locally".to_string(), + }); + } if vq.search_effort.is_some() { return Err(Error::NotSupported { message: "namespace QueryTable does not support search_effort; execute the query locally".to_string(), @@ -1470,6 +1486,16 @@ mod tests { )); } + for parallelism in [-1, 0, 1, 4] { + let query = AnyQuery::VectorQuery(VectorQueryRequest { + query_vector: vec![Arc::new(Float32Array::from(vec![1.0, 2.0]))], + query_parallelism: Some(parallelism), + ..Default::default() + }); + assert!(requires_local_namespace_execution(&query)); + assert!(matches!(convert_to_namespace_query(&query), + Err(Error::NotSupported { message }) if message.contains("query_parallelism"))); + } let nprobes_query = AnyQuery::VectorQuery(VectorQueryRequest { query_vector: vec![Arc::new(Float32Array::from(vec![1.0, 2.0]))], nprobes: Some(20), diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index eddb4d0c0..5bc2fbf9a 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -194,6 +194,9 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> { // brute-force search the index-only base arm can't do. (ef / approx_mode are // recall/speed knobs and are left to no-op.) if !query.query_vector.is_empty() { + if query.query_parallelism.is_some() { + return unsupported("query_parallelism on vector search"); + } if query.search_effort.is_some() { return unsupported("search_effort on vector search"); } @@ -855,6 +858,19 @@ mod tests { ); } + #[test] + fn query_parallelism_is_not_silently_ignored() { + let query = VectorQueryRequest { + query_vector: vec![Arc::new(arrow_array::Float32Array::from(vec![1.0, 0.0]))], + query_parallelism: Some(4), + ..Default::default() + }; + assert!( + matches!(reject_unsupported(&query), Err(Error::NotSupported { message }) + if message.contains("query_parallelism")) + ); + } + #[test] fn resident_fts_check_distinguishes_columns() { use arrow_schema::Field; diff --git a/rust/lancedb/tests/query_parallelism.rs b/rust/lancedb/tests/query_parallelism.rs new file mode 100644 index 000000000..ead969f92 --- /dev/null +++ b/rust/lancedb/tests/query_parallelism.rs @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::sync::Arc; + +use arrow_array::{ + Array, FixedSizeListArray, Float32Array, Int32Array, RecordBatch, types::Float32Type, +}; +use datafusion_common::tree_node::TreeNode; +use datafusion_physical_plan::ExecutionPlan; +use futures::TryStreamExt; +use lance::io::exec::{ANNIvfBatchExec, ANNIvfSubIndexExec}; +use lancedb::index::{Index, vector::IvfFlatIndexBuilder}; +use lancedb::query::{ExecutableQuery, QueryBase, QueryExecutionOptions}; +use lancedb::table::{AnyQuery, query::create_plan}; + +fn ann_parallelism(plan: &dyn ExecutionPlan) -> Option { + if let Some(ann) = plan.downcast_ref::() { + return Some(ann.query().query_parallelism); + } + if let Some(ann) = plan.downcast_ref::() { + return Some(ann.query().query_parallelism); + } + plan.children() + .into_iter() + .find_map(|child| ann_parallelism(child.as_ref())) +} + +#[tokio::test] +async fn query_parallelism_reaches_lance_and_preserves_results() -> lancedb::Result<()> { + let conn = lancedb::connect("memory://parallelism").execute().await?; + let vectors = FixedSizeListArray::from_iter_primitive::( + (0..256).map(|i| Some(vec![Some(i as f32), Some((i % 7) as f32)])), + 2, + ); + let batch = RecordBatch::try_from_iter(vec![ + ( + "id", + Arc::new(Int32Array::from_iter_values(0..256)) as Arc, + ), + ("vector", Arc::new(vectors) as Arc), + ])?; + let table = conn.create_table("vectors", vec![batch]).execute().await?; + table + .create_index( + &["vector"], + Index::IvfFlat(IvfFlatIndexBuilder::default().num_partitions(4)), + ) + .execute() + .await?; + let query = table + .query() + .nearest_to(&[3.25f32, 1.5])? + .nprobes(4)? + .limit(8); + assert_eq!(query.current_request().query_parallelism, None); + let mut baseline = None; + for parallelism in [None, Some(0), Some(1), Some(2), Some(-1)] { + let query = query.clone().query_parallelism(parallelism)?; + let plan = query.create_plan(QueryExecutionOptions::default()).await?; + assert_eq!( + ann_parallelism(plan.as_ref()), + Some(parallelism.unwrap_or(0)) + ); + let batches: Vec = query.execute().await?.try_collect().await?; + let rows: Vec<(i32, f32)> = batches + .iter() + .flat_map(|batch| { + let ids = batch + .column_by_name("id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let distances = batch + .column_by_name("_distance") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + ids.values() + .iter() + .copied() + .zip(distances.values().iter().copied()) + }) + .collect(); + assert_eq!(rows.len(), 8); + if let Some(expected) = &baseline { + assert_eq!(&rows, expected); + } else { + baseline = Some(rows); + } + } + assert_eq!( + query + .clone() + .query_parallelism(4)? + .query_parallelism(None)? + .current_request() + .query_parallelism, + None + ); + let batch_query = query.clone().add_query_vector(&[9.0f32, 2.0])?; + let plan = batch_query + .create_plan(QueryExecutionOptions::default()) + .await?; + assert!(plan.exists(|node| Ok(node.is::()))?); + let batches: Vec<_> = batch_query.execute().await?.try_collect().await?; + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 16); + for setting in [0, 1, -1, 4] { + let error = batch_query + .clone() + .query_parallelism(setting)? + .create_plan(QueryExecutionOptions::default()) + .await + .unwrap_err(); + assert!( + matches!(error, lancedb::Error::NotSupported { message } if message.contains("batch IVF")) + ); + } + assert!(query.clone().query_parallelism(-2).is_err()); + // Public request fields must be validated too, even if the builder is bypassed. + let mut request = query.into_request(); + request.query_parallelism = Some(-2); + let error = create_plan( + table.as_native().unwrap(), + &AnyQuery::VectorQuery(request), + QueryExecutionOptions::default(), + ) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("query_parallelism must be >= -1") + ); + Ok(()) +}