JingsongLi commented on code in PR #137:
URL:
https://github.com/apache/paimon-vector-index/pull/137#discussion_r4665366371
##########
core/src/ivfflat_io.rs:
##########
@@ -817,10 +961,22 @@ impl<R: SeekRead> IVFFlatIndexReader<R> {
.observation
.record_ivf(&probe_indices, 0, &self.list_counts);
let mut heap = ReaderTopKHeap::new(k);
+ if let Some(lists) = &self.resident_lists {
Review Comment:
**[P1] Preserve Top-K tie behavior for resident lists**
This branch pushes every candidate into one heap and bypasses the existing
parallel list scans and ordered merge of list-local heaps. With two cosine
lists of 32,768 rows at 16 dimensions, `k=2`, and `nprobe=2`, the baseline
returned IDs `[32769, 1]` and this branch returned `[32769, 32768]`, with
distances `[0.0, 1.0]` in both runs. Please reuse the existing probe grouping
and heap merge for resident lists and cover a tie at the cutoff above the
parallel-scan threshold.
##########
core/src/ivfflat_io.rs:
##########
@@ -806,6 +949,7 @@ impl<R: SeekRead> IVFFlatIndexReader<R> {
));
}
+ self.ensure_resident_lists()?;
Review Comment:
**[P1] Keep unprobed lists off the query's required read path**
This call reads the entire shard one list at a time before selecting the
probes. With 128 nonempty lists and `nprobe=8`, the first query after metadata
initialization went from one `pread` call to 128. When the final, unprobed list
had a storage read error, the baseline returned results and this branch failed
the search. Please keep normal queries on the existing read path for the
selected probes and use bounded multi-range reads for any explicit full-shard
warmup.
##########
core/src/ivfflat_io.rs:
##########
@@ -512,6 +538,112 @@ impl<R: SeekRead> IVFFlatIndexReader<R> {
Ok(())
}
+ /// Enable optional resident lists using the existing Reader memory budget.
+ /// A direct IVF-FLAT Reader remains streaming unless explicitly
configured.
+ pub(crate) fn set_resident_memory_budget(&mut self, bytes: usize) {
+ self.resident_lists = None;
+ self.resident_cache_checked = false;
+ self.resident_memory_budget = bytes;
+ }
+
+ fn resident_size_bytes(&self) -> io::Result<usize> {
+ let overflow = || {
+ io::Error::new(
+ io::ErrorKind::InvalidData,
+ "IVF-FLAT resident size overflow",
+ )
+ };
+ let mut bytes = self
+ .quantizer_centroids
+ .capacity()
+ .checked_mul(size_of::<f32>())
+ .and_then(|n| n.checked_add(self.list_offsets.capacity() *
size_of::<i64>()))
+ .and_then(|n| n.checked_add(self.list_counts.capacity() *
size_of::<i32>()))
+ .and_then(|n| n.checked_add(self.list_id_bytes_lens.capacity() *
size_of::<i32>()))
+ .and_then(|n|
n.checked_add(self.nlist.checked_mul(size_of::<FlatListData>())?))
+ .ok_or_else(overflow)?;
+ for list_id in 0..self.nlist {
+ let rows = self.list_counts[list_id] as usize;
+ if rows == 0 {
+ continue;
+ }
+ let payload_len = self.list_payload_len(list_id)?;
+ let vector_start = 12 + self.list_id_bytes_lens[list_id] as usize;
+ let alignment = align_of::<f32>();
+ let padding = (alignment - vector_start % alignment) % alignment;
+ let storage_bytes = payload_len
+ .checked_add(padding)
+ .and_then(|n| n.checked_add(size_of::<f32>() - 1))
+ .map(|n| n / size_of::<f32>() * size_of::<f32>())
+ .ok_or_else(overflow)?;
+ let decoded_ids =
rows.checked_mul(size_of::<i64>()).ok_or_else(overflow)?;
+ bytes = bytes
+ .checked_add(storage_bytes)
+ .and_then(|n| n.checked_add(decoded_ids))
+ .ok_or_else(overflow)?;
+ if self.metric == MetricType::Cosine {
+ bytes = bytes
+
.checked_add(rows.checked_mul(size_of::<f32>()).ok_or_else(overflow)?)
+ .ok_or_else(overflow)?;
+ }
+ #[cfg(target_endian = "big")]
+ {
+ let decoded_vectors = rows
+ .checked_mul(self.d)
+ .and_then(|n| n.checked_mul(size_of::<f32>()))
+ .ok_or_else(overflow)?;
+ bytes =
bytes.checked_add(decoded_vectors).ok_or_else(overflow)?;
+ }
+ }
+ Ok(bytes)
+ }
+
+ fn ensure_resident_lists(&mut self) -> io::Result<()> {
+ if self.resident_cache_checked {
+ return Ok(());
+ }
+ self.ensure_loaded()?;
+ // Admit the whole immutable index or keep the streaming path. This
+ // avoids query-dependent partial caches and their eviction churn.
+ if self.resident_memory_budget == 0
+ || self.resident_size_bytes()? > self.resident_memory_budget
+ {
+ self.resident_cache_checked = true;
+ return Ok(());
+ }
+ // Preserve the bounded streaming path for a pathological large list.
+ for list_id in 0..self.nlist {
+ if ivf_payload_is_oversized(self.list_payload_len(list_id)?) {
+ self.resident_cache_checked = true;
+ return Ok(());
+ }
+ }
+ // The full resident and partition cache share one reader budget.
+ // Release any previously cached partitions before retaining the shard.
+ self.list_cache = None;
Review Comment:
**[P2] Share cached lists with batch and range search**
Dropping the FIFO here leaves `read_scan_lists` without a cache for batch
Top-K and range search. After a single query warmed the same reader, the
baseline served both operations with zero list reads, while this branch reread
eight lists on every call in the same test. Please serve resident entries
through `read_scan_lists` so all three search paths can share the cached
payloads and cache accounting.
##########
core/src/ivfflat_io.rs:
##########
@@ -2103,6 +2414,149 @@ mod tests {
}
}
+ #[test]
+ fn resident_lists_match_streaming_scores_and_filters_without_repeated_io()
{
+ for d in [7, 768] {
+ for metric in [MetricType::L2, MetricType::InnerProduct,
MetricType::Cosine] {
+ let mut index = balanced_flat_index(d, 4, 9);
+ index.metric = metric;
+ // Include a zero vector and an empty list; keep unaligned
delta IDs.
+ index.vectors[0][..d].fill(0.0);
+ index.ids[3].clear();
+ index.vectors[3].clear();
+ let data = serialized_flat_index(&index);
+ let calls = Arc::new(AtomicUsize::new(0));
+ let mut resident = IVFFlatIndexReader::open(CountingReader {
+ inner: Cursor::new(data.clone()),
+ calls: calls.clone(),
+ })
+ .unwrap();
+ resident.set_resident_memory_budget(1024 * 1024);
+ let mut streaming =
IVFFlatIndexReader::open(Cursor::new(data)).unwrap();
+ let filter = RoaringTreemap::from_iter([0, 2, 5, 11, 19, 21]);
+ for nprobe in [1, 4] {
+ for query in [vec![0.0; d], vec![1.3; d], vec![20.1; d]] {
+ let expected = streaming.search(&query, 8,
nprobe).unwrap();
+ assert_eq!(resident.search(&query, 8,
nprobe).unwrap(), expected);
+ assert!(resident.resident_lists.is_some());
+ let warm_calls = calls.load(Ordering::Relaxed);
+ assert_eq!(resident.search(&query, 8,
nprobe).unwrap(), expected);
+ assert_eq!(calls.load(Ordering::Relaxed), warm_calls);
+ let mut filter_bytes = Vec::new();
+ filter.serialize_into(&mut filter_bytes).unwrap();
+ let expected = streaming
+ .search_with_roaring_filter(&query, 8, nprobe,
&filter_bytes)
+ .unwrap();
+ assert_eq!(
+ resident
+ .search_with_roaring_filter(&query, 8, nprobe,
&filter_bytes)
+ .unwrap(),
+ expected
+ );
+ assert_eq!(calls.load(Ordering::Relaxed), warm_calls);
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn resident_batch4_preserves_topk_ties_row_tails_and_zero_queries() {
+ for d in [1, 7, 8, 9, 768, 769] {
+ for rows in 1..10 {
+ let mut index = balanced_flat_index(d, 3, rows);
+ index.metric = MetricType::Cosine;
+ for vectors in &mut index.vectors {
+ if rows > 2 {
+ let duplicate = vectors[..d].to_vec();
+ vectors[d..2 * d].copy_from_slice(&duplicate);
+ }
+ }
+ let data = serialized_flat_index(&index);
+ let mut resident =
IVFFlatIndexReader::open(Cursor::new(data.clone())).unwrap();
+ resident.set_resident_memory_budget(8 * 1024 * 1024);
+ let mut streaming =
IVFFlatIndexReader::open(Cursor::new(data)).unwrap();
+ for query in [
+ vec![0.0; d],
+ vec![1.1; d],
+ (0..d).map(|i| (i % 17) as f32 - 8.0).collect(),
+ ] {
+ for k in [1, 4, 10, 100] {
+ let expected = streaming.search(&query, k, 3).unwrap();
+ let actual = resident.search(&query, k, 3).unwrap();
+ assert_eq!(actual.0, expected.0, "IDs d={d}
rows={rows} k={k}");
+ assert_eq!(
+ actual.1.iter().map(|v|
v.to_bits()).collect::<Vec<_>>(),
+ expected.1.iter().map(|v|
v.to_bits()).collect::<Vec<_>>()
+ );
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn resident_lists_respect_exact_budget_and_stream_when_too_small() {
+ for metric in [MetricType::L2, MetricType::Cosine] {
+ let mut index = balanced_flat_index(7, 4, 9);
+ index.metric = metric;
+ let data = serialized_flat_index(&index);
+ let mut sample =
IVFFlatIndexReader::open(Cursor::new(data.clone())).unwrap();
+ sample.ensure_loaded().unwrap();
+ let required = sample.resident_size_bytes().unwrap();
+ for (budget, should_cache) in [(0, false), (required - 1, false),
(required, true)] {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let mut reader = IVFFlatIndexReader::open(CountingReader {
+ inner: Cursor::new(data.clone()),
+ calls: calls.clone(),
+ })
+ .unwrap();
+ reader.set_resident_memory_budget(budget);
+ let query = vec![1.0; 7];
+ let result = reader.search(&query, 5, 4).unwrap();
+ let before = calls.load(Ordering::Relaxed);
+ assert_eq!(reader.search(&query, 5, 4).unwrap(), result);
+ assert_eq!(reader.resident_lists.is_some(), should_cache);
+ assert_eq!(calls.load(Ordering::Relaxed) == before,
should_cache);
+ if let Some(lists) = &reader.resident_lists {
+ let allocated = reader.quantizer_centroids.capacity() * 4
+ + reader.list_offsets.capacity() * 8
+ + reader.list_counts.capacity() * 4
+ + reader.list_id_bytes_lens.capacity() * 4
+ + lists.capacity() * size_of::<FlatListData>()
+ + lists
+ .iter()
+ .map(|l| {
+ l.ids.capacity() * 8
+ + l.vector_norms.as_ref().map_or(0, |v|
v.capacity() * 4)
+ + l.payload.storage.capacity() * 4
+ + l.payload
+ .decoded_vectors
+ .as_ref()
+ .map_or(0, |v| v.capacity() * 4)
+ })
+ .sum::<usize>();
+ assert!(
+ allocated <= budget,
+ "allocated={allocated}, budget={budget}"
+ );
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn resident_lists_do_not_publish_partial_cache_after_read_failure() {
+ let mut data = serialized_flat_index(&balanced_flat_index(7, 4, 9));
+ data.truncate(data.len() - 1);
+ let mut reader = IVFFlatIndexReader::open(Cursor::new(data)).unwrap();
+ reader.set_resident_memory_budget(1024 * 1024);
+ assert!(reader.search(&vec![1.0; 7], 5, 4).is_err());
Review Comment:
**[P2] Pass the CI Clippy check**
Both uses of `&vec![1.0; 7]` in this test trigger `clippy::useless_vec`
under `-D warnings`. Please use `&[1.0; 7]` at both call sites.
##########
core/src/ivfflat_io.rs:
##########
@@ -817,10 +961,22 @@ impl<R: SeekRead> IVFFlatIndexReader<R> {
.observation
.record_ivf(&probe_indices, 0, &self.list_counts);
let mut heap = ReaderTopKHeap::new(k);
+ if let Some(lists) = &self.resident_lists {
+ for list_id in probe_indices {
+ scan_flat_list(&q, &lists[list_id], self.d, self.metric,
filter, &mut heap)?;
Review Comment:
**[P2] Validate resident entries against public reader metadata**
Rust callers can edit the public list metadata through
`VectorIndexReader::IvfFlat`. After warming the reader and redirecting
`list_offsets[0]` to another valid list of the same shape, the baseline
returned IDs from the new offset and this path returned stale IDs. Please
validate the offset, count, encoded ID length, and dimension before reusing a
resident list, as the FIFO does.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]