This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-vector-index.git
The following commit(s) were added to refs/heads/main by this push:
new 7b4b19b feat: unify per-call search statistics across language
bindings (#124)
7b4b19b is described below
commit 7b4b19bbb89d012bb5e318b0ebb92180b8cc1080
Author: Jingsong Lee <[email protected]>
AuthorDate: Mon Nov 16 11:59:27 2026 +0800
feat: unify per-call search statistics across language bindings (#124)
---
c/test_vindex.c | 67 +++++
core/README.md | 18 ++
core/src/diskann_io.rs | 4 +-
core/src/diskann_search.rs | 15 +
core/src/index.rs | 327 ++++++++++++++++++++-
core/src/io.rs | 13 +-
core/src/ivfflat_io.rs | 19 +-
core/src/ivfpq.rs | 12 +
core/src/ivfrq_io.rs | 10 +-
core/src/ivfsq_io.rs | 19 +-
core/src/lib.rs | 1 +
core/src/search_stats.rs | 227 ++++++++++++++
cpp/test_vindex.cpp | 39 +++
docs/api.html | 17 +-
docs/diskann.html | 2 +-
ffi/src/lib.rs | 76 +++++
include/paimon_vindex.hpp | 9 +
.../paimon/index/vector/VectorIndexNative.java | 2 +
.../paimon/index/vector/VectorIndexReader.java | 12 +
.../paimon/index/vector/VectorSearchStats.java | 92 ++++++
.../index/vector/VectorIndexRangeSearchTest.java | 40 +++
jni/src/lib.rs | 37 +++
python/README.md | 34 ++-
python/paimon_vindex/__init__.py | 109 ++++++-
python/paimon_vindex/_ffi.py | 65 ++++
python/tests/test_search_stats.py | 212 +++++++++++++
26 files changed, 1453 insertions(+), 25 deletions(-)
diff --git a/c/test_vindex.c b/c/test_vindex.c
index ac0e9c8..9d5c57f 100644
--- a/c/test_vindex.c
+++ b/c/test_vindex.c
@@ -19,6 +19,7 @@
#include "paimon_vindex.h"
+#include <float.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
@@ -333,6 +334,30 @@ static void run_roundtrip(
paimon_vindex_reader_warmup_queries(reader, query, 1, 32) != 0) {
fail_ffi("reader warmup_queries failed");
}
+ PaimonVindexSearchStats stats = {0};
+ ASSERT_TRUE(paimon_vindex_reader_search_stats(reader, &stats,
sizeof(stats)) == 0);
+ ASSERT_EQ_I64(stats.query_count, 1);
+ ASSERT_TRUE(stats.candidate_count >= 2);
+ ASSERT_EQ_I64(stats.fallback_reason, 0);
+ ASSERT_EQ_I64(stats.search_width, expected_index_type ==
PAIMON_VINDEX_INDEX_TYPE_DISKANN ? 2 : 1);
+ if (expected_index_type != PAIMON_VINDEX_INDEX_TYPE_DISKANN) {
+ ASSERT_EQ_I64(stats.initial_width, 4);
+ ASSERT_EQ_I64(stats.effective_width, 4);
+ ASSERT_EQ_I64(stats.candidate_count, ROUNDTRIP_NLIST *
ROUNDTRIP_PER_LIST);
+ }
+ /* Prefix writes cannot overwrite an older caller's shorter allocation. */
+ uint64_t prefix[2] = {0, UINT64_MAX};
+ ASSERT_TRUE(paimon_vindex_reader_search_stats(
+ reader, (PaimonVindexSearchStats *)prefix, sizeof(uint64_t)) == 0);
+ ASSERT_EQ_I64(prefix[0], 1);
+ ASSERT_TRUE(prefix[1] == UINT64_MAX);
+ ASSERT_TRUE(paimon_vindex_reader_search_stats(reader, &stats, 7) != 0);
+ ASSERT_TRUE(paimon_vindex_reader_search_stats(reader, NULL, sizeof(stats))
!= 0);
+ uint64_t future[13] = {0};
+ future[12] = UINT64_MAX;
+ ASSERT_TRUE(paimon_vindex_reader_search_stats(
+ reader, (PaimonVindexSearchStats *)future, sizeof(future)) == 0);
+ ASSERT_TRUE(future[12] == UINT64_MAX);
assert_id_in_cluster(result_ids[0], 0);
ASSERT_TRUE(isfinite(result_distances[0]));
if (expected_index_type == PAIMON_VINDEX_INDEX_TYPE_IVF_PQ) {
@@ -353,6 +378,9 @@ static void run_roundtrip(
reader, queries, 2, batch_params, batch_ids, batch_distances, 2)
!= 0) {
fail_ffi("reader search batch failed");
}
+ ASSERT_TRUE(paimon_vindex_reader_search_stats(reader, &stats,
sizeof(stats)) == 0);
+ ASSERT_EQ_I64(stats.query_count, 2);
+ ASSERT_TRUE(stats.candidate_count >= 2);
assert_id_in_cluster(batch_ids[0], 0);
assert_id_in_cluster(batch_ids[1], 1);
struct PaimonVindexSearchParamsV2 batch_params_v2 = {
@@ -400,6 +428,45 @@ static void run_roundtrip(
}
assert_id_in_cluster(batch_ids[0], 0);
assert_id_in_cluster(batch_ids[1], 1);
+ const uint8_t topk_filter[] = {
+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 58, 48, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 16, 0, 0, 0,
+ 160, 134, 161, 134
+ };
+ PaimonVindexSearchParamsEx filtered_params =
paimon_vindex_search_params_ex_default();
+ filtered_params.top_k = 2;
+ filtered_params.max_initial_filter_expansion_factor =
+ expected_index_type == PAIMON_VINDEX_INDEX_TYPE_DISKANN ? 0 : 1;
+ ASSERT_TRUE(paimon_vindex_reader_search_with_roaring_filter_ex(
+ reader, query, &filtered_params, topk_filter, sizeof(topk_filter),
+ result_ids, result_distances, 2) == 0);
+ ASSERT_TRUE(result_ids[0] == 100000 || result_ids[0] == 100001);
+ ASSERT_TRUE(result_ids[1] == 100000 || result_ids[1] == 100001);
+ ASSERT_TRUE(paimon_vindex_reader_search_stats(reader, &stats,
sizeof(stats)) == 0);
+ ASSERT_EQ_I64(stats.query_count, 1);
+ ASSERT_EQ_I64(stats.candidate_count,
+ expected_index_type == PAIMON_VINDEX_INDEX_TYPE_DISKANN ? 2 :
ROUNDTRIP_VECTOR_COUNT);
+ ASSERT_EQ_I64(stats.strategy, expected_index_type ==
PAIMON_VINDEX_INDEX_TYPE_DISKANN
+ ? PAIMON_VINDEX_SEARCH_STRATEGY_FILTERED_EXHAUSTIVE :
PAIMON_VINDEX_SEARCH_STRATEGY_IVF);
+ int64_t filtered_ids[4];
+ float filtered_distances[4];
+ ASSERT_TRUE(paimon_vindex_reader_search_batch_with_roaring_filter_ex(
+ reader, queries, 2, &filtered_params, topk_filter, sizeof(topk_filter),
+ filtered_ids, filtered_distances, 4) == 0);
+ ASSERT_TRUE(paimon_vindex_reader_search_stats(reader, &stats,
sizeof(stats)) == 0);
+ ASSERT_EQ_I64(stats.query_count, 2);
+ ASSERT_EQ_I64(stats.candidate_count,
+ expected_index_type == PAIMON_VINDEX_INDEX_TYPE_DISKANN ? 4 : 2 *
ROUNDTRIP_VECTOR_COUNT);
+ /* The original by-value ABI also promises K output slots for short
results. */
+ PaimonVindexSearchParams short_params = {
+ .top_k = 3, .search_width = batch_params.search_width, .width =
batch_params.width};
+ int64_t short_ids[3];
+ float short_distances[3];
+ ASSERT_TRUE(paimon_vindex_reader_search_with_roaring_filter(
+ reader, query, short_params, topk_filter, sizeof(topk_filter),
+ short_ids, short_distances, 3) == 0);
+ ASSERT_EQ_I64(short_ids[2], -1);
+ ASSERT_TRUE(short_distances[2] == FLT_MAX);
int range_supported = -1;
ASSERT_TRUE(paimon_vindex_reader_supports_range_search(reader,
&range_supported) == 0);
ASSERT_TRUE(range_supported == (expected_index_type !=
PAIMON_VINDEX_INDEX_TYPE_DISKANN));
diff --git a/core/README.md b/core/README.md
index 5fef38d..fba36b9 100644
--- a/core/README.md
+++ b/core/README.md
@@ -130,3 +130,21 @@ The crate ships its [normative v1 storage-format
specification](STORAGE_FORMAT.m
and byte-exact fixtures. Project documentation, language bindings, and
contribution guidance live in the
[Apache Paimon Vector Index
repository](https://github.com/apache/paimon-vector-index).
+
+## Top-K statistics
+
+`VectorIndexReader::search_stats()` returns `SearchStats` for every index
family
+and all single, batch, and Roaring-filtered top-K entry points. Batch counters
+include every query, progressive round, and storage worker; `initial_width` and
+`effective_width` are maxima across queries. `search_width` identifies IVF
nprobe
+(1) or DiskANN search-list size (2). Exhaustive DiskANN has zero graph width.
+`candidate_count` counts IVF rows before filtering (and repeated single-query
+work), or DiskANN PQ evaluations. `strategy` records the algorithm actually
run;
+`fallback_reason` records insufficient-result expansion/fallback.
+
+`read_calls`, `read_ranges`, and `read_bytes` count adapter requests, including
+lazy initialization. Cache units are IVF-FLAT/SQ payload entries or DiskANN
+adjacency/raw-vector windows; IVF-PQ/RQ report zero. A core top-K failure
clears
+the snapshot. Range search, optimization, warmup and calibration preserve it.
+Existing algorithm-specific diagnostics remain available. C exposes a bounded,
+appendable statistics prefix; C++, Java and Python expose the same snapshot.
diff --git a/core/src/diskann_io.rs b/core/src/diskann_io.rs
index 4a983f0..e58e47d 100644
--- a/core/src/diskann_io.rs
+++ b/core/src/diskann_io.rs
@@ -466,7 +466,7 @@ pub struct DiskAnnHeader {
}
pub struct DiskAnnIndexReader<R: SeekRead> {
- reader: R,
+ pub(crate) reader: crate::search_stats::ObservedReader<R>,
pub header: DiskAnnHeader,
resident: Option<Arc<DiskAnnResidentData>>,
options: ResolvedVectorIndexReaderOptions,
@@ -1405,7 +1405,7 @@ impl<R: SeekRead> DiskAnnIndexReader<R> {
usize::try_from(header.sections.vectors.length).unwrap_or(usize::MAX),
);
Ok(Self {
- reader,
+ reader: crate::search_stats::ObservedReader::new(reader),
header,
resident: None,
options,
diff --git a/core/src/diskann_search.rs b/core/src/diskann_search.rs
index f124f89..f60e8e7 100644
--- a/core/src/diskann_search.rs
+++ b/core/src/diskann_search.rs
@@ -1884,6 +1884,7 @@ impl<R: SeekRead>
crate::diskann_io::DiskAnnIndexReader<R> {
) -> io::Result<()> {
let vector_count = self.header.vector_count as usize;
let search_list_size = search_list_size.min(vector_count);
+ self.reader.observation.record_graph(search_list_size);
scratch.begin_graph_search(
vector_count,
search_list_size,
@@ -1906,6 +1907,12 @@ impl<R: SeekRead>
crate::diskann_io::DiskAnnIndexReader<R> {
},
search_list_size,
)?;
+ self.last_search_stats.pq_distance_evaluations = self
+ .last_search_stats
+ .pq_distance_evaluations
+ .saturating_add(1);
+ self.last_search_stats.pq_code_loads =
+ self.last_search_stats.pq_code_loads.saturating_add(1);
// L bounds the retained candidate set, not the number of expansions.
// Newly discovered closer nodes must still be expanded until no live
// frontier candidate can improve the retained set.
@@ -1945,6 +1952,14 @@ impl<R: SeekRead>
crate::diskann_io::DiskAnnIndexReader<R> {
&scratch.neighbor_buffer,
&mut scratch.scored_neighbors,
)?;
+ self.last_search_stats.pq_distance_evaluations = self
+ .last_search_stats
+ .pq_distance_evaluations
+ .saturating_add(scratch.scored_neighbors.len());
+ self.last_search_stats.pq_code_loads = self
+ .last_search_stats
+ .pq_code_loads
+ .saturating_add(scratch.scored_neighbors.len());
for scored_index in 0..scratch.scored_neighbors.len() {
let candidate = scratch.scored_neighbors[scored_index];
scratch.insert_graph_candidate(candidate,
search_list_size)?;
diff --git a/core/src/index.rs b/core/src/index.rs
index 2d2883a..1a13b1a 100644
--- a/core/src/index.rs
+++ b/core/src/index.rs
@@ -55,6 +55,7 @@ use crate::kmeans::KMeansConfig;
use crate::range::{RangeSearchResult, VectorRangeSearchParams};
pub use crate::read_options::{DeploymentProfile, VectorIndexReadPlan,
VectorIndexReaderOptions};
use crate::rq::{is_supported_rq_bits, padded_dimension, DEFAULT_RQ_BITS};
+pub use crate::search_stats::{SearchFallbackReason, SearchStats,
SearchStrategy};
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use roaring::RoaringTreemap;
@@ -1714,6 +1715,69 @@ impl<R: SeekRead> VectorIndexReader<R> {
self.metadata().total_vectors
}
+ fn search_observation(&self) -> &crate::search_stats::SearchObservation {
+ match self {
+ Self::IvfFlat(reader) => &reader.reader.observation,
+ Self::IvfSq(reader) => &reader.reader.observation,
+ Self::IvfPq(reader) => &reader.reader.inner.observation,
+ Self::IvfRq(reader) => &reader.reader.observation,
+ Self::DiskAnn(reader) => &reader.reader.observation,
+ }
+ }
+
+ /// Snapshot of the last top-K call, aggregated over the entire batch.
+ /// See [`SearchStats`] for counter, width, failure and cache semantics.
+ pub fn search_stats(&self) -> SearchStats {
+ self.search_observation().snapshot()
+ }
+
+ fn observed_search(
+ &mut self,
+ query_count: usize,
+ search: impl FnOnce(&mut Self) -> io::Result<(Vec<i64>, Vec<f32>)>,
+ ) -> io::Result<(Vec<i64>, Vec<f32>)> {
+ let observation = self.search_observation().clone();
+ let call = observation.begin(query_count, self.index_type() ==
IndexType::DiskAnn);
+ let result = search(self);
+ if result.is_ok() {
+ if let Some(legacy) = self.diskann_search_stats() {
+ observation.update(|stats| {
+ stats.candidate_count = legacy.pq_distance_evaluations as
u64;
+ stats.cache_hits = legacy
+ .adjacency_cache_hits
+ .saturating_add(legacy.raw_vector_cache_hits)
+ as u64;
+ stats.cache_misses = legacy
+ .adjacency_cache_misses
+ .saturating_add(legacy.raw_vector_cache_misses)
+ as u64;
+ stats.strategy = if legacy.pq_distance_evaluations == 0 {
+ SearchStrategy::NotExecuted
+ } else if legacy.filtered_graph_fallbacks > 0 {
+ stats.fallback_reason =
SearchFallbackReason::InsufficientResults;
+ if legacy.filtered_graph_queries ==
legacy.filtered_graph_fallbacks
+ && legacy.filtered_exhaustive_queries ==
legacy.filtered_graph_fallbacks
+ {
+ SearchStrategy::GraphThenExhaustive
+ } else {
+ SearchStrategy::Mixed
+ }
+ } else if legacy.filtered_exhaustive_queries > 0 {
+ if legacy.filtered_graph_queries > 0 {
+ SearchStrategy::Mixed
+ } else {
+ SearchStrategy::FilteredExhaustive
+ }
+ } else {
+ SearchStrategy::DiskAnnGraph
+ };
+ });
+ }
+ }
+ call.finish(result.is_ok());
+ result
+ }
+
pub fn diskann_search_stats(&self) -> Option<DiskAnnSearchStats> {
match self {
Self::DiskAnn(reader) => Some(reader.last_search_stats()),
@@ -1791,6 +1855,14 @@ impl<R: SeekRead> VectorIndexReader<R> {
&mut self,
query: &[f32],
params: VectorSearchParams,
+ ) -> io::Result<(Vec<i64>, Vec<f32>)> {
+ self.observed_search(1, |reader| reader.search_impl(query, params))
+ }
+
+ fn search_impl(
+ &mut self,
+ query: &[f32],
+ params: VectorSearchParams,
) -> io::Result<(Vec<i64>, Vec<f32>)> {
validate_query(query, self.dimension())?;
params.validate()?;
@@ -1985,6 +2057,17 @@ impl<R: SeekRead> VectorIndexReader<R> {
query: &[f32],
params: VectorSearchParams,
roaring_filter_bytes: &[u8],
+ ) -> io::Result<(Vec<i64>, Vec<f32>)> {
+ self.observed_search(1, |reader| {
+ reader.search_with_roaring_filter_impl(query, params,
roaring_filter_bytes)
+ })
+ }
+
+ fn search_with_roaring_filter_impl(
+ &mut self,
+ query: &[f32],
+ params: VectorSearchParams,
+ roaring_filter_bytes: &[u8],
) -> io::Result<(Vec<i64>, Vec<f32>)> {
validate_query(query, self.dimension())?;
params.validate()?;
@@ -2097,6 +2180,17 @@ impl<R: SeekRead> VectorIndexReader<R> {
queries: &[f32],
query_count: usize,
params: VectorSearchParams,
+ ) -> io::Result<(Vec<i64>, Vec<f32>)> {
+ self.observed_search(query_count, |reader| {
+ reader.search_batch_impl(queries, query_count, params)
+ })
+ }
+
+ fn search_batch_impl(
+ &mut self,
+ queries: &[f32],
+ query_count: usize,
+ params: VectorSearchParams,
) -> io::Result<(Vec<i64>, Vec<f32>)> {
validate_queries(queries, query_count, self.dimension())?;
params.validate()?;
@@ -2254,6 +2348,23 @@ impl<R: SeekRead> VectorIndexReader<R> {
query_count: usize,
params: VectorSearchParams,
roaring_filter_bytes: &[u8],
+ ) -> io::Result<(Vec<i64>, Vec<f32>)> {
+ self.observed_search(query_count, |reader| {
+ reader.search_batch_with_roaring_filter_impl(
+ queries,
+ query_count,
+ params,
+ roaring_filter_bytes,
+ )
+ })
+ }
+
+ fn search_batch_with_roaring_filter_impl(
+ &mut self,
+ queries: &[f32],
+ query_count: usize,
+ params: VectorSearchParams,
+ roaring_filter_bytes: &[u8],
) -> io::Result<(Vec<i64>, Vec<f32>)> {
validate_queries(queries, query_count, self.dimension())?;
params.validate()?;
@@ -2435,9 +2546,17 @@ fn progressive_ivf_search(
mut search: impl FnMut(usize) -> io::Result<(Vec<i64>, Vec<f32>)>,
) -> io::Result<(Vec<i64>, Vec<f32>)> {
let required_per_query = top_k.min(available_matches);
+ let result_len = query_count
+ .checked_mul(top_k)
+ .ok_or_else(|| invalid_input("query count * top_k overflows usize"))?;
let mut nprobe = initial_nprobe;
loop {
- let result = search(nprobe)?;
+ let mut result = search(nprobe)?;
+ // Low-level PQ single searches return only admitted candidates. The
+ // unified API uses fixed-size rows, including when the first filtered
+ // round is empty; otherwise chunks_exact would consider it complete.
+ result.0.resize(result_len, -1);
+ result.1.resize(result_len, f32::MAX);
if params.search_width != SearchWidth::Auto
|| nprobe >= nlist
|| required_per_query == 0
@@ -2978,6 +3097,212 @@ mod tests {
VectorIndexWriter::new(training)
}
+ #[derive(Clone)]
+ struct StatsCountingReader {
+ bytes: Arc<[u8]>,
+ reads: Arc<Mutex<[u64; 3]>>,
+ }
+
+ impl SeekRead for StatsCountingReader {
+ fn pread(&mut self, ranges: &mut [ReadRequest<'_>]) -> io::Result<()> {
+ let mut reads = self.reads.lock().unwrap();
+ reads[0] += 1;
+ reads[1] += ranges.len() as u64;
+ for range in ranges {
+ reads[2] += range.buf.len() as u64;
+ let start = range.pos as usize;
+ range
+ .buf
+ .copy_from_slice(&self.bytes[start..start +
range.buf.len()]);
+ }
+ Ok(())
+ }
+
+ fn try_clone_reader(&self) -> io::Result<Option<Self>> {
+ Ok(Some(self.clone()))
+ }
+ }
+
+ #[test]
+ fn unified_search_stats_cover_all_families_calls_filters_and_storage() {
+ let pool = rayon::ThreadPoolBuilder::new()
+ .num_threads(4)
+ .build()
+ .unwrap();
+ for family in ["ivf_flat", "ivf_sq", "ivf_pq", "ivf_rq", "diskann"] {
+ let mut values = options(&[
+ ("index.type", family),
+ ("dimension", "16"),
+ ("metric", "l2"),
+ ]);
+ if family != "diskann" {
+ values.insert("nlist".to_string(), "8".to_string());
+ }
+ let config = VectorIndexConfig::from_options(&values).unwrap();
+ let data = generate_clustered_data(512, 16, 8);
+ let mut writer = build_writer(config, &data, 512);
+ writer
+ .add_vectors(&(0..512).collect::<Vec<i64>>(), &data, 512)
+ .unwrap();
+ let mut bytes = Vec::new();
+ writer.write(&mut PosWriter::new(&mut bytes)).unwrap();
+ let reads = Arc::new(Mutex::new([0; 3]));
+ let mut reader = VectorIndexReader::open(StatsCountingReader {
+ bytes: bytes.into(),
+ reads: reads.clone(),
+ })
+ .unwrap();
+ assert_eq!(reader.search_stats(), SearchStats::default());
+ let params = if family == "diskann" {
+ VectorSearchParams::with_l_search(3, 100)
+ } else {
+ VectorSearchParams::new(3, 8)
+ };
+ let mut filter = RoaringTreemap::new();
+ filter.insert(0);
+ filter.insert(8);
+ filter.insert(16);
+ let mut filter_bytes = Vec::new();
+ filter.serialize_into(&mut filter_bytes).unwrap();
+ pool.install(|| {
+ for filtered in [false, true] {
+ for batch in [false, true] {
+ *reads.lock().unwrap() = [0; 3];
+ let result = match (batch, filtered) {
+ (false, false) => reader.search(&data[..16],
params),
+ (false, true) => reader.search_with_roaring_filter(
+ &data[..16],
+ params,
+ &filter_bytes,
+ ),
+ (true, false) => reader.search_batch(&data[..64],
4, params),
+ (true, true) =>
reader.search_batch_with_roaring_filter(
+ &data[..64],
+ 4,
+ params,
+ &filter_bytes,
+ ),
+ }
+ .unwrap();
+ let stats = reader.search_stats();
+ let count = if batch { 4 } else { 1 };
+ assert_eq!(stats.query_count, count, "{family}");
+ assert_eq!(result.0.len(), count as usize * 3);
+ assert_eq!(
+ [stats.read_calls, stats.read_ranges,
stats.read_bytes],
+ *reads.lock().unwrap(),
+ "{family}"
+ );
+ assert!(stats.candidate_count >= count * 3, "{family}:
{stats:?}");
+ if family == "diskann" {
+ assert_eq!(stats.search_width, 2);
+ assert_eq!(
+ stats.strategy,
+ if filtered {
+ SearchStrategy::FilteredExhaustive
+ } else {
+ SearchStrategy::DiskAnnGraph
+ }
+ );
+ assert_eq!(stats.effective_width, if filtered { 0
} else { 100 });
+ if batch && !filtered {
+ assert!(
+ reader
+ .diskann_search_stats()
+ .unwrap()
+ .parallel_session_queries
+ > 0
+ );
+ }
+ } else {
+ assert_eq!(stats.search_width, 1);
+ assert_eq!(stats.initial_width, 8);
+ assert_eq!(stats.effective_width, 8);
+ assert_eq!(stats.candidate_count, 512 * count);
+ assert_eq!(stats.strategy, SearchStrategy::Ivf);
+ }
+ assert_eq!(stats.fallback_reason,
SearchFallbackReason::None);
+ reader.optimize_for_search().unwrap();
+ reader.warmup_queries(&data[..16], 1, 32).unwrap();
+ assert_eq!(reader.search_stats(), stats);
+ }
+ }
+ });
+ assert!(reader.search(&[], params).is_err());
+ assert_eq!(reader.search_stats(), SearchStats::default());
+ }
+ }
+
+ #[test]
+ fn unified_search_stats_track_progressive_width_and_all_round_candidates()
{
+ for family in ["ivf_flat", "ivf_sq", "ivf_pq", "ivf_rq"] {
+ let config = VectorIndexConfig::from_options(&options(&[
+ ("index.type", family),
+ ("dimension", "16"),
+ ("nlist", "64"),
+ ("metric", "l2"),
+ ]))
+ .unwrap();
+ let (mut reader, data) = build_reader(config);
+ let queries = [data[..16].to_vec(), data[63 * 16..64 *
16].to_vec()].concat();
+ let mut filter = RoaringTreemap::new();
+ for id in (0..512).step_by(64) {
+ filter.insert(id);
+ }
+ let mut bytes = Vec::new();
+ filter.serialize_into(&mut bytes).unwrap();
+ let params =
+
VectorSearchParams::automatic(8).with_max_initial_filter_expansion_factor(1);
+ let initial = params.resolve_ivf_nprobe(64, 512, Some(8)).unwrap()
as u64;
+ reader
+ .search_batch_with_roaring_filter(&queries, 2, params, &bytes)
+ .unwrap();
+ let stats = reader.search_stats();
+ assert_eq!(stats.query_count, 2);
+ assert_eq!(stats.initial_width, initial, "{family}");
+ assert!(
+ stats.effective_width > stats.initial_width,
+ "{family}: {stats:?}"
+ );
+ assert_eq!(
+ stats.fallback_reason,
+ SearchFallbackReason::InsufficientResults
+ );
+ assert_eq!(stats.initial_width, 8);
+ assert_eq!(stats.effective_width, 64);
+ // The near query stops after eight lists; the far query scans all
+ // lists exactly once through successive batch probe ranges.
+ assert_eq!(stats.candidate_count, 64 + 512);
+ let full = reader
+ .search_batch_with_roaring_filter(
+ &queries,
+ 2,
+ VectorSearchParams::new(8, 64),
+ &bytes,
+ )
+ .unwrap();
+ for (query_index, query) in queries.chunks_exact(16).enumerate() {
+ let single = reader
+ .search_with_roaring_filter(query, params, &bytes)
+ .unwrap();
+ let stats = reader.search_stats();
+ assert_eq!(stats.query_count, 1);
+ assert_eq!(stats.initial_width, initial);
+ assert!(stats.effective_width >= initial);
+ assert_eq!(single.0.len(), 8, "{family}");
+ assert_eq!(single.1.len(), 8, "{family}");
+ assert_eq!(stats.effective_width, if query_index == 0 { 8 }
else { 64 });
+ // Single-query retries rescan each complete prefix
(8+16+32+64).
+ assert_eq!(
+ stats.candidate_count,
+ if query_index == 0 { 64 } else { 960 }
+ );
+ assert!(single.0.iter().all(|id| *id >= 0));
+ }
+ assert!(full.0.iter().all(|id| *id >= 0));
+ }
+ }
+
#[test]
fn diskann_search_stats_are_available_through_unified_reader() {
let dimension = 8;
diff --git a/core/src/io.rs b/core/src/io.rs
index 8d7d6fa..695ebc8 100644
--- a/core/src/io.rs
+++ b/core/src/io.rs
@@ -104,15 +104,15 @@ pub(crate) struct ReadMetrics {
pub requested_bytes: usize,
}
-struct MeasuredSeekRead<R> {
- inner: R,
+pub(crate) struct MeasuredSeekRead<R> {
+ pub(crate) inner: crate::search_stats::ObservedReader<R>,
metrics: Option<ReadMetrics>,
}
impl<R> MeasuredSeekRead<R> {
fn new(inner: R) -> Self {
Self {
- inner,
+ inner: crate::search_stats::ObservedReader::new(inner),
metrics: None,
}
}
@@ -139,7 +139,10 @@ impl<R: SeekRead> SeekRead for MeasuredSeekRead<R> {
fn try_clone_reader(&self) -> io::Result<Option<Self>> {
// Clones start with metrics disabled, so their I/O is not included
here.
- Ok(self.inner.try_clone_reader()?.map(Self::new))
+ Ok(self.inner.try_clone_reader()?.map(|inner| Self {
+ inner,
+ metrics: None,
+ }))
}
fn read_capabilities(&self) -> SeekReadCapabilities {
@@ -535,7 +538,7 @@ fn pq_metadata_bytes(
}
pub struct IVFPQIndexReader<R: SeekRead> {
- reader: MeasuredSeekRead<R>,
+ pub(crate) reader: MeasuredSeekRead<R>,
pub d: usize,
pub nlist: usize,
pub m: usize,
diff --git a/core/src/ivfflat_io.rs b/core/src/ivfflat_io.rs
index 3c081d4..1ae8bcb 100644
--- a/core/src/ivfflat_io.rs
+++ b/core/src/ivfflat_io.rs
@@ -187,7 +187,7 @@ fn write_ivfflat_index_with_buffer_limit(
}
pub struct IVFFlatIndexReader<R: SeekRead> {
- reader: R,
+ pub(crate) reader: crate::search_stats::ObservedReader<R>,
pub d: usize,
pub nlist: usize,
pub metric: MetricType,
@@ -397,7 +397,7 @@ impl<R: SeekRead> IVFFlatIndexReader<R> {
}
Ok(Self {
- reader,
+ reader: crate::search_stats::ObservedReader::new(reader),
d,
nlist,
metric,
@@ -624,6 +624,9 @@ impl<R: SeekRead> IVFFlatIndexReader<R> {
&& entry.id_bytes_len == self.list_id_bytes_lens[list_id]
&& entry.d == self.d
{
+ self.reader
+ .observation
+ .update(|stats| stats.cache_hits =
stats.cache_hits.saturating_add(1));
results[position] = Some(Arc::clone(&entry.list));
continue;
}
@@ -631,6 +634,9 @@ impl<R: SeekRead> IVFFlatIndexReader<R> {
cache.remove(list_id);
cache.order.retain(|&id| id != list_id);
}
+ self.reader
+ .observation
+ .update(|stats| stats.cache_misses =
stats.cache_misses.saturating_add(1));
misses.push((position, list_id));
}
let mut reads = 0;
@@ -793,6 +799,9 @@ impl<R: SeekRead> IVFFlatIndexReader<R> {
let (probe_indices, _) =
kmeans::find_topk(&q, &self.quantizer_centroids, self.nlist,
self.d, nprobe);
+ self.reader
+ .observation
+ .record_ivf(&probe_indices, 0, &self.list_counts);
let mut heap = ReaderTopKHeap::new(k);
let mut batch_start = 0usize;
while batch_start < probe_indices.len() {
@@ -1211,6 +1220,12 @@ pub(crate) fn
search_batch_ivfflat_reader_filter_range<R: SeekRead>(
d,
probe_end,
);
+ for probes in &all_probe_indices {
+ reader
+ .reader
+ .observation
+ .record_ivf(probes, probe_start, &reader.list_counts);
+ }
let mut list_to_queries = vec![Vec::new(); reader.nlist];
let mut unique_lists = Vec::new();
diff --git a/core/src/ivfpq.rs b/core/src/ivfpq.rs
index bf6955f..02d5771 100644
--- a/core/src/ivfpq.rs
+++ b/core/src/ivfpq.rs
@@ -1610,6 +1610,11 @@ pub fn search_with_reader_filter<R: SeekRead>(
let (probe_indices, coarse_dists) =
kmeans::find_topk(&q, &reader.quantizer_centroids, reader.nlist, d,
nprobe);
+ reader
+ .reader
+ .inner
+ .observation
+ .record_ivf(&probe_indices, 0, &reader.list_counts);
let use_precomputed =
metric == MetricType::L2 && by_residual &&
!reader.precomputed_table.is_empty();
@@ -2826,6 +2831,13 @@ fn
search_batch_reader_filter_with_reuse_mode_and_observer<R: SeekRead>(
d,
probe_end,
);
+ for probes in &all_probe_indices {
+ reader
+ .reader
+ .inner
+ .observation
+ .record_ivf(probes, probe_start, &reader.list_counts);
+ }
timing.coarse = elapsed_since(coarse_started);
// Step 3: Read every probed list once. Queries share the decoded list
diff --git a/core/src/ivfrq_io.rs b/core/src/ivfrq_io.rs
index b35135d..16aedf1 100644
--- a/core/src/ivfrq_io.rs
+++ b/core/src/ivfrq_io.rs
@@ -261,7 +261,7 @@ fn block_list(index: &IVFRQIndex, list_id: usize, order:
&[usize]) -> (Vec<u8>,
}
pub struct IVFRQIndexReader<R: SeekRead> {
- reader: R,
+ pub(crate) reader: crate::search_stats::ObservedReader<R>,
pub d: usize,
pub padded_d: usize,
pub nlist: usize,
@@ -487,7 +487,7 @@ impl<R: SeekRead> IVFRQIndexReader<R> {
rq_metadata_bytes(d, nlist, rotation_rounds)?;
Ok(Self {
- reader,
+ reader: crate::search_stats::ObservedReader::new(reader),
d,
padded_d,
nlist,
@@ -1145,6 +1145,12 @@ pub(crate) fn search_batch_ivfrq_reader_filter_range<R:
SeekRead>(
reader.d,
probe_end,
);
+ for probes in &all_probe_indices {
+ reader
+ .reader
+ .observation
+ .record_ivf(probes, probe_start, &reader.list_counts);
+ }
let query_norms = processed
.chunks_exact(reader.d)
.map(fvec_norm_l2sqr)
diff --git a/core/src/ivfsq_io.rs b/core/src/ivfsq_io.rs
index 42ff19a..df641d2 100644
--- a/core/src/ivfsq_io.rs
+++ b/core/src/ivfsq_io.rs
@@ -172,7 +172,7 @@ pub fn write_ivfsq_index(index: &IVFSQIndex, out: &mut dyn
SeekWrite) -> io::Res
}
pub struct IVFSQIndexReader<R: SeekRead> {
- reader: R,
+ pub(crate) reader: crate::search_stats::ObservedReader<R>,
pub d: usize,
pub nlist: usize,
pub metric: MetricType,
@@ -393,7 +393,7 @@ impl<R: SeekRead> IVFSQIndexReader<R> {
SqListCache::new(nlist,
options.memory_budget_bytes.saturating_sub(resident));
Ok(Self {
- reader,
+ reader: crate::search_stats::ObservedReader::new(reader),
d,
nlist,
metric,
@@ -513,6 +513,9 @@ impl<R: SeekRead> IVFSQIndexReader<R> {
&& entry.id_bytes_len == self.list_id_bytes_lens[list_id]
&& entry.d == self.d
{
+ self.reader
+ .observation
+ .update(|stats| stats.cache_hits =
stats.cache_hits.saturating_add(1));
results[position] = Some(Arc::clone(&entry.list));
continue;
}
@@ -521,6 +524,9 @@ impl<R: SeekRead> IVFSQIndexReader<R> {
cache.remove(list_id);
cache.order.retain(|&id| id != list_id);
}
+ self.reader
+ .observation
+ .update(|stats| stats.cache_misses =
stats.cache_misses.saturating_add(1));
misses.push((position, list_id));
}
let mut reads = 0;
@@ -648,6 +654,9 @@ impl<R: SeekRead> IVFSQIndexReader<R> {
self.d,
nprobe,
);
+ self.reader
+ .observation
+ .record_ivf(&probe_indices, 0, &self.list_counts);
let mut heap = TopKHeap::new(k);
let d = self.d;
let metric = self.metric;
@@ -1050,6 +1059,12 @@ pub(crate) fn search_batch_ivfsq_reader_filter_range<R:
SeekRead>(
reader.d,
probe_end,
);
+ for probes in &all_probe_indices {
+ reader
+ .reader
+ .observation
+ .record_ivf(probes, probe_start, &reader.list_counts);
+ }
let mut seen = vec![false; reader.nlist];
let mut unique_lists = Vec::new();
for list_ids in &all_probe_indices {
diff --git a/core/src/lib.rs b/core/src/lib.rs
index 44d9ef7..79287ae 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -44,6 +44,7 @@ pub mod pq;
pub mod range;
pub mod read_options;
pub mod rq;
+pub mod search_stats;
pub mod shuffler;
pub(crate) mod sparse_table;
pub mod sq;
diff --git a/core/src/search_stats.rs b/core/src/search_stats.rs
new file mode 100644
index 0000000..caa1cbd
--- /dev/null
+++ b/core/src/search_stats.rs
@@ -0,0 +1,227 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::io::{ReadRequest, SeekRead, SeekReadCapabilities};
+use std::io;
+use std::sync::{Arc, Mutex};
+
+/// The algorithm actually executed by a top-K call.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+#[repr(u64)]
+pub enum SearchStrategy {
+ #[default]
+ NotExecuted = 0,
+ Ivf = 1,
+ DiskAnnGraph = 2,
+ FilteredExhaustive = 3,
+ GraphThenExhaustive = 4,
+ Mixed = 5,
+}
+
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+#[repr(u64)]
+pub enum SearchFallbackReason {
+ #[default]
+ None = 0,
+ /// Automatic IVF expanded, or DiskANN fell back after graph filtering.
+ InsufficientResults = 1,
+}
+
+/// Statistics for the last top-K call through `VectorIndexReader`.
+///
+/// A batch is one call: counters sum all queries, retries and worker sessions;
+/// widths are maxima across queries. IVF candidates count selected list rows
+/// before filtering (including repeated work in single-query retries). DiskANN
+/// candidates count PQ distance evaluations, including exhaustive fallback
work.
+/// Reads count `SeekRead::pread` invocations, requested ranges and bytes,
including
+/// lazy initialization. They describe storage adapter requests, not physical
I/O.
+/// Cache counters count IVF payload entries or DiskANN adjacency/raw-vector
+/// windows. Families without a payload cache report zero. Range searches,
+/// warmup and optimization preserve this snapshot; failed top-K calls clear
it.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+pub struct SearchStats {
+ pub query_count: u64,
+ /// 1 = IVF nprobe, 2 = DiskANN search-list size; 0 before a successful
call.
+ pub search_width: u64,
+ pub initial_width: u64,
+ pub effective_width: u64,
+ pub candidate_count: u64,
+ pub strategy: SearchStrategy,
+ pub fallback_reason: SearchFallbackReason,
+ pub read_calls: u64,
+ pub read_ranges: u64,
+ pub read_bytes: u64,
+ pub cache_hits: u64,
+ pub cache_misses: u64,
+}
+
+#[derive(Default)]
+struct ObservationState {
+ active: bool,
+ stats: SearchStats,
+}
+
+/// Shared by DiskANN worker readers so their storage requests belong to the
+/// parent call. No thread-local state: separate readers remain independent.
+#[derive(Clone, Default)]
+pub(crate) struct SearchObservation(Arc<Mutex<ObservationState>>);
+
+impl SearchObservation {
+ pub(crate) fn begin(&self, query_count: usize, diskann: bool) ->
SearchCall {
+ let mut state = self.0.lock().unwrap_or_else(|error|
error.into_inner());
+ state.stats = SearchStats {
+ query_count: query_count as u64,
+ search_width: if diskann { 2 } else { 1 },
+ strategy: if diskann {
+ SearchStrategy::DiskAnnGraph
+ } else {
+ SearchStrategy::Ivf
+ },
+ ..SearchStats::default()
+ };
+ state.active = true;
+ SearchCall(self.clone(), false)
+ }
+
+ pub(crate) fn finish(&self, succeeded: bool) {
+ let mut state = self.0.lock().unwrap_or_else(|error|
error.into_inner());
+ state.active = false;
+ if !succeeded {
+ state.stats = SearchStats::default();
+ }
+ }
+
+ pub(crate) fn snapshot(&self) -> SearchStats {
+ self.0
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .stats
+ }
+
+ pub(crate) fn update(&self, update: impl FnOnce(&mut SearchStats)) {
+ let mut state = self.0.lock().unwrap_or_else(|error|
error.into_inner());
+ if state.active {
+ update(&mut state.stats);
+ }
+ }
+
+ pub(crate) fn record_ivf(&self, probes: &[usize], start: usize, counts:
&[i32]) {
+ self.update(|stats| {
+ let width = probes.len() as u64;
+ if stats.initial_width == 0 {
+ stats.initial_width = width;
+ }
+ if start > 0 || width > stats.effective_width &&
stats.effective_width > 0 {
+ stats.fallback_reason =
SearchFallbackReason::InsufficientResults;
+ }
+ stats.effective_width = stats.effective_width.max(width);
+ for &list in probes.iter().skip(start) {
+ stats.candidate_count =
stats.candidate_count.saturating_add(counts[list] as u64);
+ }
+ });
+ }
+
+ pub(crate) fn record_graph(&self, width: usize) {
+ self.update(|stats| {
+ stats.initial_width = stats.initial_width.max(width as u64);
+ stats.effective_width = stats.effective_width.max(width as u64);
+ });
+ }
+}
+
+/// Clears a partial snapshot when a search unwinds through an FFI/JNI
boundary.
+pub(crate) struct SearchCall(SearchObservation, bool);
+
+impl SearchCall {
+ pub(crate) fn finish(mut self, succeeded: bool) {
+ self.0.finish(succeeded);
+ self.1 = true;
+ }
+}
+
+impl Drop for SearchCall {
+ fn drop(&mut self) {
+ if !self.1 {
+ self.0.finish(false);
+ }
+ }
+}
+
+pub(crate) struct ObservedReader<R> {
+ inner: R,
+ pub(crate) observation: SearchObservation,
+}
+
+impl<R> ObservedReader<R> {
+ pub(crate) fn new(inner: R) -> Self {
+ Self {
+ inner,
+ observation: SearchObservation::default(),
+ }
+ }
+}
+
+impl<R: SeekRead> SeekRead for ObservedReader<R> {
+ fn pread(&mut self, ranges: &mut [ReadRequest<'_>]) -> io::Result<()> {
+ if !ranges.is_empty() {
+ self.observation.update(|stats| {
+ stats.read_calls = stats.read_calls.saturating_add(1);
+ stats.read_ranges =
stats.read_ranges.saturating_add(ranges.len() as u64);
+ for range in ranges.iter() {
+ stats.read_bytes =
stats.read_bytes.saturating_add(range.buf.len() as u64);
+ }
+ });
+ }
+ self.inner.pread(ranges)
+ }
+
+ fn try_clone_reader(&self) -> io::Result<Option<Self>> {
+ Ok(self.inner.try_clone_reader()?.map(|inner| Self {
+ inner,
+ observation: self.observation.clone(),
+ }))
+ }
+
+ fn read_capabilities(&self) -> SeekReadCapabilities {
+ self.inner.read_capabilities()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn unwinding_clears_partial_statistics_and_allows_the_next_call() {
+ let observation = SearchObservation::default();
+ let result = std::panic::catch_unwind(|| {
+ let _call = observation.begin(3, false);
+ observation.update(|stats| {
+ stats.read_bytes = 42;
+ panic!("failed while collecting statistics");
+ });
+ });
+ assert!(result.is_err());
+ assert_eq!(observation.snapshot(), SearchStats::default());
+ observation.update(|stats| stats.read_bytes = 99);
+ assert_eq!(observation.snapshot(), SearchStats::default());
+ let call = observation.begin(1, false);
+ observation.record_ivf(&[0], 0, &[7]);
+ call.finish(true);
+ assert_eq!(observation.snapshot().candidate_count, 7);
+ }
+}
diff --git a/cpp/test_vindex.cpp b/cpp/test_vindex.cpp
index 308fc91..f8f5c76 100644
--- a/cpp/test_vindex.cpp
+++ b/cpp/test_vindex.cpp
@@ -235,6 +235,14 @@ static void run_roundtrip(
reader.warmup_queries(query.data(), 1, 32);
}
auto result = reader.search(query.data(), search_params);
+ auto stats = reader.search_stats();
+ ASSERT_EQ(stats.query_count, 1);
+ ASSERT_TRUE(stats.candidate_count >= 2);
+ ASSERT_EQ(stats.fallback_reason, 0);
+ if (expected_index_type != PAIMON_VINDEX_INDEX_TYPE_DISKANN) {
+ ASSERT_EQ(stats.initial_width, 4);
+ ASSERT_EQ(stats.effective_width, 4);
+ }
ASSERT_EQ(result.ids.size(), 2);
assert_id_in_cluster(result.ids[0], 0);
ASSERT_TRUE(std::isfinite(result.distances[0]));
@@ -252,9 +260,40 @@ static void run_roundtrip(
batch_params.ivfpq_batch_table_reuse =
PAIMON_VINDEX_IVFPQ_BATCH_TABLE_REUSE_OFF;
batch_params.ivfpq_batch_table_reuse_max_bytes = 1;
auto batch = reader.search_batch(queries.data(), 2, batch_params);
+ stats = reader.search_stats();
+ ASSERT_EQ(stats.query_count, 2);
+ ASSERT_TRUE(stats.candidate_count >= 2);
ASSERT_EQ(batch.ids.size(), 2);
assert_id_in_cluster(batch.ids[0], 0);
assert_id_in_cluster(batch.ids[1], 1);
+ const uint8_t topk_filter[] = {
+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 58, 48, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 16, 0, 0, 0,
+ 160, 134, 161, 134
+ };
+ auto filtered_params = paimon::vindex::SearchParams::automatic(3);
+ filtered_params.max_initial_filter_expansion_factor =
+ expected_index_type == PAIMON_VINDEX_INDEX_TYPE_DISKANN ? 0 : 1;
+ auto filtered = reader.search_with_roaring_filter(
+ query.data(), filtered_params, topk_filter, sizeof(topk_filter));
+ ASSERT_TRUE(filtered.ids[0] == 100000 || filtered.ids[0] == 100001);
+ ASSERT_TRUE(filtered.ids[1] == 100000 || filtered.ids[1] == 100001);
+ ASSERT_EQ(filtered.ids.size(), 3);
+ ASSERT_EQ(filtered.ids[2], -1);
+ ASSERT_EQ(filtered.distances[2], std::numeric_limits<float>::max());
+ stats = reader.search_stats();
+ ASSERT_EQ(stats.query_count, 1);
+ ASSERT_EQ(stats.candidate_count,
+ expected_index_type == PAIMON_VINDEX_INDEX_TYPE_DISKANN ? 2 :
kRoundtripVectorCount);
+ auto filtered_batch = reader.search_batch_with_roaring_filter(
+ queries.data(), 2, filtered_params, topk_filter, sizeof(topk_filter));
+ stats = reader.search_stats();
+ ASSERT_EQ(filtered_batch.ids.size(), 6);
+ ASSERT_EQ(filtered_batch.ids[2], -1);
+ ASSERT_EQ(filtered_batch.ids[5], -1);
+ ASSERT_EQ(stats.query_count, 2);
+ ASSERT_EQ(stats.candidate_count,
+ expected_index_type == PAIMON_VINDEX_INDEX_TYPE_DISKANN ? 4 : 2 *
kRoundtripVectorCount);
ASSERT_EQ(reader.supports_range_search(), expected_index_type !=
PAIMON_VINDEX_INDEX_TYPE_DISKANN);
if (expected_index_type == PAIMON_VINDEX_INDEX_TYPE_DISKANN) {
bool rejected = false;
diff --git a/docs/api.html b/docs/api.html
index 7874ac7..33e1d95 100644
--- a/docs/api.html
+++ b/docs/api.html
@@ -64,7 +64,7 @@
<div
class="table-wrap"><table><thead><tr><th>Parameter</th><th>Applies
to</th><th>Description</th></tr></thead><tbody>
<tr><td><code>top_k</code></td><td>All indexes</td><td>Number of
nearest neighbors returned for each query.</td></tr>
<tr><td><code>Auto</code> width</td><td>All indexes</td><td>IVF
starts at <code>max(8, ceil(nlist/16))</code>, adds enough average-list
capacity for at least <code>4 × top_k</code> candidates, scales for filter
selectivity, and progressively doubles when a filtered result is short. DiskANN
uses a calibrated width when present, otherwise <code>max(100, 2 ×
top_k)</code>.</td></tr>
-
<tr><td><code>max_initial_filter_expansion_factor</code></td><td>Automatic IVF
search in Rust, C, C++, and Java</td><td>Optional cap on inverse-selectivity
expansion of the initial <code>nprobe</code>. Unset preserves the current
unlimited behavior. A value of 1 keeps the unfiltered automatic width. Lower
factors reduce initial search work but may reduce recall compared with uncapped
automatic search. Progressive expansion occurs only when fewer than
<code>top_k</code> valid [...]
+
<tr><td><code>max_initial_filter_expansion_factor</code></td><td>Automatic IVF
search in Rust, C, C++, Java, and Python</td><td>Optional cap on
inverse-selectivity expansion of the initial <code>nprobe</code>. Unset
preserves the current unlimited behavior. A value of 1 keeps the unfiltered
automatic width. Lower factors reduce initial search work but may reduce recall
compared with uncapped automatic search. Progressive expansion occurs only when
fewer than <code>top_k</code [...]
<tr><td><code>nprobe</code></td><td>IVF families</td><td>Explicit
expert override for the number of lists probed. A tagged IVF width is rejected
by DiskANN rather than silently ignored.</td></tr>
<tr><td><code>l_search</code></td><td>DiskANN</td><td>Explicit
expert override for graph search-list size; it is clamped to at least
<code>top_k</code>. A tagged DiskANN width is rejected by IVF indexes.</td></tr>
<tr><td><code>ivfpq_batch_table_reuse</code></td><td>8-bit IVF-PQ
batch search</td><td>Controls reuse of query distance tables across inverted
lists: <code>off</code>, <code>on</code>, or <code>auto</code>. The default is
<code>auto</code>.</td></tr>
@@ -74,6 +74,21 @@
<div class="callout"><strong>IVF-RQ width is a build
option</strong><code>rq.bits</code> accepts 1–8 and defaults to 4. It is
persisted in the file and reported as <code>rq_bits</code> /
<code>rqBits</code> metadata; search has no separate bit-width switch.</div>
</section>
+ <section class="article-section" id="search-stats">
+ <h2>Per-call top-K statistics</h2>
+ <p>All index families expose one snapshot after each top-K call:
Rust <code>reader.search_stats()</code>, C
<code>paimon_vindex_reader_search_stats(reader, &stats,
sizeof(stats))</code>, C++ and Python <code>reader.search_stats()</code>, and
Java <code>reader.searchStats()</code>. Existing result types and search entry
points retain their ABI. Rust's <code>diskann_search_stats()</code> and
<code>ivfrq_search_stats()</code> remain available for algorithm-specific
diagnostics.</p>
+ <div
class="table-wrap"><table><thead><tr><th>Field</th><th>Meaning</th></tr></thead><tbody>
+ <tr><td><code>query_count</code></td><td>Original query count,
including queries that finish before progressive batch expansion. Counters sum
all queries, retries, and parallel worker sessions in this call.</td></tr>
+ <tr><td><code>search_width</code>, <code>initial_width</code>,
<code>effective_width</code></td><td>Width kind (1 IVF nprobe, 2 DiskANN
search-list size), first executed width, and largest executed width. Widths are
maxima across batch queries and clamp to the available lists/nodes. An
exhaustive DiskANN scan has zero graph width.</td></tr>
+ <tr><td><code>candidate_count</code></td><td>IVF list rows
selected before filtering; repeated work in single-query retries counts again.
Batch retries count only newly probed lists. DiskANN counts PQ distance
evaluations, including graph work and exhaustive fallback.</td></tr>
+ <tr><td><code>strategy</code>,
<code>fallback_reason</code></td><td>Strategy: 0 not executed, 1 IVF, 2 DiskANN
graph, 3 filtered exhaustive, 4 graph then exhaustive, 5 mixed batch
strategies. Fallback: 0 none, 1 insufficient results (automatic IVF expansion
or DiskANN graph fallback).</td></tr>
+ <tr><td><code>read_calls</code>, <code>read_ranges</code>,
<code>read_bytes</code></td><td>Positional-read calls, requested ranges and
bytes at the storage adapter boundary, including lazy initialization and all
workers. These counters do not measure physical device traffic or an adapter's
own cache.</td></tr>
+ <tr><td><code>cache_hits</code>,
<code>cache_misses</code></td><td>IVF-FLAT/SQ payload cache entries, or DiskANN
adjacency/raw-vector windows. IVF-PQ/RQ have no payload cache and report zero.
Batch payload sharing may reduce reads without creating additional cache
hits.</td></tr>
+ </tbody></table></div>
+ <p>Before the first top-K call the snapshot is zero. A top-K failure
inside core clears it; validation rejected by a language wrapper before
entering core preserves it. Range search, optimization, warmup and calibration
preserve it. Serialize search and snapshot retrieval when sharing a reader
across threads. C callers provide the output allocation size: only complete
known <code>uint64_t</code> fields within that size are written, so future
fields can be appended safely.</p>
+ <p>Python supports <code>SearchParams.automatic(top_k=10,
max_initial_filter_expansion_factor=4)</code> for both single and batched
filtered IVF calls. <code>None</code> is uncapped; positive integers cap
initial expansion only. Explicit widths reject this setting. With an older
native library, existing top-K calls still work; requesting the new cap or
statistics without the corresponding native exports raises an upgrade error.</p>
+ </section>
+
<section class="article-section" id="range">
<h2>Range search parameters and results</h2>
<p>Range search returns every eligible probed row inside a half-open
distance band instead of a fixed number of nearest neighbours. Rust, C, C++,
JNI/Java and Python support IVF-FLAT, IVF-SQ, IVF-PQ and IVF-RQ with L2, cosine
and inner product, for single/batch queries with or without a Roaring
allow-list. FLAT tests exact distances; SQ, PQ and RQ test quantized estimates.
Capability queries delegate to core. DiskANN remains unsupported; exact,
complete membership requires full [...]
diff --git a/docs/diskann.html b/docs/diskann.html
index 76c684a..f9bdac8 100644
--- a/docs/diskann.html
+++ b/docs/diskann.html
@@ -132,7 +132,7 @@ reader.calibrate_search_width(&representative_queries,
representative_query_
let params = VectorSearchParams::automatic(10);
let (ids, squared_l2) = reader.search(&query, params)?;</code></pre></div>
<p>The core API depends only on <code>SeekRead</code>; the
application storage adapter owns local-cache, object-store, and transport
details. Its <code>pread</code> implementation should issue all ranges in a
search round concurrently and may report immutable-source capabilities so
DiskANN does not overfill a callback or choose the wrong coalescing size. Its
I/O executor must remain runnable when CPU query workers are saturated:
recursively scheduling range reads onto that same [...]
- <p>The parent Reader and retained search-session clones share one
immutable raw-vector LRU. Query-local caches hold borrowed <code>Arc</code>
windows, so concurrent reranks for the same range are single-flighted instead
of reading duplicate bytes. Cache hits and oldest eviction update linked
recency metadata in constant time, and capacity is charged by retained
<code>Vec::capacity()</code>. Misses in one search are read together; a query
whose working set is larger than its loc [...]
+ <p>The parent Reader and retained search-session clones share one
immutable raw-vector LRU. Query-local caches hold borrowed <code>Arc</code>
windows, so concurrent reranks for the same range are single-flighted instead
of reading duplicate bytes. Cache hits and oldest eviction update linked
recency metadata in constant time, and capacity is charged by retained
<code>Vec::capacity()</code>. Misses in one search are read together; a query
whose working set is larger than its loc [...]
<p>F16 compact-vector rerank on AArch64 loads unaligned
half-precision lanes, rejects non-finite values, converts them to F32, and
accumulates L2 in the same NEON loop. This removes the temporary decode buffer
and the second SIMD pass while preserving the scalar fallback and sentinel
behavior on other targets.</p>
<p>Cold adjacency windows outside the automatically sized hot prefix
use a separate bounded LRU shared by the Reader and its batch workers.
Concurrent misses for the same window are single-flighted: one worker performs
the positional read while the others wait and then borrow the immutable
payload. Successful reads move their existing Vec allocation into shared
ownership without copying the payload. Capacity is charged by actual retained
allocation capacity and clipped to both [...]
<p>DiskANN retains cloned storage handles as reusable search
sessions. Small batches (up to four queries per worker) run graph traversal and
persisted-vector rerank concurrently end to end, avoiding a serial
parent-rerank bottleneck; the interleaved layout always uses this path because
the graph read already contains the vector. Larger compact-layout batches keep
the object-store-friendly path: workers return node IDs, the parent unions
raw-vector windows, and rerank streams ch [...]
diff --git a/ffi/src/lib.rs b/ffi/src/lib.rs
index ba831fb..86223fd 100644
--- a/ffi/src/lib.rs
+++ b/ffi/src/lib.rs
@@ -54,6 +54,15 @@ pub const PAIMON_VINDEX_SEARCH_WIDTH_AUTO: u32 = 0;
pub const PAIMON_VINDEX_SEARCH_WIDTH_IVF_NPROBE: u32 = 1;
pub const PAIMON_VINDEX_SEARCH_WIDTH_DISKANN_L_SEARCH: u32 = 2;
+pub const PAIMON_VINDEX_SEARCH_STRATEGY_NOT_EXECUTED: u64 = 0;
+pub const PAIMON_VINDEX_SEARCH_STRATEGY_IVF: u64 = 1;
+pub const PAIMON_VINDEX_SEARCH_STRATEGY_DISKANN_GRAPH: u64 = 2;
+pub const PAIMON_VINDEX_SEARCH_STRATEGY_FILTERED_EXHAUSTIVE: u64 = 3;
+pub const PAIMON_VINDEX_SEARCH_STRATEGY_GRAPH_THEN_EXHAUSTIVE: u64 = 4;
+pub const PAIMON_VINDEX_SEARCH_STRATEGY_MIXED: u64 = 5;
+pub const PAIMON_VINDEX_SEARCH_FALLBACK_NONE: u64 = 0;
+pub const PAIMON_VINDEX_SEARCH_FALLBACK_INSUFFICIENT_RESULTS: u64 = 1;
+
pub const PAIMON_VINDEX_IVFPQ_BATCH_TABLE_REUSE_OFF: u32 = 0;
pub const PAIMON_VINDEX_IVFPQ_BATCH_TABLE_REUSE_ON: u32 = 1;
pub const PAIMON_VINDEX_IVFPQ_BATCH_TABLE_REUSE_AUTO: u32 = 2;
@@ -289,6 +298,29 @@ pub struct PaimonVindexSearchParamsV2 {
pub ivfpq_batch_table_reuse_max_bytes: usize,
}
+/// Per-call top-K statistics. Widths are batch maxima; counters sum all work.
+/// Strategy: 0 not executed, 1 IVF, 2 DiskANN graph, 3 filtered exhaustive,
+/// 4 graph then exhaustive, 5 mixed. Fallback: 0 none, 1 insufficient results.
+/// search_width: 0 not executed, 1 IVF nprobe, 2 DiskANN search-list size.
+/// Read bytes/ranges are requests to the adapter, including lazy
initialization.
+/// Candidates: IVF rows before filtering; DiskANN PQ evaluations.
+#[repr(C)]
+#[derive(Clone, Copy, Default)]
+pub struct PaimonVindexSearchStats {
+ pub query_count: u64,
+ pub search_width: u64,
+ pub initial_width: u64,
+ pub effective_width: u64,
+ pub candidate_count: u64,
+ pub strategy: u64,
+ pub fallback_reason: u64,
+ pub read_calls: u64,
+ pub read_ranges: u64,
+ pub read_bytes: u64,
+ pub cache_hits: u64,
+ pub cache_misses: u64,
+}
+
/// Extensible search parameters passed by pointer.
///
/// Callers must set `struct_size` to the exact end of the last initialized
@@ -973,6 +1005,50 @@ pub unsafe extern "C" fn paimon_vindex_reader_metadata(
})
}
+/// Copies the last top-K snapshot. Before any search, or after a failed core
+/// top-K call, all fields are zero. Other operations preserve the snapshot.
+/// `out_size` bounds the writable buffer. Only complete u64 fields in the
known
+/// prefix are written; unknown trailing bytes are untouched. This allows
future
+/// appended fields without changing the ABI. At least one u64 must fit.
+#[no_mangle]
+pub unsafe extern "C" fn paimon_vindex_reader_search_stats(
+ handle: *const PaimonVindexReaderHandle,
+ out: *mut PaimonVindexSearchStats,
+ out_size: usize,
+) -> c_int {
+ ffi_status(|| {
+ if out.is_null() || out_size < size_of::<u64>() {
+ return Err("statistics buffer is null or too small".to_string());
+ }
+ let handle = unsafe { reader_ref(handle) }?;
+ let stats = handle.inner.search_stats();
+ let raw = PaimonVindexSearchStats {
+ query_count: stats.query_count,
+ search_width: stats.search_width,
+ initial_width: stats.initial_width,
+ effective_width: stats.effective_width,
+ candidate_count: stats.candidate_count,
+ strategy: stats.strategy as u64,
+ fallback_reason: stats.fallback_reason as u64,
+ read_calls: stats.read_calls,
+ read_ranges: stats.read_ranges,
+ read_bytes: stats.read_bytes,
+ cache_hits: stats.cache_hits,
+ cache_misses: stats.cache_misses,
+ };
+ let bytes = out_size.min(size_of::<PaimonVindexSearchStats>()) /
size_of::<u64>()
+ * size_of::<u64>();
+ unsafe {
+ ptr::copy_nonoverlapping(
+ (&raw as *const PaimonVindexSearchStats).cast::<u8>(),
+ out.cast::<u8>(),
+ bytes,
+ )
+ };
+ Ok(())
+ })
+}
+
#[no_mangle]
pub unsafe extern "C" fn paimon_vindex_reader_read_plan(
handle: *const PaimonVindexReaderHandle,
diff --git a/include/paimon_vindex.hpp b/include/paimon_vindex.hpp
index 6fedbe5..b997ac1 100644
--- a/include/paimon_vindex.hpp
+++ b/include/paimon_vindex.hpp
@@ -316,6 +316,8 @@ inline RangeSearchResult
copy_range_result(PaimonVindexRangeSearchResult* raw, i
}
+using SearchStats = PaimonVindexSearchStats;
+
struct SearchParams {
size_t top_k = 0;
uint32_t search_width = PAIMON_VINDEX_SEARCH_WIDTH_AUTO;
@@ -659,6 +661,13 @@ public:
return l_search;
}
+ SearchStats search_stats() const {
+ std::lock_guard<detail::NativeHandleMutex> lock(native_handle_mutex_);
+ SearchStats stats{};
+ check(paimon_vindex_reader_search_stats(require_open(), &stats,
sizeof(stats)));
+ return stats;
+ }
+
ReadPlan read_plan() const {
std::lock_guard<detail::NativeHandleMutex> lock(native_handle_mutex_);
PaimonVindexReadPlan raw;
diff --git
a/java/src/main/java/org/apache/paimon/index/vector/VectorIndexNative.java
b/java/src/main/java/org/apache/paimon/index/vector/VectorIndexNative.java
index ceffd29..2f6d6e8 100644
--- a/java/src/main/java/org/apache/paimon/index/vector/VectorIndexNative.java
+++ b/java/src/main/java/org/apache/paimon/index/vector/VectorIndexNative.java
@@ -61,6 +61,8 @@ final class VectorIndexNative {
static native VectorIndexReadPlan readPlan(long ptr);
+ static native long[] searchStats(long ptr);
+
static native VectorSearchResult search(long ptr, float[] query,
VectorSearchParams params);
static native VectorSearchResult searchWithRoaringFilter(
diff --git
a/java/src/main/java/org/apache/paimon/index/vector/VectorIndexReader.java
b/java/src/main/java/org/apache/paimon/index/vector/VectorIndexReader.java
index d7ba6c6..e94904a 100644
--- a/java/src/main/java/org/apache/paimon/index/vector/VectorIndexReader.java
+++ b/java/src/main/java/org/apache/paimon/index/vector/VectorIndexReader.java
@@ -77,6 +77,18 @@ public final class VectorIndexReader implements
AutoCloseable {
return metadata().totalVectors();
}
+ public VectorSearchStats searchStats() {
+ rejectCallbackReentry();
+ synchronized (nativeHandleLock) {
+ enterNativeHandle();
+ try {
+ return new
VectorSearchStats(VectorIndexNative.searchStats(requireOpen()));
+ } finally {
+ exitNativeHandle();
+ }
+ }
+ }
+
public void optimizeForSearch() {
rejectCallbackReentry();
synchronized (nativeHandleLock) {
diff --git
a/java/src/main/java/org/apache/paimon/index/vector/VectorSearchStats.java
b/java/src/main/java/org/apache/paimon/index/vector/VectorSearchStats.java
new file mode 100644
index 0000000..7c5ab79
--- /dev/null
+++ b/java/src/main/java/org/apache/paimon/index/vector/VectorSearchStats.java
@@ -0,0 +1,92 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.paimon.index.vector;
+
+/**
+ * Last top-K call. Batch counters sum all work; widths are maxima. IVF
candidates
+ * are rows before filtering; DiskANN candidates are PQ evaluations. Reads
count
+ * adapter requests, including lazy initialization. Cache units are IVF payload
+ * entries or DiskANN adjacency/raw windows. Other operations preserve the
snapshot.
+ */
+public final class VectorSearchStats {
+ public enum Strategy {
+ NOT_EXECUTED, IVF, DISKANN_GRAPH, FILTERED_EXHAUSTIVE,
GRAPH_THEN_EXHAUSTIVE, MIXED
+ }
+
+ public enum FallbackReason {
+ NONE, INSUFFICIENT_RESULTS
+ }
+
+ private final long[] values;
+
+ VectorSearchStats(long[] values) {
+ if (values.length != 12) {
+ throw new IllegalArgumentException("invalid search statistics
length");
+ }
+ this.values = values.clone();
+ }
+
+ public long queryCount() {
+ return values[0];
+ }
+
+ /** Width kind: 0 before a call, 1 for IVF nprobe, 2 for DiskANN
search-list size. */
+ public long searchWidth() {
+ return values[1];
+ }
+
+ public long initialWidth() {
+ return values[2];
+ }
+
+ public long effectiveWidth() {
+ return values[3];
+ }
+
+ public long candidateCount() {
+ return values[4];
+ }
+
+ public Strategy strategy() {
+ return Strategy.values()[(int) values[5]];
+ }
+
+ public FallbackReason fallbackReason() {
+ return FallbackReason.values()[(int) values[6]];
+ }
+
+ public long readCalls() {
+ return values[7];
+ }
+
+ public long readRanges() {
+ return values[8];
+ }
+
+ public long readBytes() {
+ return values[9];
+ }
+
+ public long cacheHits() {
+ return values[10];
+ }
+
+ public long cacheMisses() {
+ return values[11];
+ }
+}
diff --git
a/java/src/test/java/org/apache/paimon/index/vector/VectorIndexRangeSearchTest.java
b/java/src/test/java/org/apache/paimon/index/vector/VectorIndexRangeSearchTest.java
index b4fbf66..784e137 100644
---
a/java/src/test/java/org/apache/paimon/index/vector/VectorIndexRangeSearchTest.java
+++
b/java/src/test/java/org/apache/paimon/index/vector/VectorIndexRangeSearchTest.java
@@ -523,6 +523,34 @@ public class VectorIndexRangeSearchTest {
VectorRangeSearchParams all = params(metric, null, null);
try (VectorIndexReader reader = open(build(indexType, metric, 8,
data))) {
check(reader.supportsRangeSearch(), indexType + " " + metric + "
support");
+ check(reader.searchStats().queryCount() == 0, "initial top-K
stats");
+ VectorSearchParams topK =
VectorSearchParams.automatic(3).withMaxInitialFilterExpansionFactor(1);
+ for (boolean filteredTopK : new boolean[] {false, true}) {
+ for (boolean batchTopK : new boolean[] {false, true}) {
+ byte[] bitmap = filteredTopK ? filter() : null;
+ if (batchTopK) {
+ if (bitmap == null) { reader.searchBatch(queries, 2,
topK); }
+ else { reader.searchBatch(queries, 2, topK, bitmap); }
+ } else {
+ float[] query = Arrays.copyOf(queries, 8);
+ if (bitmap == null) { reader.search(query, topK); }
+ else { reader.search(query, topK, bitmap); }
+ }
+ VectorSearchStats stats = reader.searchStats();
+ check(stats.queryCount() == (batchTopK ? 2 : 1), "top-K
query count");
+ check(stats.strategy() == VectorSearchStats.Strategy.IVF,
"top-K strategy");
+ check(stats.initialWidth() == 2 && stats.effectiveWidth()
== 2, "top-K width");
+ check(stats.candidateCount() == VECTOR_COUNT * (batchTopK
? 2 : 1), "top-K candidates");
+ check(stats.readRanges() >= stats.readCalls(), "top-K
reads");
+ reader.rangeSearchBatch(queries, 2, all);
+ check(reader.searchStats().candidateCount() ==
stats.candidateCount(), "range preserves top-K stats");
+ }
+ }
+ VectorSearchResult shortResult = reader.search(
+ Arrays.copyOf(queries, 8), VectorSearchParams.ivf(5, 2),
filter());
+ check(shortResult.size() == 5, "short top-K results retain K
slots");
+ check(shortResult.ids()[4] == -1 && shortResult.distances()[4] ==
Float.MAX_VALUE,
+ "short top-K padding");
VectorRangeSearchResult full = reader.rangeSearchBatch(queries, 2,
all);
assertShape(full, 2);
check(full.labels().length == VECTOR_COUNT * 2, "unbounded
includes every row");
@@ -869,6 +897,18 @@ public class VectorIndexRangeSearchTest {
data[offset] = (offset * 17 % 67) / 16.0f;
}
try (VectorIndexReader reader = open(build("diskann", "l2", 8, data)))
{
+ VectorSearchParams topK = VectorSearchParams.diskAnn(2, 32);
+ reader.searchBatch(Arrays.copyOf(data, 16), 2, topK);
+ VectorSearchStats stats = reader.searchStats();
+ check(stats.queryCount() == 2, "DiskANN top-K batch count");
+ check(stats.strategy() ==
VectorSearchStats.Strategy.DISKANN_GRAPH, "DiskANN graph strategy");
+ check(stats.effectiveWidth() == 32, "DiskANN actual width");
+ check(stats.candidateCount() >= 4, "DiskANN candidates");
+ reader.search(Arrays.copyOf(data, 8), topK, filter());
+ stats = reader.searchStats();
+ check(stats.queryCount() == 1, "DiskANN filtered count");
+ check(stats.strategy() ==
VectorSearchStats.Strategy.FILTERED_EXHAUSTIVE, "DiskANN exhaustive strategy");
+ check(stats.effectiveWidth() == 0, "exhaustive has no graph
width");
check(!reader.supportsRangeSearch(), "DiskANN unsupported");
VectorRangeSearchParams empty = params("l2", 0.0f, 0.0f);
expectMessage(
diff --git a/jni/src/lib.rs b/jni/src/lib.rs
index ec047f8..a815579 100644
--- a/jni/src/lib.rs
+++ b/jni/src/lib.rs
@@ -895,6 +895,43 @@ pub extern "system" fn
Java_org_apache_paimon_index_vector_VectorIndexNative_cal
})
}
+#[no_mangle]
+pub extern "system" fn
Java_org_apache_paimon_index_vector_VectorIndexNative_searchStats(
+ env: JNIEnv,
+ _class: JClass,
+ ptr: jlong,
+) -> jobject {
+ jni_call(env, |env| {
+ let reader = match deref_reader(ptr) {
+ Some(reader) => reader,
+ None => return throw_and_return(env, "null native pointer (reader
already freed?)"),
+ };
+ let stats = reader.search_stats();
+ let values = [
+ stats.query_count as jlong,
+ stats.search_width as jlong,
+ stats.initial_width as jlong,
+ stats.effective_width as jlong,
+ stats.candidate_count as jlong,
+ stats.strategy as jlong,
+ stats.fallback_reason as jlong,
+ stats.read_calls as jlong,
+ stats.read_ranges as jlong,
+ stats.read_bytes as jlong,
+ stats.cache_hits as jlong,
+ stats.cache_misses as jlong,
+ ];
+ let array = match env.new_long_array(values.len() as i32) {
+ Ok(array) => array,
+ Err(error) => return throw_and_return(env, &error.to_string()),
+ };
+ if let Err(error) = env.set_long_array_region(&array, 0, &values) {
+ return throw_and_return(env, &error.to_string());
+ }
+ array.into_raw()
+ })
+}
+
#[no_mangle]
pub extern "system" fn
Java_org_apache_paimon_index_vector_VectorIndexNative_readPlan(
env: JNIEnv,
diff --git a/python/README.md b/python/README.md
index 461d3f8..00728dd 100644
--- a/python/README.md
+++ b/python/README.md
@@ -17,7 +17,39 @@
~ under the License.
-->
-# Python distance range search
+# Python vector search
+
+Top-K `search` and `search_batch` accept the same `SearchParams`, including an
+optional initial filter expansion cap for automatic IVF search:
+
+```python
+from paimon_vindex import SearchParams
+
+params = SearchParams.automatic(top_k=10,
max_initial_filter_expansion_factor=4)
+ids, distances = reader.search(query, params, filter_bytes=roaring_allowlist)
+stats = reader.search_stats()
+print(stats.initial_width, stats.effective_width, stats.candidate_count)
+print(stats.strategy, stats.fallback_reason, stats.read_calls,
stats.read_bytes)
+```
+
+The cap is a positive integer or `None` (uncapped). It applies to the initial
+filter-selectivity expansion; progressive search can exceed it when results are
+short. Explicit IVF/DiskANN widths reject the cap. Smaller caps may reduce
recall.
+The same parameters work with `search_batch(queries, params,
filter_bytes=...)`.
+
+`SearchStats` is an immutable snapshot of the last core top-K call. A batch
sums
+all queries and retries; widths are batch maxima. IVF candidates count list
rows
+before filtering, including repeated single-query work; DiskANN candidates
count
+PQ evaluations. `read_calls`, `read_ranges`, and `read_bytes` count requests
to the
+input adapter, including lazy loading and parallel workers. `cache_hits` and
+`cache_misses` count IVF-FLAT/SQ payload entries or DiskANN
adjacency/raw-vector
+windows; IVF-PQ/RQ report zero. A failed core top-K call clears the snapshot;
+range search, warmup, optimization and calibration preserve it. Read the
snapshot
+before another thread searches through the same reader. Older native libraries
+keep existing top-K behavior; unavailable cap/statistics features raise an
upgrade
+error when requested.
+
+## Distance range search
`VectorIndexReader.range_search` and `range_search_batch` add variable-length
results alongside the unchanged top-K `search` and `search_batch` APIs.
IVF-Flat,
diff --git a/python/paimon_vindex/__init__.py b/python/paimon_vindex/__init__.py
index e817349..f7b43f9 100644
--- a/python/paimon_vindex/__init__.py
+++ b/python/paimon_vindex/__init__.py
@@ -346,6 +346,43 @@ class VectorIndexReadPlan:
memory_budget_bytes: int
+class SearchStrategy(IntEnum):
+ NOT_EXECUTED = 0
+ IVF = 1
+ DISKANN_GRAPH = 2
+ FILTERED_EXHAUSTIVE = 3
+ GRAPH_THEN_EXHAUSTIVE = 4
+ MIXED = 5
+
+
+class SearchFallbackReason(IntEnum):
+ NONE = 0
+ INSUFFICIENT_RESULTS = 1
+
+
+@dataclass(frozen=True)
+class SearchStats:
+ """Last top-K call: batch counters sum all work; widths are maxima.
+
+ IVF candidates are list rows before filtering; DiskANN candidates are PQ
+ evaluations. Reads are adapter requests, including lazy initialization.
+ Cache units are payload entries (IVF) or adjacency/raw windows (DiskANN).
+ Range searches and warmup preserve this snapshot. Failed core calls clear
it.
+ """
+ query_count: int
+ search_width: SearchWidth
+ initial_width: int
+ effective_width: int
+ candidate_count: int
+ strategy: SearchStrategy
+ fallback_reason: SearchFallbackReason
+ read_calls: int
+ read_ranges: int
+ read_bytes: int
+ cache_hits: int
+ cache_misses: int
+
+
@dataclass(frozen=True)
class SearchParams:
top_k: int
@@ -358,6 +395,8 @@ class SearchParams:
_DEFAULT_IVFPQ_BATCH_TABLE_REUSE_MAX_BYTES
)
+ max_initial_filter_expansion_factor: Optional[int] = None
+
def __post_init__(self):
try:
search_width = SearchWidth(self.search_width)
@@ -384,6 +423,12 @@ class SearchParams:
"IVF-PQ batch table reuse max bytes",
allow_zero=False,
)
+ factor = self.max_initial_filter_expansion_factor
+ if factor is not None:
+ factor = _size_t(factor, "maximum initial filter expansion
factor", allow_zero=False)
+ if search_width != SearchWidth.AUTO:
+ raise ValueError("maximum initial filter expansion factor
requires automatic IVF search")
+ object.__setattr__(self, "max_initial_filter_expansion_factor", factor)
object.__setattr__(self, "top_k", top_k)
object.__setattr__(self, "search_width", search_width)
object.__setattr__(self, "width", width)
@@ -393,8 +438,8 @@ class SearchParams:
)
@classmethod
- def automatic(cls, top_k: int):
- return cls(top_k=top_k)
+ def automatic(cls, top_k: int, max_initial_filter_expansion_factor=None):
+ return cls(top_k=top_k,
max_initial_filter_expansion_factor=max_initial_filter_expansion_factor)
@classmethod
def ivf(
@@ -427,6 +472,25 @@ class SearchParams:
self.width,
)
+ def _native_args(self, batch):
+ if _ffi.HAS_SEARCH_PARAMS_EX:
+ return ctypes.byref(self.to_ffi_ex()), "_ex"
+ if self.max_initial_filter_expansion_factor is not None:
+ raise RuntimeError("automatic IVF filter expansion cap requires a
native-library upgrade")
+ return (self.to_ffi_v2(), "_v2") if batch else (self.to_ffi(), "")
+
+ def to_ffi_ex(self):
+ return _ffi.PaimonVindexSearchParamsEx(
+
_ffi.PaimonVindexSearchParamsEx.ivfpq_batch_table_reuse_max_bytes.offset
+ + ctypes.sizeof(ctypes.c_size_t),
+ self.top_k,
+ int(self.search_width),
+ self.width,
+ self.max_initial_filter_expansion_factor or 0,
+ int(self.ivfpq_batch_table_reuse),
+ self.ivfpq_batch_table_reuse_max_bytes,
+ )
+
def to_ffi_v2(self):
return _ffi.PaimonVindexSearchParamsV2(
self.top_k,
@@ -961,6 +1025,31 @@ class VectorIndexReader:
_check_error("metadata failed")
return _metadata_from_ffi(raw)
+ def search_stats(self):
+ if not _ffi.HAS_SEARCH_STATS:
+ raise RuntimeError("search statistics require a native-library
upgrade")
+ with self._native_handle_lock:
+ self._require_open()
+ raw = _ffi.PaimonVindexSearchStats()
+ if lib.paimon_vindex_reader_search_stats(
+ self._handle, ctypes.byref(raw), ctypes.sizeof(raw)
+ ) != 0:
+ _check_error("search_stats failed")
+ return SearchStats(
+ raw.query_count,
+ SearchWidth(raw.search_width),
+ raw.initial_width,
+ raw.effective_width,
+ raw.candidate_count,
+ SearchStrategy(raw.strategy),
+ SearchFallbackReason(raw.fallback_reason),
+ raw.read_calls,
+ raw.read_ranges,
+ raw.read_bytes,
+ raw.cache_hits,
+ raw.cache_misses,
+ )
+
def optimize_for_search(self):
with self._native_handle_lock:
self._require_open()
@@ -1115,14 +1204,14 @@ class VectorIndexReader:
f"query length {query.shape[0]} does not match index dimension
"
f"{self._metadata.dimension}"
)
- ffi_params = params.to_ffi()
+ ffi_params, suffix = params._native_args(batch=False)
ids = np.empty(params.top_k, dtype=np.int64)
distances = np.empty(params.top_k, dtype=np.float32)
with self._native_handle_lock:
self._require_open()
if filter_bytes is None:
- rc = lib.paimon_vindex_reader_search(
+ rc = getattr(lib, "paimon_vindex_reader_search" + suffix)(
self._handle,
query.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
ffi_params,
@@ -1132,7 +1221,7 @@ class VectorIndexReader:
)
else:
filter_buf, filter_len, _ = self._filter_args(filter_bytes)
- rc = lib.paimon_vindex_reader_search_with_roaring_filter(
+ rc = getattr(lib,
"paimon_vindex_reader_search_with_roaring_filter" + suffix)(
self._handle,
query.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
ffi_params,
@@ -1153,7 +1242,7 @@ class VectorIndexReader:
f"queries length {queries.size} does not match nq * dimension "
f"{queries.shape[0] * self._metadata.dimension}"
)
- ffi_params = params.to_ffi_v2()
+ ffi_params, suffix = params._native_args(batch=True)
result_len = queries.shape[0] * params.top_k
ids = np.empty((queries.shape[0], params.top_k), dtype=np.int64)
distances = np.empty((queries.shape[0], params.top_k),
dtype=np.float32)
@@ -1161,7 +1250,7 @@ class VectorIndexReader:
with self._native_handle_lock:
self._require_open()
if filter_bytes is None:
- rc = lib.paimon_vindex_reader_search_batch_v2(
+ rc = getattr(lib, "paimon_vindex_reader_search_batch" +
suffix)(
self._handle,
queries.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
queries.shape[0],
@@ -1172,7 +1261,7 @@ class VectorIndexReader:
)
else:
filter_buf, filter_len, _ = self._filter_args(filter_bytes)
- rc =
lib.paimon_vindex_reader_search_batch_with_roaring_filter_v2(
+ rc = getattr(lib,
"paimon_vindex_reader_search_batch_with_roaring_filter" + suffix)(
self._handle,
queries.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
queries.shape[0],
@@ -1220,6 +1309,10 @@ __all__ = [
"RangeSearchResult",
"RangeSearchStats",
"SearchParams",
+ "SearchStats",
+ "SearchStrategy",
+ "SearchFallbackReason",
+ "SearchWidth",
"VectorIndexMetadata",
"VectorIndexReadPlan",
"VectorIndexReader",
diff --git a/python/paimon_vindex/_ffi.py b/python/paimon_vindex/_ffi.py
index 83cd0d3..4e47ddc 100644
--- a/python/paimon_vindex/_ffi.py
+++ b/python/paimon_vindex/_ffi.py
@@ -157,6 +157,35 @@ class PaimonVindexSearchParamsV2(Structure):
]
+class PaimonVindexSearchParamsEx(Structure):
+ _fields_ = [
+ ("struct_size", c_size_t),
+ ("top_k", c_size_t),
+ ("search_width", c_uint32),
+ ("width", c_size_t),
+ ("max_initial_filter_expansion_factor", c_size_t),
+ ("ivfpq_batch_table_reuse", c_uint32),
+ ("ivfpq_batch_table_reuse_max_bytes", c_size_t),
+ ]
+
+
+class PaimonVindexSearchStats(Structure):
+ _fields_ = [
+ ("query_count", c_uint64),
+ ("search_width", c_uint64),
+ ("initial_width", c_uint64),
+ ("effective_width", c_uint64),
+ ("candidate_count", c_uint64),
+ ("strategy", c_uint64),
+ ("fallback_reason", c_uint64),
+ ("read_calls", c_uint64),
+ ("read_ranges", c_uint64),
+ ("read_bytes", c_uint64),
+ ("cache_hits", c_uint64),
+ ("cache_misses", c_uint64),
+ ]
+
+
class PaimonVindexRawDistanceBand(Structure):
_fields_ = [
("metric", c_uint32),
@@ -315,6 +344,42 @@ lib.paimon_vindex_reader_read_plan.argtypes = [
]
lib.paimon_vindex_reader_read_plan.restype = c_int
+try:
+ _search_stats_fn = lib.paimon_vindex_reader_search_stats
+except AttributeError:
+ HAS_SEARCH_STATS = False
+else:
+ HAS_SEARCH_STATS = True
+ _search_stats_fn.argtypes = [c_void_p, POINTER(PaimonVindexSearchStats),
c_size_t]
+ _search_stats_fn.restype = c_int
+
+HAS_SEARCH_PARAMS_EX = all(hasattr(lib, name) for name in (
+ "paimon_vindex_reader_search_ex",
+ "paimon_vindex_reader_search_with_roaring_filter_ex",
+ "paimon_vindex_reader_search_batch_ex",
+ "paimon_vindex_reader_search_batch_with_roaring_filter_ex",
+))
+if HAS_SEARCH_PARAMS_EX:
+ lib.paimon_vindex_reader_search_ex.argtypes = [
+ c_void_p, POINTER(c_float), POINTER(PaimonVindexSearchParamsEx),
POINTER(c_int64), POINTER(c_float), c_size_t,
+ ]
+ lib.paimon_vindex_reader_search_ex.restype = c_int
+
+ lib.paimon_vindex_reader_search_with_roaring_filter_ex.argtypes = [
+ c_void_p, POINTER(c_float), POINTER(PaimonVindexSearchParamsEx),
POINTER(c_uint8), c_size_t, POINTER(c_int64), POINTER(c_float), c_size_t,
+ ]
+ lib.paimon_vindex_reader_search_with_roaring_filter_ex.restype = c_int
+
+ lib.paimon_vindex_reader_search_batch_ex.argtypes = [
+ c_void_p, POINTER(c_float), c_size_t,
POINTER(PaimonVindexSearchParamsEx), POINTER(c_int64), POINTER(c_float),
c_size_t,
+ ]
+ lib.paimon_vindex_reader_search_batch_ex.restype = c_int
+
+ lib.paimon_vindex_reader_search_batch_with_roaring_filter_ex.argtypes = [
+ c_void_p, POINTER(c_float), c_size_t,
POINTER(PaimonVindexSearchParamsEx), POINTER(c_uint8), c_size_t,
POINTER(c_int64), POINTER(c_float), c_size_t,
+ ]
+ lib.paimon_vindex_reader_search_batch_with_roaring_filter_ex.restype =
c_int
+
lib.paimon_vindex_reader_search.argtypes = [
c_void_p,
POINTER(c_float),
diff --git a/python/tests/test_search_stats.py
b/python/tests/test_search_stats.py
new file mode 100644
index 0000000..7687537
--- /dev/null
+++ b/python/tests/test_search_stats.py
@@ -0,0 +1,212 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import ctypes
+import struct
+
+import numpy as np
+import pytest
+
+from paimon_vindex import SearchFallbackReason, SearchParams, SearchStrategy,
SearchWidth, VectorIndexReader
+from test_vindex import VectorIndexInput, build_index
+
+
+def allowlist(labels):
+ labels = sorted(labels)
+ return (struct.pack("<QI", 1, 0)
+ + struct.pack("<IIHHI", 12346, 1, 0, len(labels) - 1, 16)
+ + struct.pack(f"<{len(labels)}H", *labels))
+
+
+class CountingInput(VectorIndexInput):
+ def __init__(self, data):
+ super().__init__(data)
+ self.reads = [0, 0, 0]
+
+ def pread_many(self, ranges):
+ self.reads[0] += 1
+ self.reads[1] += len(ranges)
+ self.reads[2] += sum(length for _, length in ranges)
+ return super().pread_many(ranges)
+
+
[email protected]("family", ["ivf_flat", "ivf_sq", "ivf_pq", "ivf_rq",
"diskann"])
+def test_search_stats_match_single_batch_filter_and_io(family):
+ options = {"index.type": family, "dimension": "16", "metric": "l2"}
+ if family != "diskann":
+ options["nlist"] = "4"
+ data_bytes, data = build_index(options, 16)
+ source = CountingInput(data_bytes)
+ with VectorIndexReader(source) as reader:
+ assert reader.search_stats().query_count == 0
+ assert reader.search_stats().strategy == SearchStrategy.NOT_EXECUTED
+ params = SearchParams.diskann(3, 100) if family == "diskann" else
SearchParams.ivf(3, 4)
+ for filtered in (False, True):
+ for batch in (False, True):
+ source.reads[:] = [0, 0, 0]
+ search = reader.search_batch if batch else reader.search
+ results = search(data[:4] if batch else data[0], params,
+ filter_bytes=allowlist([0, 4, 8]) if filtered
else None)
+ stats = reader.search_stats()
+ count = 4 if batch else 1
+ assert stats.query_count == count
+ assert results[0].shape == ((4, 3) if batch else (3,))
+ assert [stats.read_calls, stats.read_ranges, stats.read_bytes]
== source.reads
+ assert stats.candidate_count >= count * 3
+ assert stats.fallback_reason == SearchFallbackReason.NONE
+ if family == "diskann":
+ assert stats.search_width == SearchWidth.DISKANN_L_SEARCH
+ assert stats.strategy ==
(SearchStrategy.FILTERED_EXHAUSTIVE if filtered
+ else
SearchStrategy.DISKANN_GRAPH)
+ assert stats.effective_width == (0 if filtered else 100)
+ else:
+ assert stats.strategy == SearchStrategy.IVF
+ assert stats.search_width == SearchWidth.IVF_NPROBE
+ assert stats.initial_width == stats.effective_width == 4
+ assert stats.candidate_count == len(data) * count
+ if family in ("ivf_flat", "ivf_sq") and batch:
+ assert stats.cache_hits > 0
+ reader.optimize_for_search()
+ assert reader.search_stats() == stats
+
+
[email protected]("batch", [False, True])
+def test_python_automatic_filter_expansion_cap_reaches_native_search(batch):
+ options = {"index.type": "ivf_flat", "dimension": "16", "nlist": "64",
"metric": "l2"}
+ data_bytes, data = build_index(options, 16)
+ with VectorIndexReader(VectorIndexInput(data_bytes)) as reader:
+ method = reader.search_batch if batch else reader.search
+ queries = data[[63, 63]] if batch else data[63]
+ method(queries, SearchParams.automatic(3))
+ baseline = reader.search_stats().initial_width
+ bitmap = allowlist(range(63, 512, 64))
+ method(queries, SearchParams.automatic(3), filter_bytes=bitmap)
+ uncapped = reader.search_stats().initial_width
+ params = SearchParams.automatic(3,
max_initial_filter_expansion_factor=1)
+ results = method(queries, params, filter_bytes=bitmap)
+ stats = reader.search_stats()
+ assert stats.initial_width == baseline < uncapped
+ assert stats.query_count == (2 if batch else 1)
+ assert np.all(np.isin(results[0], list(range(63, 512, 64))))
+ raw = params.to_ffi_ex()
+ assert raw.struct_size ==
(type(raw).ivfpq_batch_table_reuse_max_bytes.offset
+ + ctypes.sizeof(ctypes.c_size_t))
+ assert raw.max_initial_filter_expansion_factor == 1
+
+
[email protected]("factor", [0, -1, 1.5])
+def test_python_rejects_invalid_filter_expansion_factor(factor):
+ with pytest.raises((TypeError, ValueError)):
+ SearchParams.automatic(3, max_initial_filter_expansion_factor=factor)
+
+
+def test_python_rejects_cap_with_explicit_width():
+ with pytest.raises(ValueError, match="automatic IVF"):
+ SearchParams(3, SearchWidth.IVF_NPROBE, 4,
+ max_initial_filter_expansion_factor=1)
+
+
+def test_older_native_topk_remains_usable(monkeypatch):
+ from paimon_vindex import _ffi
+
+ options = {"index.type": "ivf_flat", "dimension": "16", "nlist": "4",
"metric": "l2"}
+ data_bytes, data = build_index(options, 16)
+ with VectorIndexReader(VectorIndexInput(data_bytes)) as reader:
+ params = SearchParams.ivf(3, 4)
+ expected = reader.search(data[0], params)
+ monkeypatch.setattr(_ffi, "HAS_SEARCH_PARAMS_EX", False)
+ for actual, reference in zip(reader.search(data[0], params), expected):
+ np.testing.assert_array_equal(actual, reference)
+ batch = reader.search_batch(data[:2], params)
+ np.testing.assert_array_equal(batch[0][0], expected[0])
+ with pytest.raises(RuntimeError, match="upgrade"):
+ reader.search(data[0], SearchParams.automatic(3, 1))
+ monkeypatch.setattr(_ffi, "HAS_SEARCH_STATS", False)
+ with pytest.raises(RuntimeError, match="upgrade"):
+ reader.search_stats()
+
+
[email protected]("family", ["ivf_flat", "ivf_sq", "ivf_pq", "ivf_rq"])
+def
test_capped_filtered_single_expands_and_batch_counts_only_new_lists(family):
+ options = {"index.type": family, "dimension": "16", "nlist": "64",
"metric": "l2"}
+ encoded, data = build_index(options, 16)
+ bitmap = allowlist(range(0, 512, 64))
+ params = SearchParams.automatic(8, max_initial_filter_expansion_factor=1)
+ with VectorIndexReader(VectorIndexInput(encoded)) as reader:
+ for row, expected_width, expected_candidates in [(0, 8, 64), (63, 64,
960)]:
+ labels, distances = reader.search(data[row], params,
filter_bytes=bitmap)
+ assert labels.shape == distances.shape == (8,)
+ np.testing.assert_array_equal(np.sort(labels), np.arange(0, 512,
64))
+ assert np.all(np.isfinite(distances))
+ stats = reader.search_stats()
+ assert stats.query_count == 1
+ assert stats.initial_width == 8
+ assert stats.effective_width == expected_width
+ assert stats.candidate_count == expected_candidates
+ assert stats.fallback_reason == (SearchFallbackReason.NONE if row
== 0
+ else
SearchFallbackReason.INSUFFICIENT_RESULTS)
+ for rows, expected_candidates in [([0, 63], 576), ([0] * 32 + [63],
2560)]:
+ labels, distances = reader.search_batch(data[rows], params,
filter_bytes=bitmap)
+ assert labels.shape == distances.shape == (len(rows), 8)
+ np.testing.assert_array_equal(np.sort(labels, axis=1),
+ np.tile(np.arange(0, 512, 64),
(len(rows), 1)))
+ stats = reader.search_stats()
+ assert stats.query_count == len(rows)
+ assert stats.initial_width == 8
+ assert stats.effective_width == 64
+ assert stats.candidate_count == expected_candidates
+ assert stats.fallback_reason ==
SearchFallbackReason.INSUFFICIENT_RESULTS
+
+
[email protected]("automatic", [False, True])
[email protected]("bitmap, expected_hits", [(b"\0" * 8, 0),
(allowlist([0]), 1)])
+def test_pq_single_pads_short_filtered_results_like_batch(automatic, bitmap,
expected_hits):
+ options = {"index.type": "ivf_pq", "dimension": "16", "nlist": "4",
"metric": "l2"}
+ encoded, data = build_index(options, 16)
+ params = SearchParams.automatic(3, 1) if automatic else
SearchParams.ivf(3, 4)
+ with VectorIndexReader(VectorIndexInput(encoded)) as reader:
+ labels, distances = reader.search(data[0], params, filter_bytes=bitmap)
+ batch_labels, batch_distances = reader.search_batch(data[:1], params,
filter_bytes=bitmap)
+ assert labels.shape == distances.shape == (3,)
+ np.testing.assert_array_equal(labels, batch_labels[0])
+ np.testing.assert_array_equal(distances, batch_distances[0])
+ assert np.count_nonzero(distances != np.finfo(np.float32).max) ==
expected_hits
+ np.testing.assert_array_equal(labels[expected_hits:], [-1] * (3 -
expected_hits))
+
+
+def test_pq_padding_keeps_real_negative_ids():
+ import io
+ from paimon_vindex import VectorIndexTrainer, VectorIndexWriter
+
+ options = {"index.type": "ivf_pq", "dimension": "16", "nlist": "4",
"metric": "l2"}
+ _, data = build_index(options, 16)
+ labels = np.arange(len(data), dtype=np.int64)
+ labels[:2] = [-1, -7]
+ output = io.BytesIO()
+ with VectorIndexTrainer.train(options, data) as training:
+ with VectorIndexWriter(training) as writer:
+ writer.add_vectors(labels, data)
+ writer.write(output)
+ params = SearchParams.ivf(len(data) + 3, 4)
+ with VectorIndexReader(VectorIndexInput(output.getvalue())) as reader:
+ single_labels, single_distances = reader.search(data[0], params)
+ batch_labels, batch_distances = reader.search_batch(data[:1], params)
+ np.testing.assert_array_equal(single_labels, batch_labels[0])
+ np.testing.assert_array_equal(single_distances, batch_distances[0])
+ valid = single_distances != np.finfo(np.float32).max
+ np.testing.assert_array_equal(np.sort(single_labels[valid]),
np.sort(labels))
+ np.testing.assert_array_equal(single_labels[~valid], [-1, -1, -1])