miomiocat commented on code in PR #137:
URL: 
https://github.com/apache/paimon-vector-index/pull/137#discussion_r4674985958


##########
core/src/ivfflat_io.rs:
##########
@@ -806,6 +949,7 @@ impl<R: SeekRead> IVFFlatIndexReader<R> {
             ));
         }
 
+        self.ensure_resident_lists()?;

Review Comment:
   Removed full-shard warmup in 298ac849. Probe selection now precedes list 
reads as it does on main. Cache misses use the existing bounded multi-range 
reads, so an unprobed list is outside the query's read path.



##########
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:
   The revised implementation retains the existing FIFO and populates norms on 
admission to `read_scan_lists`. All three search modes continue to share its 
entries and byte budget. Range search keeps its existing cosine input 
validation.



##########
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:
   Updated in 298ac849. Cached lists now go through the existing probe 
grouping, list-local heaps and ordered merge. A regression compares cached and 
uncached IDs and distances on two 32,768-row cosine lists at d=16 and k=2, with 
a tie at the cutoff.



##########
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:
   The full-shard cache tests containing those two allocations were removed 
along with that implementation. The replacement cutoff test uses a stack array. 
The updated core, tests and benchmark targets compiled locally.



##########
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:
   The separate resident entries were removed. Every cache lookup now goes 
through the FIFO's existing offset, count, ID-length and dimension checks, and 
a changed entry's norms are evicted with its payload.



-- 
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]

Reply via email to