Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 156 additions & 5 deletions bindings/c/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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};

Expand Down Expand Up @@ -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::<Int64Array>()
.unwrap();
let scores = batch
.column_by_name("score")
.unwrap()
.as_any()
.downcast_ref::<Float32Array>()
.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::<Int64Array>()
.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::<Int64Array>()
.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";
Expand Down
2 changes: 2 additions & 0 deletions bindings/c/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,8 @@ pub(crate) struct VectorSearchState {
pub limit: Option<usize>,
pub options: std::collections::HashMap<String, String>,
pub filter: Option<Predicate>,
pub row_range: Option<(i64, i64)>,
pub distance_metric: Option<String>,
// Optional column projection applied by `execute_read` (plus the always-appended
// `__paimon_search_score`). `None` materializes every user column.
pub projection: Option<Vec<String>>,
Expand Down
133 changes: 133 additions & 0 deletions bindings/c/src/vector_search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<ArrowRecordBatchStream> {
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::<paimon::Result<Vec<_>>>()?;
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]>,
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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;
3 changes: 3 additions & 0 deletions crates/paimon/src/table/batch_vector_search_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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
Expand All @@ -154,6 +156,7 @@ impl<'a> BatchVectorSearchBuilder<'a> {
limit,
&self.options,
self.filter.as_ref(),
None,
context,
)
}
Expand Down
Loading
Loading