diff --git a/bindings/c/src/tests.rs b/bindings/c/src/tests.rs index 5d4d1b68e..1e4419031 100644 --- a/bindings/c/src/tests.rs +++ b/bindings/c/src/tests.rs @@ -41,12 +41,12 @@ use std::sync::{Arc, Mutex}; use arrow::buffer::NullBuffer; use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; -use arrow_array::{Array, Int32Array, RecordBatch, StringArray, StructArray}; +use arrow_array::{Array, ArrayRef, Int32Array, Int64Array, RecordBatch, StringArray, StructArray}; use arrow_schema::{DataType as ArrowDataType, Field as ArrowField, Schema as ArrowSchema}; use paimon::catalog::Identifier; use paimon::io::FileIOBuilder; use paimon::spec::{ - BlobDescriptor, CommitKind, DataType, IntType, Schema, TableSchema, VarCharType, + ArrayType, BlobDescriptor, CommitKind, DataType, IntType, Schema, TableSchema, VarCharType, }; use paimon::table::{SnapshotManager, Table}; use paimon::{Catalog, FileSystemCatalog, Options}; @@ -3338,13 +3338,13 @@ fn test_two_commits_same_builder() { // `__paimon_search_score` Float32 column; row order is best-first. use arrow_array::builder::{FixedSizeListBuilder, Float32Builder, ListBuilder}; -use arrow_array::{ArrayRef, Float32Array}; +use arrow_array::Float32Array; use bytes::Bytes; use futures::TryStreamExt; use paimon::io::FileIO; use paimon::spec::{ - ArrayType, DataFileMeta, Datum, FloatType, GlobalIndexMeta, IndexFileMeta, Predicate, - PredicateBuilder, VectorType, + DataFileMeta, Datum, FloatType, GlobalIndexMeta, IndexFileMeta, Predicate, PredicateBuilder, + VectorType, }; use paimon::table::{CommitMessage, TableCommit}; @@ -4291,6 +4291,157 @@ fn vector_search_append_table_read_matches_rust() { } } +#[test] +fn vector_search_execute_scored_honors_global_row_range() { + let path = "memory:/vsearch_scored_row_range"; + let table = build_append_vector_table(path); + let query = [1.0f32, 0.0]; + let handle = unsafe { wrap_table(table) }; + + unsafe { + let builder = c_vector_builder(handle, "embedding", &query, 6, ptr::null_mut()); + let metric = CString::new("inner_product").unwrap(); + let error = paimon_vector_search_builder_with_distance_metric(builder, metric.as_ptr()); + assert!(error.is_null()); + let error = paimon_vector_search_builder_with_row_range(builder, 2, 4); + assert!(error.is_null()); + let result = paimon_vector_search_builder_execute_scored(builder); + paimon_vector_search_builder_free(builder); + assert!(result.error.is_null()); + assert!(!result.reader.is_null()); + + let next = paimon_record_batch_reader_next(result.reader); + assert!(next.error.is_null()); + let batch = import_batch(&next.batch); + paimon_arrow_batch_free(next.batch); + let row_ids = batch + .column_by_name("row_id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let scores = batch + .column_by_name("score") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(row_ids.len(), 3); + assert_eq!(scores.len(), 3); + let mut ids = row_ids.values().to_vec(); + ids.sort_unstable(); + assert_eq!(ids, vec![2, 3, 4]); + + let eof = paimon_record_batch_reader_next(result.reader); + assert!(eof.error.is_null()); + assert!(eof.batch.array.is_null()); + paimon_record_batch_reader_free(result.reader); + + let builder = c_vector_builder(handle, "embedding", &query, 3, ptr::null_mut()); + let error = paimon_vector_search_builder_with_row_range(builder, 0, i64::MAX); + assert!(error.is_null()); + let result = paimon_vector_search_builder_execute_scored(builder); + assert!(result.error.is_null()); + let next = paimon_record_batch_reader_next(result.reader); + assert!(next.error.is_null()); + assert_eq!(import_batch(&next.batch).num_rows(), 3); + paimon_arrow_batch_free(next.batch); + paimon_record_batch_reader_free(result.reader); + let error = paimon_vector_search_builder_with_row_range(builder, 5, 4); + assert!(!error.is_null()); + paimon_error_free(error); + paimon_vector_search_builder_free(builder); + + let builder = c_vector_builder(handle, "embedding", &query, 3, ptr::null_mut()); + let wrong_metric = CString::new("l2").unwrap(); + let error = + paimon_vector_search_builder_with_distance_metric(builder, wrong_metric.as_ptr()); + assert!(error.is_null()); + let result = paimon_vector_search_builder_execute_scored(builder); + paimon_vector_search_builder_free(builder); + assert!(!result.error.is_null()); + assert!(result.reader.is_null()); + paimon_error_free(result.error); + unwrap_table(handle); + } +} + +#[test] +fn vector_search_scored_intersects_scalar_filter_and_row_range() { + let table = build_append_vector_table("memory:/vsearch_scored_filter_scope"); + let handle = unsafe { wrap_table(table) }; + unsafe { + for (threshold, expected) in [(3, vec![3, 4]), (99, vec![])] { + let predicate = build_predicate_ge(handle, "id", threshold); + let builder = c_vector_builder(handle, "embedding", &[1.0, 0.0], 6, predicate); + assert!(paimon_vector_search_builder_with_row_range(builder, 2, 4).is_null()); + let result = paimon_vector_search_builder_execute_scored(builder); + paimon_vector_search_builder_free(builder); + assert!(result.error.is_null()); + let mut ids = Vec::new(); + loop { + let next = paimon_record_batch_reader_next(result.reader); + assert!(next.error.is_null()); + if next.batch.array.is_null() { + break; + } + let batch = import_batch(&next.batch); + paimon_arrow_batch_free(next.batch); + ids.extend_from_slice( + batch + .column_by_name("row_id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values(), + ); + } + ids.sort_unstable(); + assert_eq!(ids, expected); + paimon_record_batch_reader_free(result.reader); + } + unwrap_table(handle); + } +} + +#[test] +fn vector_search_execute_scored_forwards_scalar_filter() { + let path = "memory:/vsearch_scored_filter"; + let table = build_append_vector_table(path); + let query = [1.0f32, 0.0]; + let handle = unsafe { wrap_table(table) }; + + unsafe { + let predicate = build_predicate_ge(handle, "id", 3); + let builder = c_vector_builder(handle, "embedding", &query, 6, predicate); + let result = paimon_vector_search_builder_execute_scored(builder); + paimon_vector_search_builder_free(builder); + assert!(result.error.is_null()); + assert!(!result.reader.is_null()); + + let next = paimon_record_batch_reader_next(result.reader); + assert!(next.error.is_null()); + let batch = import_batch(&next.batch); + paimon_arrow_batch_free(next.batch); + let row_ids = batch + .column_by_name("row_id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let mut ids = row_ids.values().to_vec(); + ids.sort_unstable(); + assert_eq!(ids, vec![3, 4, 5]); + + let eof = paimon_record_batch_reader_next(result.reader); + assert!(eof.error.is_null()); + assert!(eof.batch.array.is_null()); + paimon_record_batch_reader_free(result.reader); + unwrap_table(handle); + } +} + #[test] fn vector_search_pk_filter_excludes_neighbor() { let path = "memory:/vsearch_pk_filter_read"; diff --git a/bindings/c/src/types.rs b/bindings/c/src/types.rs index 490dd5a4e..c8fd42cc5 100644 --- a/bindings/c/src/types.rs +++ b/bindings/c/src/types.rs @@ -361,6 +361,8 @@ pub(crate) struct VectorSearchState { pub limit: Option, pub options: std::collections::HashMap, pub filter: Option, + pub row_range: Option<(i64, i64)>, + pub distance_metric: Option, // Optional column projection applied by `execute_read` (plus the always-appended // `__paimon_search_score`). `None` materializes every user column. pub projection: Option>, diff --git a/bindings/c/src/vector_search.rs b/bindings/c/src/vector_search.rs index f79d01d99..ab4ab5361 100644 --- a/bindings/c/src/vector_search.rs +++ b/bindings/c/src/vector_search.rs @@ -29,6 +29,12 @@ use std::collections::HashMap; use std::ffi::{c_char, c_void}; +use std::sync::Arc; + +use arrow_array::{Float32Array, Int64Array, RecordBatch}; +use arrow_schema::{DataType as ArrowDataType, Field as ArrowField, Schema as ArrowSchema}; +use futures::stream; +use paimon::vector_search::ScoredRowIds; use paimon::spec::Predicate; use paimon::table::GlobalIndexResult; @@ -65,6 +71,8 @@ pub unsafe extern "C" fn paimon_table_new_vector_search_builder( limit: None, options: HashMap::new(), filter: None, + row_range: None, + distance_metric: None, projection: None, }; let inner = Box::into_raw(Box::new(state)) as *mut c_void; @@ -148,6 +156,58 @@ pub unsafe extern "C" fn paimon_vector_search_builder_with_limit( std::ptr::null_mut() } +/// Restrict candidates to the inclusive global row-ID interval before Top-K. +/// +/// # Safety +/// A non-null builder must be a live vector-search handle. +#[no_mangle] +pub unsafe extern "C" fn paimon_vector_search_builder_with_row_range( + b: *mut paimon_vector_search_builder, + from: i64, + to: i64, +) -> *mut paimon_error { + if let Err(e) = check_non_null(b, "b") { + return e; + } + if from < 0 || from > to { + return paimon_error::new( + PaimonErrorCode::InvalidInput, + format!("Invalid vector search row range [{from}, {to}]"), + ); + } + let state = &mut *((*b).inner as *mut VectorSearchState); + state.row_range = Some((from, to)); + std::ptr::null_mut() +} + +/// Require the persisted vector metric to match the requested metric. +/// +/// # Safety +/// A non-null builder must be a live vector-search handle. A non-null metric must be a null-terminated UTF-8 string. +#[no_mangle] +pub unsafe extern "C" fn paimon_vector_search_builder_with_distance_metric( + b: *mut paimon_vector_search_builder, + metric: *const c_char, +) -> *mut paimon_error { + if let Err(e) = check_non_null(b, "b") { + return e; + } + let metric = match validate_cstr(metric, "distance metric") { + Ok(metric) => metric, + Err(e) => return e, + }; + let normalized = metric.to_ascii_lowercase().replace('-', "_"); + if !matches!(normalized.as_str(), "l2" | "cosine" | "inner_product") { + return paimon_error::new( + PaimonErrorCode::InvalidInput, + format!("Unknown vector search metric: {metric}"), + ); + } + let state = &mut *((*b).inner as *mut VectorSearchState); + state.distance_metric = Some(normalized); + std::ptr::null_mut() +} + /// Set scan/search options for a vector-search builder. /// /// # Safety @@ -319,6 +379,63 @@ pub unsafe extern "C" fn paimon_vector_search_builder_execute_read( })) } +/// Return an Arrow reader of global Int64 row IDs and Float32 scores. Free the returned reader with paimon_record_batch_reader_free. +/// +/// # Safety +/// A non-null builder must be a live vector-search handle. +#[no_mangle] +pub unsafe extern "C" fn paimon_vector_search_builder_execute_scored( + b: *mut paimon_vector_search_builder, +) -> paimon_result_record_batch_reader { + let state = match vector_search_state(b) { + Ok(state) => state, + Err(error) => { + return paimon_result_record_batch_reader { + reader: std::ptr::null_mut(), + error, + } + } + }; + let builder = configured_builder(state); + wrap_vector_stream( + runtime() + .block_on(async { scored_row_ids_to_stream(builder.execute().await?.into_row_ids()?) }), + ) +} + +fn scored_row_ids_to_stream(result: ScoredRowIds) -> paimon::Result { + let row_ids = result + .row_ids + .into_iter() + .map(|row_id| { + i64::try_from(row_id).map_err(|_| paimon::Error::DataInvalid { + message: format!("Vector search row id {row_id} exceeds i64::MAX"), + source: None, + }) + }) + .collect::>>()?; + let schema = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("row_id", ArrowDataType::Int64, false), + ArrowField::new("score", ArrowDataType::Float32, false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(row_ids)), + Arc::new(Float32Array::from(result.scores)), + ], + ) + .map_err(|e| paimon::Error::UnexpectedError { + message: format!("Failed to build scored vector-search batch: {e}"), + source: Some(Box::new(e)), + })?; + if batch.num_rows() == 0 { + Ok(Box::pin(stream::empty())) + } else { + Ok(Box::pin(stream::iter([Ok(batch)]))) + } +} + pub(crate) async fn materialize_search_result( result: GlobalIndexResult, projection: Option<&[String]>, @@ -371,6 +488,12 @@ fn configured_builder(state: &VectorSearchState) -> VectorSearchBuilder<'_> { if let Some(filter) = &state.filter { builder.with_filter(filter.clone()); } + if let Some((from, to)) = state.row_range { + builder.with_row_range(paimon::table::RowRange::new(from, to)); + } + if let Some(metric) = &state.distance_metric { + builder.with_expected_distance_metric(metric); + } builder } @@ -480,3 +603,13 @@ const _: unsafe extern "C" fn(*const paimon_vector_search_builder) -> paimon_res paimon_vector_search_builder_new_scan; const _: unsafe extern "C" fn(*const paimon_vector_search_builder) -> paimon_result_vector_read = paimon_vector_search_builder_new_read; + +const _: unsafe extern "C" fn(*mut paimon_vector_search_builder, i64, i64) -> *mut paimon_error = + paimon_vector_search_builder_with_row_range; +const _: unsafe extern "C" fn( + *mut paimon_vector_search_builder, + *const c_char, +) -> *mut paimon_error = paimon_vector_search_builder_with_distance_metric; +const _: unsafe extern "C" fn( + *mut paimon_vector_search_builder, +) -> paimon_result_record_batch_reader = paimon_vector_search_builder_execute_scored; diff --git a/crates/paimon/src/table/batch_vector_search_builder.rs b/crates/paimon/src/table/batch_vector_search_builder.rs index ec06e277d..e7832e0c0 100644 --- a/crates/paimon/src/table/batch_vector_search_builder.rs +++ b/crates/paimon/src/table/batch_vector_search_builder.rs @@ -121,6 +121,7 @@ impl<'a> BatchVectorSearchBuilder<'a> { column, self.filter.as_ref(), self.include_row_ids.as_ref(), + None, self.prepared_filter.as_ref(), ) .map(|scan| scan.with_options(&self.options)) @@ -134,6 +135,7 @@ impl<'a> BatchVectorSearchBuilder<'a> { column, self.filter.as_ref(), self.include_row_ids.as_ref(), + None, self.prepared_filter.as_ref(), )?; let queries = self @@ -154,6 +156,7 @@ impl<'a> BatchVectorSearchBuilder<'a> { limit, &self.options, self.filter.as_ref(), + None, context, ) } diff --git a/crates/paimon/src/table/de_vector_read.rs b/crates/paimon/src/table/de_vector_read.rs index 7526f1867..5c38a3543 100644 --- a/crates/paimon/src/table/de_vector_read.rs +++ b/crates/paimon/src/table/de_vector_read.rs @@ -77,6 +77,7 @@ use multi_vector::{ListScorer, ListScoring}; /// Owns the queries and executes the snapshot-scoped plan from `DeVectorScan`. pub(super) struct DeVectorRead { + row_range: Option, vector_searches: Vec, max_sim: bool, } @@ -110,6 +111,7 @@ impl DeVectorRead { Ok(Self { vector_searches, max_sim: false, + row_range: None, }) } @@ -118,6 +120,18 @@ impl DeVectorRead { self } + pub(super) fn with_row_range(mut self, range: Option) -> Self { + self.row_range = range; + self + } + + pub(super) fn with_expected_distance_metric(mut self, metric: Option<&str>) -> Self { + for search in &mut self.vector_searches { + search.expected_distance_metric = metric.map(str::to_string); + } + self + } + /// Validate a result read, including projections over an empty result. pub(super) fn read_type( table: &Table, @@ -288,6 +302,7 @@ impl DeVectorRead { source_splits.as_deref(), &scalar_prefilter_ranges, self.max_sim, + self.row_range.as_ref(), ) .await? }; @@ -961,6 +976,7 @@ async fn evaluate_batch_vector_search( None, &[], false, + None, ) .await } @@ -973,6 +989,7 @@ async fn evaluate_batch_vector_search_with_executor( sources: Option<&[crate::table::SearchScanSplit]>, scalar_prefilter_ranges: &[RowRange], max_sim: bool, + row_range: Option<&RowRange>, ) -> crate::Result> { let timing_enabled = vector_search_timing_enabled(); let total_start = timing_enabled.then(Instant::now); @@ -1033,10 +1050,12 @@ async fn evaluate_batch_vector_search_with_executor( .filter(|e| { e.kind == FileKind::Add && is_vindex_index_type(&e.index_file.index_type) - && e.index_file - .global_index_meta - .as_ref() - .is_some_and(|m| m.index_field_id == field_id) + && e.index_file.global_index_meta.as_ref().is_some_and(|m| { + m.index_field_id == field_id + && row_range.is_none_or(|r| { + r.overlaps_inclusive(m.row_range_start, m.row_range_end) + }) + }) }) .collect(); @@ -1356,6 +1375,28 @@ async fn evaluate_batch_vector_search_with_executor( .map(&restrict_to_live) .or_else(|| live_rows.clone()), }; + // Work in local index coordinates. A range covering the whole shard + // needs no bitmap, even when its upper bound is i64::MAX. + let local = if let Some(range) = row_range + .filter(|r| r.from() > meta.row_range_start || r.to() < meta.row_range_end) + { + let from = + (range.from().max(meta.row_range_start) - meta.row_range_start) as u64; + let to = (range.to().min(meta.row_range_end) - meta.row_range_start) as u64; + let scoped = if let Some(local) = local { + let mut bitmap = (*local).clone(); + bitmap.remove_range(..from); + bitmap.remove_range(to + 1..); + bitmap + } else { + let mut bitmap = RoaringTreemap::new(); + bitmap.insert_range(from..=to); + bitmap + }; + Some(Arc::new(scoped)) + } else { + local + }; if let Some(local) = local { search.set_shared_include_row_ids(local); } @@ -1565,6 +1606,12 @@ async fn evaluate_batch_vector_search_with_executor( } ranges }; + if let Some(range) = row_range { + raw_ranges = raw_ranges + .iter() + .filter_map(|r| r.intersect_inclusive(range.from(), range.to())) + .collect(); + } raw_ranges = merge_row_ranges(raw_ranges); if !scalar_prefilter_ranges.is_empty() && !bitmap_ranges.is_empty() { let covered = intersect_sorted_ranges(scalar_prefilter_ranges, &bitmap_ranges); @@ -2222,6 +2269,14 @@ enum RawVectorMetric { } impl RawVectorMetric { + fn as_str(self) -> &'static str { + match self { + Self::L2 => "l2", + Self::Cosine => "cosine", + Self::InnerProduct => "inner_product", + } + } + fn parse(value: &str) -> crate::Result { Self::parse_normalized(&normalize_metric(value)).ok_or_else(|| crate::Error::DataInvalid { message: format!("Unknown vector search metric: {value}"), @@ -2552,6 +2607,9 @@ async fn read_raw_vector_scores( let result_count = list_scoring.map_or(vector_searches.len(), |mode| { mode.result_count(vector_searches.len()) }); + for search in vector_searches { + search.ensure_distance_metric(metric.as_str())?; + } let timing_enabled = vector_search_timing_enabled(); let total_start = timing_enabled.then(Instant::now); if vector_searches.is_empty() { @@ -3646,6 +3704,8 @@ struct TaskVectorSearch { limit: usize, field: String, options: HashMap, + #[serde(default)] + expected_distance_metric: Option, include: Option, } #[derive(Clone, Serialize, Deserialize)] @@ -3682,6 +3742,7 @@ impl TaskVectorQueries { limit: search.limit, field: search.field_name.clone(), options: search.options.clone(), + expected_distance_metric: search.expected_distance_metric.clone(), include, }) }) @@ -3712,6 +3773,7 @@ impl TaskVectorQueries { query.field.clone(), )? .with_options(query.options.clone()); + search.expected_distance_metric = query.expected_distance_metric.clone(); if let Some(index) = query.include { let shared = filters.get(index).ok_or_else(|| { crate::table::search_task::invalid( diff --git a/crates/paimon/src/table/de_vector_read/tests.rs b/crates/paimon/src/table/de_vector_read/tests.rs index f12dd3793..acaba3c60 100644 --- a/crates/paimon/src/table/de_vector_read/tests.rs +++ b/crates/paimon/src/table/de_vector_read/tests.rs @@ -246,6 +246,7 @@ fn scheduled_vector_transport_restores_one_shared_raw_filter_per_bitmap() { .collect::>(); for search in &mut searches { search.set_shared_include_row_ids(Arc::clone(&shared)); + search.expected_distance_metric = Some("l2".into()); search.options = HashMap::from([ ( "global-index.diskann.index-columns".into(), @@ -264,6 +265,7 @@ fn scheduled_vector_transport_restores_one_shared_raw_filter_per_bitmap() { assert!(restored.iter().all( |search| search.options["global-index.diskann.index-columns"] == "embedding" && search.options["opaque.parameter"] == "unchanged" + && search.expected_distance_metric.as_deref() == Some("l2") )); let restored_shared = shared_batch_include_row_ids(&restored).unwrap(); assert_eq!(restored_shared.as_ref(), shared.as_ref()); @@ -887,6 +889,27 @@ fn test_configured_raw_vector_metric_precedence_and_conflict_default() { ); } +#[tokio::test] +async fn raw_search_rejects_mismatched_expected_metric() { + let table = de_vector_table().await; + let search = VectorSearch::new(vec![1.0, 0.0], 3, "embedding".into()) + .unwrap() + .with_expected_distance_metric("cosine".into()); + let result = read_raw_batch_vector_search_with_executor( + &table, + &[search], + &[RowRange::new(0, 3)], + RawVectorMetric::L2, + None, + None, + ) + .await; + assert!( + matches!(result, Err(crate::Error::DataInvalid { message, .. }) + if message.contains("metric mismatch")) + ); +} + #[tokio::test] async fn raw_search_without_files_uses_the_configured_indexer_default() { let file_io = FileIOBuilder::new("memory").build().unwrap(); diff --git a/crates/paimon/src/table/pk_vector_read.rs b/crates/paimon/src/table/pk_vector_read.rs index 7cc7417f9..0fec57083 100644 --- a/crates/paimon/src/table/pk_vector_read.rs +++ b/crates/paimon/src/table/pk_vector_read.rs @@ -68,9 +68,15 @@ pub(super) struct PkVectorRead { vector_column: String, queries: Vec>, limit: usize, + expected_distance_metric: Option, } impl PkVectorRead { + pub(super) fn with_expected_distance_metric(mut self, metric: Option<&str>) -> Self { + self.expected_distance_metric = metric.map(str::to_string); + self + } + /// Capture query inputs; format-dependent options wait for the scan plan. pub(super) fn new( table: &Table, @@ -87,6 +93,7 @@ impl PkVectorRead { vector_column: vector_column.to_string(), queries: queries.iter().map(|query| query.to_vec()).collect(), limit, + expected_distance_metric: None, } } @@ -139,6 +146,19 @@ impl PkVectorRead { params.metric = metric; params.vector_options.metric = metric.as_str().into(); } + if let Some(expected) = &self.expected_distance_metric { + let expected = VectorSearchMetric::parse(expected)?; + if expected != params.metric { + return Err(crate::Error::DataInvalid { + message: format!( + "Vector search metric mismatch: query expects {}, but index uses {}", + expected.as_str(), + params.metric.as_str() + ), + source: None, + }); + } + } let candidates = search_pk_candidates_batch_with_plan( &self.table, self.filter.as_ref(), diff --git a/crates/paimon/src/table/vector_read.rs b/crates/paimon/src/table/vector_read.rs index 0135e32e4..27a61a3d4 100644 --- a/crates/paimon/src/table/vector_read.rs +++ b/crates/paimon/src/table/vector_read.rs @@ -100,18 +100,24 @@ impl BatchVectorRead { limit: usize, options: &HashMap, filter: Option<&Predicate>, + expected_distance_metric: Option<&str>, context: PlanContext, ) -> crate::Result { let core = CoreOptions::new(table.schema().options()); let reader = if targets_primary_key_column(table, column) { let pk_col = core.single_vector_index_column()?; PkVectorSearchParams::validate_inputs(table, filter, &pk_col, queries, limit)?; - VectorReadKind::PrimaryKey(Box::new(PkVectorRead::new( - table, options, filter, &pk_col, queries, limit, - ))) + VectorReadKind::PrimaryKey(Box::new( + PkVectorRead::new(table, options, filter, &pk_col, queries, limit) + .with_expected_distance_metric(expected_distance_metric), + )) } else { validate_list_queries(table, column, queries, false)?; - VectorReadKind::DataEvolution(DeVectorRead::new(column, queries, limit, options)?) + VectorReadKind::DataEvolution( + DeVectorRead::new(column, queries, limit, options)? + .with_row_range(context.row_range.clone()) + .with_expected_distance_metric(expected_distance_metric), + ) }; Ok(Self { context, @@ -126,10 +132,14 @@ impl BatchVectorRead { queries: &[&[f32]], limit: usize, options: &HashMap, + expected_distance_metric: Option<&str>, context: PlanContext, ) -> crate::Result { validate_list_queries(table, column, queries, true)?; - let reader = DeVectorRead::new(column, queries, limit, options)?.with_max_sim(); + let reader = DeVectorRead::new(column, queries, limit, options)? + .with_row_range(context.row_range.clone()) + .with_max_sim() + .with_expected_distance_metric(expected_distance_metric); Ok(Self { context, table: table.clone(), diff --git a/crates/paimon/src/table/vector_scan.rs b/crates/paimon/src/table/vector_scan.rs index 41fa7c74e..6f9a07c85 100644 --- a/crates/paimon/src/table/vector_scan.rs +++ b/crates/paimon/src/table/vector_scan.rs @@ -209,6 +209,7 @@ pub(super) struct PlanContext { pub(super) column: String, pub(super) filter: Option, pub(super) include_row_ids: Option>, + pub(super) row_range: Option, pub(super) prepared_snapshot: Option>, } @@ -218,6 +219,7 @@ impl PlanContext { column: &str, filter: Option<&Predicate>, include_row_ids: Option<&Arc>, + row_range: Option<&RowRange>, prepared: Option<&PreparedVectorSearchFilter>, ) -> crate::Result { let core = CoreOptions::new(table.schema().options()); @@ -240,8 +242,13 @@ impl PlanContext { message: "Vector column must be set via with_vector_column()".to_string(), }); } + if row_range.is_some_and(|r| r.from() < 0) { + return Err(crate::Error::ConfigInvalid { + message: "Global row IDs must be nonnegative".into(), + }); + } if targets_primary_key_column(table, column) - && (include_row_ids.is_some() || prepared.is_some()) + && (row_range.is_some() || include_row_ids.is_some() || prepared.is_some()) { return Err(crate::Error::DataInvalid { message: "global row-ID filters cannot be applied to primary-key file positions; use with_filter()".to_string(), source: None, @@ -250,6 +257,7 @@ impl PlanContext { Ok(Self { column: column.to_string(), filter: filter.cloned(), + row_range: row_range.cloned(), include_row_ids: prepared .map(PreparedVectorSearchFilter::include_row_ids) .or(include_row_ids) @@ -278,9 +286,11 @@ impl VectorScan { column: &str, filter: Option<&Predicate>, include_row_ids: Option<&Arc>, + row_range: Option<&RowRange>, prepared: Option<&PreparedVectorSearchFilter>, ) -> crate::Result { - let context = PlanContext::new(table, column, filter, include_row_ids, prepared)?; + let context = + PlanContext::new(table, column, filter, include_row_ids, row_range, prepared)?; let core = CoreOptions::new(table.schema().options()); let scan = if targets_primary_key_column(table, column) { let column = core.single_vector_index_column()?; diff --git a/crates/paimon/src/table/vector_search_builder.rs b/crates/paimon/src/table/vector_search_builder.rs index e1b2ada6b..8a5e96091 100644 --- a/crates/paimon/src/table/vector_search_builder.rs +++ b/crates/paimon/src/table/vector_search_builder.rs @@ -21,7 +21,7 @@ use crate::spec::{CoreOptions, Predicate}; use crate::table::vector_read::{BatchVectorRead, VectorRead}; use crate::table::vector_scan::{PlanContext, VectorScan}; use crate::table::vector_search_common::{add_filter, validate_partition_filter}; -use crate::table::Table; +use crate::table::{RowRange, Table}; use crate::vector_search::GlobalIndexResult; use std::borrow::Cow; use std::collections::HashMap; @@ -45,6 +45,9 @@ struct VectorSearchConfig { limit: Option, options: HashMap, filter: Option, + include_row_ids: Option>, + expected_distance_metric: Option, + row_range: Option, } impl<'a> VectorSearchBuilder<'a> { @@ -124,6 +127,23 @@ impl<'a> VectorSearchBuilder<'a> { self } + pub fn with_include_row_ids(&mut self, include_row_ids: roaring::RoaringTreemap) -> &mut Self { + self.config.write().unwrap().include_row_ids = Some(Arc::new(include_row_ids)); + self + } + + /// Restrict candidates to an inclusive interval of global row IDs before Top-K. + /// Replaces an earlier interval and intersects any scalar or bitmap filter. + pub fn with_row_range(&mut self, range: RowRange) -> &mut Self { + self.config.write().unwrap().row_range = Some(range); + self + } + + pub fn with_expected_distance_metric(&mut self, metric: &str) -> &mut Self { + self.config.write().unwrap().expected_distance_metric = Some(metric.to_string()); + self + } + /// Add a partition-only predicate expressed against the table schema. pub fn with_partition_filter(&mut self, filter: Predicate) -> crate::Result<&mut Self> { validate_partition_filter(&self.table, &filter)?; @@ -145,8 +165,15 @@ impl<'a> VectorSearchBuilder<'a> { .ok_or_else(|| crate::Error::ConfigInvalid { message: "Vector column must be set via with_vector_column()".to_string(), })?; - VectorScan::new(&self.table, column, config.filter.as_ref(), None, None) - .map(|scan| scan.with_options(&config.options)) + VectorScan::new( + &self.table, + column, + config.filter.as_ref(), + config.include_row_ids.as_ref(), + config.row_range.as_ref(), + None, + ) + .map(|scan| scan.with_options(&config.options)) } /// Create an owned reader; query errors are reported before planning. @@ -157,7 +184,14 @@ impl<'a> VectorSearchBuilder<'a> { fn read_with_config(&self, config: &VectorSearchConfig) -> crate::Result { let (column, queries, limit) = self.query(config)?; - let context = PlanContext::new(&self.table, column, config.filter.as_ref(), None, None)?; + let context = PlanContext::new( + &self.table, + column, + config.filter.as_ref(), + config.include_row_ids.as_ref(), + config.row_range.as_ref(), + None, + )?; let queries = queries.iter().map(Vec::as_slice).collect::>(); let batch = if config.max_sim { BatchVectorRead::new_max_sim( @@ -166,6 +200,7 @@ impl<'a> VectorSearchBuilder<'a> { &queries, limit, &config.options, + config.expected_distance_metric.as_deref(), context, )? } else { @@ -176,6 +211,7 @@ impl<'a> VectorSearchBuilder<'a> { limit, &config.options, config.filter.as_ref(), + config.expected_distance_metric.as_deref(), context, )? }; diff --git a/crates/paimon/src/vector_search.rs b/crates/paimon/src/vector_search.rs index dc5327857..1d45eb285 100644 --- a/crates/paimon/src/vector_search.rs +++ b/crates/paimon/src/vector_search.rs @@ -27,6 +27,7 @@ pub struct VectorSearch { pub limit: usize, pub field_name: String, pub options: HashMap, + pub expected_distance_metric: Option, pub include_row_ids: Option, pub(crate) shared_include_row_ids: Option>, } @@ -56,6 +57,7 @@ impl VectorSearch { limit, field_name, options: HashMap::new(), + expected_distance_metric: None, include_row_ids: None, shared_include_row_ids: None, }) @@ -72,6 +74,25 @@ impl VectorSearch { self } + pub fn with_expected_distance_metric(mut self, metric: String) -> Self { + self.expected_distance_metric = Some(metric); + self + } + + pub(crate) fn ensure_distance_metric(&self, actual: &str) -> crate::Result<()> { + if let Some(expected) = &self.expected_distance_metric { + if expected != actual { + return Err(crate::Error::DataInvalid { + message: format!( + "Vector search metric mismatch: query expects {expected}, but index uses {actual}" + ), + source: None, + }); + } + } + Ok(()) + } + pub(crate) fn set_shared_include_row_ids( &mut self, include_row_ids: Arc, diff --git a/crates/paimon/src/vindex/reader.rs b/crates/paimon/src/vindex/reader.rs index b40f0dd49..4bd8afd7e 100644 --- a/crates/paimon/src/vindex/reader.rs +++ b/crates/paimon/src/vindex/reader.rs @@ -510,6 +510,12 @@ fn prepare_search_with_shared_filter( merged_options.extend(vector_search.options.clone()); &merged_options }; + let metric_name = match metadata.metric { + MetricType::L2 => "l2", + MetricType::Cosine => "cosine", + MetricType::InnerProduct => "inner_product", + }; + vector_search.ensure_distance_metric(metric_name)?; if vector_search.vector.len() != metadata.dimension { return Err(crate::Error::DataInvalid { message: format!( diff --git a/docs/src/c-binding.md b/docs/src/c-binding.md index 2ca3b4aa3..2d9d480c8 100644 --- a/docs/src/c-binding.md +++ b/docs/src/c-binding.md @@ -520,6 +520,13 @@ and ranges. Combine predicates with `paimon_predicate_and`, ## Vector Scan, Plan, and Read +`paimon_vector_search_builder_execute_scored` returns global row IDs and scores +as Arrow Int64 and Float32 columns named `row_id` and `score`. An inclusive +interval supplied to `paimon_vector_search_builder_with_row_range` intersects +any scalar filter before Top-K. Use +`paimon_vector_search_builder_with_distance_metric` when the query requires a +specific metric. Primary-key vector results use file-local positions. + DE and primary-key vector searches use the same execution API: 1. Configure a `paimon_vector_search_builder` with the column, query, limit,