Skip to main content

hermes_core/segment/reader/
mod.rs

1//! Async segment reader with lazy loading
2
3pub(crate) mod bmp;
4pub(crate) mod loader;
5mod types;
6
7pub use bmp::BmpIndex;
8#[cfg(feature = "diagnostics")]
9pub use types::DimRawData;
10pub use types::{SparseIndex, VectorIndex, VectorSearchResult};
11
12/// Memory statistics for a single segment
13#[derive(Debug, Clone, Default)]
14pub struct SegmentMemoryStats {
15    /// Segment ID
16    pub segment_id: u128,
17    /// Number of documents in segment
18    pub num_docs: u32,
19    /// Term dictionary block cache bytes
20    pub term_dict_cache_bytes: usize,
21    /// Document store block cache bytes
22    pub store_cache_bytes: usize,
23    /// Sparse vector index bytes (in-memory posting lists)
24    pub sparse_index_bytes: usize,
25    /// Dense vector index bytes (cluster assignments, quantized codes)
26    pub dense_index_bytes: usize,
27    /// Bloom filter bytes
28    pub bloom_filter_bytes: usize,
29}
30
31impl SegmentMemoryStats {
32    /// Total estimated memory for this segment
33    pub fn total_bytes(&self) -> usize {
34        self.term_dict_cache_bytes
35            + self.store_cache_bytes
36            + self.sparse_index_bytes
37            + self.dense_index_bytes
38            + self.bloom_filter_bytes
39    }
40}
41
42use std::sync::Arc;
43
44use rustc_hash::FxHashMap;
45
46use super::vector_data::LazyFlatVectorData;
47use crate::directories::{Directory, FileHandle};
48use crate::dsl::{DenseVectorQuantization, Document, Field, Schema};
49use crate::structures::{
50    AsyncSSTableReader, BlockPostingList, CoarseCentroids, IVFPQIndex, IVFRaBitQIndex, PQCodebook,
51    RaBitQIndex, SSTableStats, TermInfo,
52};
53use crate::{DocId, Error, Result};
54
55use super::store::{AsyncStoreReader, RawStoreBlock};
56use super::types::{SegmentFiles, SegmentId, SegmentMeta};
57
58/// Combine per-ordinal (doc_id, ordinal, score) triples into VectorSearchResults,
59/// applying the multi-value combiner, sorting by score desc, and truncating to `limit`.
60///
61/// Fast path: when all ordinals are 0 (single-valued field), skips the HashMap
62/// grouping entirely and just sorts + truncates the raw results.
63pub(crate) fn combine_ordinal_results(
64    raw: impl IntoIterator<Item = (u32, u16, f32)>,
65    combiner: crate::query::MultiValueCombiner,
66    limit: usize,
67) -> Vec<VectorSearchResult> {
68    let collected: Vec<(u32, u16, f32)> = raw.into_iter().collect();
69
70    let num_raw = collected.len();
71    if log::log_enabled!(log::Level::Debug) {
72        let mut ids: Vec<u32> = collected.iter().map(|(d, _, _)| *d).collect();
73        ids.sort_unstable();
74        ids.dedup();
75        log::debug!(
76            "combine_ordinal_results: {} raw entries, {} unique docs, combiner={:?}, limit={}",
77            num_raw,
78            ids.len(),
79            combiner,
80            limit
81        );
82    }
83
84    // Fast path: all ordinals are 0 → no grouping needed, skip HashMap
85    let all_single = collected.iter().all(|&(_, ord, _)| ord == 0);
86    if all_single {
87        let mut results: Vec<VectorSearchResult> = collected
88            .into_iter()
89            .map(|(doc_id, _, score)| VectorSearchResult::new(doc_id, score, vec![(0, score)]))
90            .collect();
91        results.sort_unstable_by(|a, b| {
92            b.score
93                .partial_cmp(&a.score)
94                .unwrap_or(std::cmp::Ordering::Equal)
95        });
96        results.truncate(limit);
97        return results;
98    }
99
100    // Slow path: multi-valued field — group by doc_id, apply combiner
101    let mut doc_ordinals: rustc_hash::FxHashMap<DocId, Vec<(u32, f32)>> =
102        rustc_hash::FxHashMap::default();
103    for (doc_id, ordinal, score) in collected {
104        doc_ordinals
105            .entry(doc_id as DocId)
106            .or_default()
107            .push((ordinal as u32, score));
108    }
109    let mut results: Vec<VectorSearchResult> = doc_ordinals
110        .into_iter()
111        .map(|(doc_id, ordinals)| {
112            let combined_score = combiner.combine(&ordinals);
113            VectorSearchResult::new(doc_id, combined_score, ordinals)
114        })
115        .collect();
116    results.sort_unstable_by(|a, b| {
117        b.score
118            .partial_cmp(&a.score)
119            .unwrap_or(std::cmp::Ordering::Equal)
120    });
121    results.truncate(limit);
122    results
123}
124
125/// Async segment reader with lazy loading
126///
127/// - Term dictionary: only index loaded, blocks loaded on-demand
128/// - Postings: loaded on-demand per term via HTTP range requests
129/// - Document store: only index loaded, blocks loaded on-demand via HTTP range requests
130pub struct SegmentReader {
131    meta: SegmentMeta,
132    /// Term dictionary with lazy block loading
133    term_dict: Arc<AsyncSSTableReader<TermInfo>>,
134    /// Postings file handle - fetches ranges on demand
135    postings_handle: FileHandle,
136    /// Document store with lazy block loading
137    store: Arc<AsyncStoreReader>,
138    schema: Arc<Schema>,
139    /// Dense vector indexes per field (RaBitQ or IVF-RaBitQ) — for search
140    vector_indexes: FxHashMap<u32, VectorIndex>,
141    /// Lazy flat vectors per field — for reranking and merge (doc_ids in memory, vectors via mmap)
142    flat_vectors: FxHashMap<u32, LazyFlatVectorData>,
143    /// Per-field coarse centroids for IVF/ScaNN search
144    coarse_centroids: FxHashMap<u32, Arc<CoarseCentroids>>,
145    /// Sparse vector indexes per field (MaxScore format)
146    sparse_indexes: FxHashMap<u32, SparseIndex>,
147    /// BMP sparse vector indexes per field (BMP format)
148    bmp_indexes: FxHashMap<u32, BmpIndex>,
149    /// Position file handle for phrase queries (lazy loading)
150    positions_handle: Option<FileHandle>,
151    /// Fast-field columnar readers per field_id
152    fast_fields: FxHashMap<u32, crate::structures::fast_field::FastFieldReader>,
153    /// Per-segment MaxScore threshold (f32 stored as AtomicU32 bits).
154    /// Allows per-field MaxScore groups within a single query to share thresholds:
155    /// field A's result seeds field B's pruning on the same segment.
156    shared_threshold: std::sync::atomic::AtomicU32,
157}
158
159impl SegmentReader {
160    /// Open a segment with lazy loading
161    pub async fn open<D: Directory>(
162        dir: &D,
163        segment_id: SegmentId,
164        schema: Arc<Schema>,
165        cache_blocks: usize,
166    ) -> Result<Self> {
167        let files = SegmentFiles::new(segment_id.0);
168
169        // Read metadata (small, always loaded)
170        let meta_slice = dir.open_read(&files.meta).await?;
171        let meta_bytes = meta_slice.read_bytes().await?;
172        let meta = SegmentMeta::deserialize(meta_bytes.as_slice())?;
173        debug_assert_eq!(meta.id, segment_id.0);
174
175        // Open term dictionary with lazy loading (fetches ranges on demand)
176        let term_dict_handle = dir.open_lazy(&files.term_dict).await?;
177        let term_dict = AsyncSSTableReader::open(term_dict_handle, cache_blocks).await?;
178
179        // Get postings file handle (lazy - fetches ranges on demand)
180        let postings_handle = dir.open_lazy(&files.postings).await?;
181
182        // Open store with lazy loading
183        let store_handle = dir.open_lazy(&files.store).await?;
184        let store = AsyncStoreReader::open(store_handle, cache_blocks).await?;
185
186        // Load dense vector indexes from unified .vectors file
187        let vectors_data = loader::load_vectors_file(dir, &files, &schema).await?;
188        let vector_indexes = vectors_data.indexes;
189        let flat_vectors = vectors_data.flat_vectors;
190
191        // Fields served by an ANN index only touch flat vectors for scattered
192        // rerank reads — disable readahead for them once at open. Flat-only
193        // fields keep default advice: brute-force scans them sequentially.
194        // Advice is sticky on the mapping, so per-query re-advising is wasted.
195        #[cfg(feature = "native")]
196        for (field_id, lazy_flat) in &flat_vectors {
197            if vector_indexes.contains_key(field_id) {
198                lazy_flat.advise_random_access();
199            }
200        }
201
202        // Load sparse vector indexes from .sparse file (MaxScore + BMP)
203        let sparse_data = loader::load_sparse_file(dir, &files, meta.num_docs, &schema).await?;
204        let sparse_indexes = sparse_data.maxscore_indexes;
205        let bmp_indexes = sparse_data.bmp_indexes;
206
207        // Open positions file handle (if exists) - offsets are now in TermInfo
208        let positions_handle = loader::open_positions_file(dir, &files, &schema).await?;
209
210        // Load fast-field columns from .fast file
211        let fast_fields = loader::load_fast_fields_file(dir, &files, &schema).await?;
212
213        // Log segment loading stats
214        {
215            let mut parts = vec![format!(
216                "[segment] loaded {:016x}: docs={}",
217                segment_id.0, meta.num_docs
218            )];
219            if !vector_indexes.is_empty() || !flat_vectors.is_empty() {
220                parts.push(format!(
221                    "dense: {} ann + {} flat fields",
222                    vector_indexes.len(),
223                    flat_vectors.len()
224                ));
225            }
226            for (field_id, idx) in &sparse_indexes {
227                parts.push(format!(
228                    "sparse field {}: {} dims, ~{:.1} KB",
229                    field_id,
230                    idx.num_dimensions(),
231                    idx.num_dimensions() as f64 * 24.0 / 1024.0
232                ));
233            }
234            for (field_id, idx) in &bmp_indexes {
235                parts.push(format!(
236                    "bmp field {}: {} dims, {} blocks",
237                    field_id,
238                    idx.dims(),
239                    idx.num_blocks
240                ));
241            }
242            if !fast_fields.is_empty() {
243                parts.push(format!("fast: {} fields", fast_fields.len()));
244            }
245            log::debug!("{}", parts.join(", "));
246        }
247
248        Ok(Self {
249            meta,
250            term_dict: Arc::new(term_dict),
251            postings_handle,
252            store: Arc::new(store),
253            schema,
254            vector_indexes,
255            flat_vectors,
256            coarse_centroids: FxHashMap::default(),
257            sparse_indexes,
258            bmp_indexes,
259            positions_handle,
260            fast_fields,
261            shared_threshold: std::sync::atomic::AtomicU32::new(0),
262        })
263    }
264
265    /// Reset the per-segment threshold (call before each new search).
266    #[inline]
267    pub fn reset_shared_threshold(&self) {
268        self.shared_threshold
269            .store(0, std::sync::atomic::Ordering::Relaxed);
270    }
271
272    /// Read the per-segment MaxScore threshold.
273    #[inline]
274    pub fn shared_threshold_f32(&self) -> f32 {
275        f32::from_bits(
276            self.shared_threshold
277                .load(std::sync::atomic::Ordering::Relaxed),
278        )
279    }
280
281    /// Update the threshold if new value is higher (monotonic max).
282    #[inline]
283    pub fn update_shared_threshold(&self, new_threshold: f32) {
284        use std::sync::atomic::Ordering::Relaxed;
285        let new_bits = new_threshold.to_bits();
286        let mut current_bits = self.shared_threshold.load(Relaxed);
287        while new_threshold > f32::from_bits(current_bits) {
288            match self.shared_threshold.compare_exchange_weak(
289                current_bits,
290                new_bits,
291                Relaxed,
292                Relaxed,
293            ) {
294                Ok(_) => return,
295                Err(actual) => current_bits = actual,
296            }
297        }
298    }
299
300    pub fn meta(&self) -> &SegmentMeta {
301        &self.meta
302    }
303
304    pub fn num_docs(&self) -> u32 {
305        self.meta.num_docs
306    }
307
308    /// Get average field length for BM25F scoring
309    pub fn avg_field_len(&self, field: Field) -> f32 {
310        self.meta.avg_field_len(field)
311    }
312
313    pub fn schema(&self) -> &Schema {
314        &self.schema
315    }
316
317    /// Get sparse indexes for all fields
318    pub fn sparse_indexes(&self) -> &FxHashMap<u32, SparseIndex> {
319        &self.sparse_indexes
320    }
321
322    /// Get sparse index for a specific field (MaxScore format)
323    pub fn sparse_index(&self, field: Field) -> Option<&SparseIndex> {
324        self.sparse_indexes.get(&field.0)
325    }
326
327    /// Get BMP index for a specific field
328    pub fn bmp_index(&self, field: Field) -> Option<&BmpIndex> {
329        self.bmp_indexes.get(&field.0)
330    }
331
332    /// Get all BMP indexes
333    pub fn bmp_indexes(&self) -> &FxHashMap<u32, BmpIndex> {
334        &self.bmp_indexes
335    }
336
337    /// Get vector indexes for all fields
338    pub fn vector_indexes(&self) -> &FxHashMap<u32, VectorIndex> {
339        &self.vector_indexes
340    }
341
342    /// Get lazy flat vectors for all fields (for reranking and merge)
343    pub fn flat_vectors(&self) -> &FxHashMap<u32, LazyFlatVectorData> {
344        &self.flat_vectors
345    }
346
347    /// Get a fast-field reader for a specific field.
348    pub fn fast_field(
349        &self,
350        field_id: u32,
351    ) -> Option<&crate::structures::fast_field::FastFieldReader> {
352        self.fast_fields.get(&field_id)
353    }
354
355    /// Get all fast-field readers.
356    pub fn fast_fields(&self) -> &FxHashMap<u32, crate::structures::fast_field::FastFieldReader> {
357        &self.fast_fields
358    }
359
360    /// Get term dictionary stats for debugging
361    pub fn term_dict_stats(&self) -> SSTableStats {
362        self.term_dict.stats()
363    }
364
365    /// Estimate memory usage of this segment reader
366    pub fn memory_stats(&self) -> SegmentMemoryStats {
367        let term_dict_stats = self.term_dict.stats();
368
369        // Term dict cache: num_blocks * avg_block_size (estimate 4KB per cached block)
370        let term_dict_cache_bytes = self.term_dict.cached_blocks() * 4096;
371
372        // Store cache: similar estimate
373        let store_cache_bytes = self.store.cached_blocks() * 4096;
374
375        // Sparse index: SoA dim table + OwnedBytes skip section + BMP grids
376        let sparse_index_bytes: usize = self
377            .sparse_indexes
378            .values()
379            .map(|s| s.estimated_memory_bytes())
380            .sum::<usize>()
381            + self
382                .bmp_indexes
383                .values()
384                .map(|b| b.estimated_memory_bytes())
385                .sum::<usize>();
386
387        // Dense index: vectors are memory-mapped, but we track index structures
388        // RaBitQ/IVF indexes have cluster assignments in memory
389        let dense_index_bytes: usize = self
390            .vector_indexes
391            .values()
392            .map(|v| v.estimated_memory_bytes())
393            .sum();
394
395        SegmentMemoryStats {
396            segment_id: self.meta.id,
397            num_docs: self.meta.num_docs,
398            term_dict_cache_bytes,
399            store_cache_bytes,
400            sparse_index_bytes,
401            dense_index_bytes,
402            bloom_filter_bytes: term_dict_stats.bloom_filter_size,
403        }
404    }
405
406    /// Get posting list for a term (async - loads on demand)
407    ///
408    /// For small posting lists (1-3 docs), the data is inlined in the term dictionary
409    /// and no additional I/O is needed. For larger lists, reads from .post file.
410    pub async fn get_postings(
411        &self,
412        field: Field,
413        term: &[u8],
414    ) -> Result<Option<BlockPostingList>> {
415        log::debug!(
416            "SegmentReader::get_postings field={} term_len={}",
417            field.0,
418            term.len()
419        );
420
421        // Build key: field_id + term
422        let mut key = Vec::with_capacity(4 + term.len());
423        key.extend_from_slice(&field.0.to_le_bytes());
424        key.extend_from_slice(term);
425
426        // Look up in term dictionary
427        let term_info = match self.term_dict.get(&key).await? {
428            Some(info) => {
429                log::debug!("SegmentReader::get_postings found term_info");
430                info
431            }
432            None => {
433                log::debug!("SegmentReader::get_postings term not found");
434                return Ok(None);
435            }
436        };
437
438        // Check if posting list is inlined
439        if let Some((doc_ids, term_freqs)) = term_info.decode_inline() {
440            // Build BlockPostingList from inline data (no I/O needed!)
441            let mut posting_list = crate::structures::PostingList::with_capacity(doc_ids.len());
442            for (doc_id, tf) in doc_ids.into_iter().zip(term_freqs.into_iter()) {
443                posting_list.push(doc_id, tf);
444            }
445            let block_list = BlockPostingList::from_posting_list(&posting_list)?;
446            return Ok(Some(block_list));
447        }
448
449        // External posting list - read from postings file handle (lazy - HTTP range request)
450        let (posting_offset, posting_len) = term_info.external_info().ok_or_else(|| {
451            Error::Corruption("TermInfo has neither inline nor external data".to_string())
452        })?;
453
454        let start = posting_offset;
455        let end = start + posting_len;
456
457        if end > self.postings_handle.len() {
458            return Err(Error::Corruption(
459                "Posting offset out of bounds".to_string(),
460            ));
461        }
462
463        let posting_bytes = self.postings_handle.read_bytes_range(start..end).await?;
464        let block_list = BlockPostingList::deserialize_zero_copy(posting_bytes)?;
465
466        Ok(Some(block_list))
467    }
468
469    /// Get all posting lists for terms that start with `prefix` in the given field.
470    pub async fn get_prefix_postings(
471        &self,
472        field: Field,
473        prefix: &[u8],
474    ) -> Result<Vec<BlockPostingList>> {
475        // Build composite key prefix: field_id ++ prefix
476        let mut key_prefix = Vec::with_capacity(4 + prefix.len());
477        key_prefix.extend_from_slice(&field.0.to_le_bytes());
478        key_prefix.extend_from_slice(prefix);
479
480        let entries = self.term_dict.prefix_scan(&key_prefix).await?;
481        let mut results = Vec::with_capacity(entries.len());
482
483        for (_key, term_info) in entries {
484            if let Some((doc_ids, term_freqs)) = term_info.decode_inline() {
485                let mut posting_list = crate::structures::PostingList::with_capacity(doc_ids.len());
486                for (doc_id, tf) in doc_ids.into_iter().zip(term_freqs.into_iter()) {
487                    posting_list.push(doc_id, tf);
488                }
489                results.push(BlockPostingList::from_posting_list(&posting_list)?);
490            } else if let Some((posting_offset, posting_len)) = term_info.external_info() {
491                let start = posting_offset;
492                let end = start + posting_len;
493                if end > self.postings_handle.len() {
494                    continue;
495                }
496                let posting_bytes = self.postings_handle.read_bytes_range(start..end).await?;
497                results.push(BlockPostingList::deserialize_zero_copy(posting_bytes)?);
498            }
499        }
500
501        Ok(results)
502    }
503
504    /// Get document by local doc_id (async - loads on demand).
505    ///
506    /// Dense vector fields are hydrated from LazyFlatVectorData (not stored in .store).
507    /// Uses binary search on sorted doc_ids for O(log N) lookup.
508    pub async fn doc(&self, local_doc_id: DocId) -> Result<Option<Document>> {
509        self.doc_with_fields(local_doc_id, None).await
510    }
511
512    /// Get document by local doc_id, hydrating only the specified fields.
513    ///
514    /// If `fields` is `None`, all fields (including dense vectors) are hydrated.
515    /// If `fields` is `Some(set)`, only dense vector fields in the set are hydrated,
516    /// skipping expensive mmap reads + dequantization for unrequested vector fields.
517    pub async fn doc_with_fields(
518        &self,
519        local_doc_id: DocId,
520        fields: Option<&rustc_hash::FxHashSet<u32>>,
521    ) -> Result<Option<Document>> {
522        let mut doc = match fields {
523            Some(set) => {
524                let field_ids: Vec<u32> = set.iter().copied().collect();
525                match self
526                    .store
527                    .get_fields(local_doc_id, &self.schema, &field_ids)
528                    .await
529                {
530                    Ok(Some(d)) => d,
531                    Ok(None) => return Ok(None),
532                    Err(e) => return Err(Error::from(e)),
533                }
534            }
535            None => match self.store.get(local_doc_id, &self.schema).await {
536                Ok(Some(d)) => d,
537                Ok(None) => return Ok(None),
538                Err(e) => return Err(Error::from(e)),
539            },
540        };
541
542        // Hydrate dense vector fields from flat vector data
543        for (&field_id, lazy_flat) in &self.flat_vectors {
544            // Skip vector fields not in the requested set
545            if let Some(set) = fields
546                && !set.contains(&field_id)
547            {
548                continue;
549            }
550
551            let is_binary = lazy_flat.quantization == DenseVectorQuantization::Binary;
552            let (start, entries) = lazy_flat.flat_indexes_for_doc(local_doc_id);
553            for (j, &(_doc_id, _ordinal)) in entries.iter().enumerate() {
554                let flat_idx = start + j;
555                if is_binary {
556                    let vbs = lazy_flat.vector_byte_size();
557                    let mut raw = vec![0u8; vbs];
558                    match lazy_flat.read_vector_raw_into(flat_idx, &mut raw).await {
559                        Ok(()) => {
560                            doc.add_binary_dense_vector(Field(field_id), raw);
561                        }
562                        Err(e) => {
563                            log::warn!("Failed to hydrate binary vector field {}: {}", field_id, e);
564                        }
565                    }
566                } else {
567                    match lazy_flat.get_vector(flat_idx).await {
568                        Ok(vec) => {
569                            doc.add_dense_vector(Field(field_id), vec);
570                        }
571                        Err(e) => {
572                            log::warn!("Failed to hydrate vector field {}: {}", field_id, e);
573                        }
574                    }
575                }
576            }
577        }
578
579        Ok(Some(doc))
580    }
581
582    /// Prefetch term dictionary blocks for a key range
583    pub async fn prefetch_terms(
584        &self,
585        field: Field,
586        start_term: &[u8],
587        end_term: &[u8],
588    ) -> Result<()> {
589        let mut start_key = Vec::with_capacity(4 + start_term.len());
590        start_key.extend_from_slice(&field.0.to_le_bytes());
591        start_key.extend_from_slice(start_term);
592
593        let mut end_key = Vec::with_capacity(4 + end_term.len());
594        end_key.extend_from_slice(&field.0.to_le_bytes());
595        end_key.extend_from_slice(end_term);
596
597        self.term_dict.prefetch_range(&start_key, &end_key).await?;
598        Ok(())
599    }
600
601    /// Check if store uses dictionary compression (incompatible with raw merging)
602    pub fn store_has_dict(&self) -> bool {
603        self.store.has_dict()
604    }
605
606    /// Get store reference for merge operations
607    pub fn store(&self) -> &super::store::AsyncStoreReader {
608        &self.store
609    }
610
611    /// Get raw store blocks for optimized merging
612    pub fn store_raw_blocks(&self) -> Vec<RawStoreBlock> {
613        self.store.raw_blocks()
614    }
615
616    /// Get store data slice for raw block access
617    pub fn store_data_slice(&self) -> &FileHandle {
618        self.store.data_slice()
619    }
620
621    /// Get all terms from this segment (for merge)
622    pub async fn all_terms(&self) -> Result<Vec<(Vec<u8>, TermInfo)>> {
623        self.term_dict.all_entries().await.map_err(Error::from)
624    }
625
626    /// Get all terms with parsed field and term string (for statistics aggregation)
627    ///
628    /// Returns (field, term_string, doc_freq) for each term in the dictionary.
629    /// Skips terms that aren't valid UTF-8.
630    pub async fn all_terms_with_stats(&self) -> Result<Vec<(Field, String, u32)>> {
631        let entries = self.term_dict.all_entries().await?;
632        let mut result = Vec::with_capacity(entries.len());
633
634        for (key, term_info) in entries {
635            // Key format: field_id (4 bytes little-endian) + term bytes
636            if key.len() > 4 {
637                let field_id = u32::from_le_bytes([key[0], key[1], key[2], key[3]]);
638                let term_bytes = &key[4..];
639                if let Ok(term_str) = std::str::from_utf8(term_bytes) {
640                    result.push((Field(field_id), term_str.to_string(), term_info.doc_freq()));
641                }
642            }
643        }
644
645        Ok(result)
646    }
647
648    /// Get streaming iterator over term dictionary (for memory-efficient merge)
649    pub fn term_dict_iter(&self) -> crate::structures::AsyncSSTableIterator<'_, TermInfo> {
650        self.term_dict.iter()
651    }
652
653    /// Prefetch all term dictionary blocks in a single bulk I/O call.
654    ///
655    /// Call before merge iteration to eliminate per-block cache misses.
656    pub async fn prefetch_term_dict(&self) -> crate::Result<()> {
657        self.term_dict
658            .prefetch_all_data_bulk()
659            .await
660            .map_err(crate::Error::from)
661    }
662
663    /// Read raw posting bytes at offset
664    pub async fn read_postings(&self, offset: u64, len: u64) -> Result<Vec<u8>> {
665        let start = offset;
666        let end = start + len;
667        let bytes = self.postings_handle.read_bytes_range(start..end).await?;
668        Ok(bytes.to_vec())
669    }
670
671    /// Read raw position bytes at offset (for merge)
672    pub async fn read_position_bytes(&self, offset: u64, len: u64) -> Result<Option<Vec<u8>>> {
673        let handle = match &self.positions_handle {
674            Some(h) => h,
675            None => return Ok(None),
676        };
677        let start = offset;
678        let end = start + len;
679        let bytes = handle.read_bytes_range(start..end).await?;
680        Ok(Some(bytes.to_vec()))
681    }
682
683    /// Check if this segment has a positions file
684    pub fn has_positions_file(&self) -> bool {
685        self.positions_handle.is_some()
686    }
687
688    /// Batch cosine scoring on raw quantized bytes.
689    ///
690    /// Dispatches to the appropriate SIMD scorer based on quantization type.
691    /// Vectors file uses data-first layout (offset 0) with 8-byte padding between
692    /// fields, so mmap slices are always properly aligned for f32/f16/u8 access.
693    fn score_quantized_batch(
694        query: &[f32],
695        raw: &[u8],
696        quant: crate::dsl::DenseVectorQuantization,
697        dim: usize,
698        scores: &mut [f32],
699        unit_norm: bool,
700    ) {
701        use crate::dsl::DenseVectorQuantization;
702        use crate::structures::simd;
703        match (quant, unit_norm) {
704            (DenseVectorQuantization::F32, false) => {
705                let num_floats = scores.len() * dim;
706                debug_assert!(
707                    (raw.as_ptr() as usize).is_multiple_of(std::mem::align_of::<f32>()),
708                    "f32 vector data not 4-byte aligned — vectors file may use legacy format"
709                );
710                let vectors: &[f32] =
711                    unsafe { std::slice::from_raw_parts(raw.as_ptr() as *const f32, num_floats) };
712                simd::batch_cosine_scores(query, vectors, dim, scores);
713            }
714            (DenseVectorQuantization::F32, true) => {
715                let num_floats = scores.len() * dim;
716                debug_assert!(
717                    (raw.as_ptr() as usize).is_multiple_of(std::mem::align_of::<f32>()),
718                    "f32 vector data not 4-byte aligned"
719                );
720                let vectors: &[f32] =
721                    unsafe { std::slice::from_raw_parts(raw.as_ptr() as *const f32, num_floats) };
722                simd::batch_dot_scores(query, vectors, dim, scores);
723            }
724            (DenseVectorQuantization::F16, false) => {
725                simd::batch_cosine_scores_f16(query, raw, dim, scores);
726            }
727            (DenseVectorQuantization::F16, true) => {
728                simd::batch_dot_scores_f16(query, raw, dim, scores);
729            }
730            (DenseVectorQuantization::UInt8, false) => {
731                simd::batch_cosine_scores_u8(query, raw, dim, scores);
732            }
733            (DenseVectorQuantization::UInt8, true) => {
734                simd::batch_dot_scores_u8(query, raw, dim, scores);
735            }
736            (DenseVectorQuantization::Binary, _) => {
737                // Binary vectors use search_binary_dense_vector(), not search_dense_vector()
738                unreachable!("Binary quantization should not reach score_quantized_batch");
739            }
740        }
741    }
742
743    /// Search dense vectors using RaBitQ
744    ///
745    /// Returns VectorSearchResult with ordinal tracking for multi-value fields.
746    /// Doc IDs are segment-local.
747    /// For multi-valued documents, scores are combined using the specified combiner.
748    pub async fn search_dense_vector(
749        &self,
750        field: Field,
751        query: &[f32],
752        k: usize,
753        nprobe: usize,
754        rerank_factor: f32,
755        combiner: crate::query::MultiValueCombiner,
756    ) -> Result<Vec<VectorSearchResult>> {
757        let ann_index = self.vector_indexes.get(&field.0);
758        let lazy_flat = self.flat_vectors.get(&field.0);
759
760        // No vectors at all for this field
761        if ann_index.is_none() && lazy_flat.is_none() {
762            return Ok(Vec::new());
763        }
764
765        // Check if vectors are pre-normalized (skip per-vector norm in scoring)
766        let unit_norm = self
767            .schema
768            .get_field_entry(field)
769            .and_then(|e| e.dense_vector_config.as_ref())
770            .is_some_and(|c| c.unit_norm);
771
772        /// Batch size for brute-force scoring (4096 vectors × 768 dims × 4 bytes ≈ 12MB)
773        const BRUTE_FORCE_BATCH: usize = 4096;
774
775        let fetch_k = (k as f32 * rerank_factor.max(1.0)).ceil() as usize;
776
777        // Results are (doc_id, ordinal, score) where score = similarity (higher = better)
778        let t0 = std::time::Instant::now();
779        let mut results: Vec<(u32, u16, f32)> = if let Some(index) = ann_index {
780            // ANN search (RaBitQ, IVF, ScaNN)
781            match index {
782                VectorIndex::RaBitQ(lazy) => {
783                    let rabitq = lazy.get().ok_or_else(|| {
784                        Error::Schema("RaBitQ index deserialization failed".to_string())
785                    })?;
786                    rabitq
787                        .search(query, fetch_k)
788                        .into_iter()
789                        .map(|(doc_id, ordinal, dist)| (doc_id, ordinal, 1.0 / (1.0 + dist)))
790                        .collect()
791                }
792                VectorIndex::IVF(lazy) => {
793                    let (index, codebook) = lazy.get().ok_or_else(|| {
794                        Error::Schema("IVF index deserialization failed".to_string())
795                    })?;
796                    let centroids = self.coarse_centroids.get(&field.0).ok_or_else(|| {
797                        Error::Schema(format!(
798                            "IVF index requires coarse centroids for field {}",
799                            field.0
800                        ))
801                    })?;
802                    let effective_nprobe = if nprobe > 0 { nprobe } else { 32 };
803                    index
804                        .search(centroids, codebook, query, fetch_k, Some(effective_nprobe))
805                        .into_iter()
806                        .map(|(doc_id, ordinal, dist)| (doc_id, ordinal, 1.0 / (1.0 + dist)))
807                        .collect()
808                }
809                VectorIndex::ScaNN(lazy) => {
810                    let (index, codebook) = lazy.get().ok_or_else(|| {
811                        Error::Schema("ScaNN index deserialization failed".to_string())
812                    })?;
813                    let centroids = self.coarse_centroids.get(&field.0).ok_or_else(|| {
814                        Error::Schema(format!(
815                            "ScaNN index requires coarse centroids for field {}",
816                            field.0
817                        ))
818                    })?;
819                    let effective_nprobe = if nprobe > 0 { nprobe } else { 32 };
820                    index
821                        .search(centroids, codebook, query, fetch_k, Some(effective_nprobe))
822                        .into_iter()
823                        .map(|(doc_id, ordinal, dist)| (doc_id, ordinal, 1.0 / (1.0 + dist)))
824                        .collect()
825                }
826            }
827        } else if let Some(lazy_flat) = lazy_flat {
828            // Batched brute-force from lazy flat vectors (native-precision SIMD scoring)
829            // Uses a top-k heap to avoid collecting and sorting all N candidates.
830            log::debug!(
831                "[search_dense] field {}: brute-force on {} vectors (dim={}, quant={:?})",
832                field.0,
833                lazy_flat.num_vectors,
834                lazy_flat.dim,
835                lazy_flat.quantization
836            );
837            let dim = lazy_flat.dim;
838            let n = lazy_flat.num_vectors;
839            let quant = lazy_flat.quantization;
840            let mut collector = crate::query::ScoreCollector::new(fetch_k);
841            let mut scores = vec![0f32; BRUTE_FORCE_BATCH];
842
843            for batch_start in (0..n).step_by(BRUTE_FORCE_BATCH) {
844                let batch_count = BRUTE_FORCE_BATCH.min(n - batch_start);
845                let batch_bytes = lazy_flat
846                    .read_vectors_batch(batch_start, batch_count)
847                    .await
848                    .map_err(crate::Error::Io)?;
849                let raw = batch_bytes.as_slice();
850
851                Self::score_quantized_batch(
852                    query,
853                    raw,
854                    quant,
855                    dim,
856                    &mut scores[..batch_count],
857                    unit_norm,
858                );
859
860                for (i, &score) in scores.iter().enumerate().take(batch_count) {
861                    let (doc_id, ordinal) = lazy_flat.get_doc_id(batch_start + i);
862                    collector.insert_with_ordinal(doc_id, score, ordinal);
863                }
864            }
865
866            collector
867                .into_sorted_results()
868                .into_iter()
869                .map(|(doc_id, score, ordinal)| (doc_id, ordinal, score))
870                .collect()
871        } else {
872            return Ok(Vec::new());
873        };
874        let l1_elapsed = t0.elapsed();
875        log::debug!(
876            "[search_dense] field {}: L1 returned {} candidates in {:.1}ms",
877            field.0,
878            results.len(),
879            l1_elapsed.as_secs_f64() * 1000.0
880        );
881
882        // Rerank ANN candidates using raw vectors from lazy flat (binary search lookup)
883        // Uses native-precision SIMD scoring on quantized bytes — no dequantization overhead.
884        if ann_index.is_some()
885            && !results.is_empty()
886            && let Some(lazy_flat) = lazy_flat
887        {
888            let t_rerank = std::time::Instant::now();
889            let dim = lazy_flat.dim;
890            let quant = lazy_flat.quantization;
891            let vbs = lazy_flat.vector_byte_size();
892
893            // Resolve flat indexes for each candidate via binary search
894            let mut resolved: Vec<(usize, usize)> = Vec::new(); // (result_idx, flat_idx)
895            for (ri, c) in results.iter().enumerate() {
896                let (start, entries) = lazy_flat.flat_indexes_for_doc(c.0);
897                for (j, &(_, ord)) in entries.iter().enumerate() {
898                    if ord == c.1 {
899                        resolved.push((ri, start + j));
900                        break;
901                    }
902                }
903            }
904
905            let t_resolve = t_rerank.elapsed();
906            if !resolved.is_empty() {
907                // Sort by flat_idx for sequential mmap access (better page locality)
908                resolved.sort_unstable_by_key(|&(_, flat_idx)| flat_idx);
909
910                // Under memory pressure the candidate pages are likely evicted;
911                // batch-prefetch them so page-ins overlap instead of serializing
912                // as one major fault per vector. (MADV_RANDOM for this region is
913                // set once at segment open.)
914                #[cfg(feature = "native")]
915                lazy_flat.prefetch_vectors(resolved.iter().map(|&(_, flat_idx)| flat_idx));
916
917                // Batch-read raw quantized bytes into contiguous buffer
918                let t_read = std::time::Instant::now();
919                let mut raw_buf = vec![0u8; resolved.len() * vbs];
920                for (buf_idx, &(_, flat_idx)) in resolved.iter().enumerate() {
921                    let _ = lazy_flat
922                        .read_vector_raw_into(
923                            flat_idx,
924                            &mut raw_buf[buf_idx * vbs..(buf_idx + 1) * vbs],
925                        )
926                        .await;
927                }
928
929                let read_elapsed = t_read.elapsed();
930
931                // Native-precision batch SIMD cosine scoring
932                let t_score = std::time::Instant::now();
933                let mut scores = vec![0f32; resolved.len()];
934                Self::score_quantized_batch(query, &raw_buf, quant, dim, &mut scores, unit_norm);
935                let score_elapsed = t_score.elapsed();
936
937                // Write scores back to results
938                for (buf_idx, &(ri, _)) in resolved.iter().enumerate() {
939                    results[ri].2 = scores[buf_idx];
940                }
941
942                log::debug!(
943                    "[search_dense] field {}: rerank {} vectors (dim={}, quant={:?}, {}B/vec): resolve={:.1}ms read={:.1}ms score={:.1}ms",
944                    field.0,
945                    resolved.len(),
946                    dim,
947                    quant,
948                    vbs,
949                    t_resolve.as_secs_f64() * 1000.0,
950                    read_elapsed.as_secs_f64() * 1000.0,
951                    score_elapsed.as_secs_f64() * 1000.0,
952                );
953            }
954
955            if results.len() > fetch_k {
956                results.select_nth_unstable_by(fetch_k, |a, b| b.2.total_cmp(&a.2));
957                results.truncate(fetch_k);
958            }
959            results.sort_unstable_by(|a, b| b.2.total_cmp(&a.2));
960            log::debug!(
961                "[search_dense] field {}: rerank total={:.1}ms",
962                field.0,
963                t_rerank.elapsed().as_secs_f64() * 1000.0
964            );
965        }
966
967        Ok(combine_ordinal_results(results, combiner, k))
968    }
969
970    /// Search binary dense vectors using brute-force Hamming distance.
971    ///
972    /// Always flat brute-force (no ANN). Returns VectorSearchResult with ordinal tracking.
973    pub async fn search_binary_dense_vector(
974        &self,
975        field: Field,
976        query: &[u8],
977        k: usize,
978        combiner: crate::query::MultiValueCombiner,
979    ) -> Result<Vec<VectorSearchResult>> {
980        let lazy_flat = match self.flat_vectors.get(&field.0) {
981            Some(f) => f,
982            None => return Ok(Vec::new()),
983        };
984
985        const BRUTE_FORCE_BATCH: usize = 8192; // Binary vectors are tiny, use larger batches
986
987        let dim_bits = lazy_flat.dim;
988        let byte_len = lazy_flat.vector_byte_size();
989        let n = lazy_flat.num_vectors;
990
991        if byte_len != query.len() {
992            return Err(Error::Schema(format!(
993                "Binary query vector byte length {} != field byte length {}",
994                query.len(),
995                byte_len
996            )));
997        }
998
999        let mut collector = crate::query::ScoreCollector::new(k);
1000        let mut scores = vec![0f32; BRUTE_FORCE_BATCH];
1001
1002        for batch_start in (0..n).step_by(BRUTE_FORCE_BATCH) {
1003            let batch_count = BRUTE_FORCE_BATCH.min(n - batch_start);
1004            let batch_bytes = lazy_flat
1005                .read_vectors_batch(batch_start, batch_count)
1006                .await
1007                .map_err(crate::Error::Io)?;
1008            let raw = batch_bytes.as_slice();
1009
1010            crate::structures::simd::batch_hamming_scores(
1011                query,
1012                raw,
1013                byte_len,
1014                dim_bits,
1015                &mut scores[..batch_count],
1016            );
1017
1018            let threshold = collector.threshold();
1019            for (i, &score) in scores.iter().enumerate().take(batch_count) {
1020                if score > threshold {
1021                    let (doc_id, ordinal) = lazy_flat.get_doc_id(batch_start + i);
1022                    collector.insert_with_ordinal(doc_id, score, ordinal);
1023                }
1024            }
1025        }
1026
1027        let results: Vec<(u32, u16, f32)> = collector
1028            .into_sorted_results()
1029            .into_iter()
1030            .map(|(doc_id, score, ordinal)| (doc_id, ordinal, score))
1031            .collect();
1032
1033        Ok(combine_ordinal_results(results, combiner, k))
1034    }
1035
1036    /// Check if this segment has dense vectors for the given field
1037    pub fn has_dense_vector_index(&self, field: Field) -> bool {
1038        self.vector_indexes.contains_key(&field.0) || self.flat_vectors.contains_key(&field.0)
1039    }
1040
1041    /// Get the dense vector index for a field (if available)
1042    pub fn get_dense_vector_index(&self, field: Field) -> Option<Arc<RaBitQIndex>> {
1043        match self.vector_indexes.get(&field.0) {
1044            Some(VectorIndex::RaBitQ(lazy)) => lazy.get().cloned(),
1045            _ => None,
1046        }
1047    }
1048
1049    /// Get the IVF vector index for a field (if available)
1050    pub fn get_ivf_vector_index(
1051        &self,
1052        field: Field,
1053    ) -> Option<(Arc<IVFRaBitQIndex>, Arc<crate::structures::RaBitQCodebook>)> {
1054        match self.vector_indexes.get(&field.0) {
1055            Some(VectorIndex::IVF(lazy)) => lazy.get().map(|(i, c)| (i.clone(), c.clone())),
1056            _ => None,
1057        }
1058    }
1059
1060    /// Get coarse centroids for a field
1061    pub fn coarse_centroids(&self, field_id: u32) -> Option<&Arc<CoarseCentroids>> {
1062        self.coarse_centroids.get(&field_id)
1063    }
1064
1065    /// Set per-field coarse centroids from index-level trained structures
1066    pub fn set_coarse_centroids(&mut self, centroids: FxHashMap<u32, Arc<CoarseCentroids>>) {
1067        self.coarse_centroids = centroids;
1068    }
1069
1070    /// Get the ScaNN vector index for a field (if available)
1071    pub fn get_scann_vector_index(
1072        &self,
1073        field: Field,
1074    ) -> Option<(Arc<IVFPQIndex>, Arc<PQCodebook>)> {
1075        match self.vector_indexes.get(&field.0) {
1076            Some(VectorIndex::ScaNN(lazy)) => lazy.get().map(|(i, c)| (i.clone(), c.clone())),
1077            _ => None,
1078        }
1079    }
1080
1081    /// Get the vector index type for a field
1082    pub fn get_vector_index(&self, field: Field) -> Option<&VectorIndex> {
1083        self.vector_indexes.get(&field.0)
1084    }
1085
1086    /// Get positions for a term (for phrase queries)
1087    ///
1088    /// Position offsets are now embedded in TermInfo, so we first look up
1089    /// the term to get its TermInfo, then use position_info() to get the offset.
1090    pub async fn get_positions(
1091        &self,
1092        field: Field,
1093        term: &[u8],
1094    ) -> Result<Option<crate::structures::PositionPostingList>> {
1095        // Get positions handle
1096        let handle = match &self.positions_handle {
1097            Some(h) => h,
1098            None => return Ok(None),
1099        };
1100
1101        // Build key: field_id + term
1102        let mut key = Vec::with_capacity(4 + term.len());
1103        key.extend_from_slice(&field.0.to_le_bytes());
1104        key.extend_from_slice(term);
1105
1106        // Look up term in dictionary to get TermInfo with position offset
1107        let term_info = match self.term_dict.get(&key).await? {
1108            Some(info) => info,
1109            None => return Ok(None),
1110        };
1111
1112        // Get position offset from TermInfo
1113        let (offset, length) = match term_info.position_info() {
1114            Some((o, l)) => (o, l),
1115            None => return Ok(None),
1116        };
1117
1118        // Read the position data
1119        let slice = handle.slice(offset..offset + length);
1120        let data = slice.read_bytes().await?;
1121
1122        // Deserialize
1123        let pos_list = crate::structures::PositionPostingList::deserialize(data.as_slice())?;
1124
1125        Ok(Some(pos_list))
1126    }
1127
1128    /// Check if positions are available for a field
1129    pub fn has_positions(&self, field: Field) -> bool {
1130        // Check schema for position mode on this field
1131        if let Some(entry) = self.schema.get_field_entry(field) {
1132            entry.positions.is_some()
1133        } else {
1134            false
1135        }
1136    }
1137}
1138
1139// ── Synchronous search methods (mmap/RAM only) ─────────────────────────────
1140#[cfg(feature = "sync")]
1141impl SegmentReader {
1142    /// Synchronous posting list lookup — requires Inline (mmap/RAM) file handles.
1143    pub fn get_postings_sync(&self, field: Field, term: &[u8]) -> Result<Option<BlockPostingList>> {
1144        // Build key: field_id + term
1145        let mut key = Vec::with_capacity(4 + term.len());
1146        key.extend_from_slice(&field.0.to_le_bytes());
1147        key.extend_from_slice(term);
1148
1149        // Look up in term dictionary (sync)
1150        let term_info = match self.term_dict.get_sync(&key)? {
1151            Some(info) => info,
1152            None => return Ok(None),
1153        };
1154
1155        // Check if posting list is inlined
1156        if let Some((doc_ids, term_freqs)) = term_info.decode_inline() {
1157            let mut posting_list = crate::structures::PostingList::with_capacity(doc_ids.len());
1158            for (doc_id, tf) in doc_ids.into_iter().zip(term_freqs.into_iter()) {
1159                posting_list.push(doc_id, tf);
1160            }
1161            let block_list = BlockPostingList::from_posting_list(&posting_list)?;
1162            return Ok(Some(block_list));
1163        }
1164
1165        // External posting list — sync range read
1166        let (posting_offset, posting_len) = term_info.external_info().ok_or_else(|| {
1167            Error::Corruption("TermInfo has neither inline nor external data".to_string())
1168        })?;
1169
1170        let start = posting_offset;
1171        let end = start + posting_len;
1172
1173        if end > self.postings_handle.len() {
1174            return Err(Error::Corruption(
1175                "Posting offset out of bounds".to_string(),
1176            ));
1177        }
1178
1179        let posting_bytes = self.postings_handle.read_bytes_range_sync(start..end)?;
1180        let block_list = BlockPostingList::deserialize_zero_copy(posting_bytes)?;
1181
1182        Ok(Some(block_list))
1183    }
1184
1185    /// Synchronous prefix posting list lookup — requires Inline (mmap/RAM) file handles.
1186    pub fn get_prefix_postings_sync(
1187        &self,
1188        field: Field,
1189        prefix: &[u8],
1190    ) -> Result<Vec<BlockPostingList>> {
1191        let mut key_prefix = Vec::with_capacity(4 + prefix.len());
1192        key_prefix.extend_from_slice(&field.0.to_le_bytes());
1193        key_prefix.extend_from_slice(prefix);
1194
1195        let entries = self.term_dict.prefix_scan_sync(&key_prefix)?;
1196        let mut results = Vec::with_capacity(entries.len());
1197
1198        for (_key, term_info) in entries {
1199            if let Some((doc_ids, term_freqs)) = term_info.decode_inline() {
1200                let mut posting_list = crate::structures::PostingList::with_capacity(doc_ids.len());
1201                for (doc_id, tf) in doc_ids.into_iter().zip(term_freqs.into_iter()) {
1202                    posting_list.push(doc_id, tf);
1203                }
1204                results.push(BlockPostingList::from_posting_list(&posting_list)?);
1205            } else if let Some((posting_offset, posting_len)) = term_info.external_info() {
1206                let start = posting_offset;
1207                let end = start + posting_len;
1208                if end > self.postings_handle.len() {
1209                    continue;
1210                }
1211                let posting_bytes = self.postings_handle.read_bytes_range_sync(start..end)?;
1212                results.push(BlockPostingList::deserialize_zero_copy(posting_bytes)?);
1213            }
1214        }
1215
1216        Ok(results)
1217    }
1218
1219    /// Synchronous position list lookup — requires Inline (mmap/RAM) file handles.
1220    pub fn get_positions_sync(
1221        &self,
1222        field: Field,
1223        term: &[u8],
1224    ) -> Result<Option<crate::structures::PositionPostingList>> {
1225        let handle = match &self.positions_handle {
1226            Some(h) => h,
1227            None => return Ok(None),
1228        };
1229
1230        // Build key: field_id + term
1231        let mut key = Vec::with_capacity(4 + term.len());
1232        key.extend_from_slice(&field.0.to_le_bytes());
1233        key.extend_from_slice(term);
1234
1235        // Look up term in dictionary (sync)
1236        let term_info = match self.term_dict.get_sync(&key)? {
1237            Some(info) => info,
1238            None => return Ok(None),
1239        };
1240
1241        let (offset, length) = match term_info.position_info() {
1242            Some((o, l)) => (o, l),
1243            None => return Ok(None),
1244        };
1245
1246        let slice = handle.slice(offset..offset + length);
1247        let data = slice.read_bytes_sync()?;
1248
1249        let pos_list = crate::structures::PositionPostingList::deserialize(data.as_slice())?;
1250        Ok(Some(pos_list))
1251    }
1252
1253    /// Synchronous dense vector search — ANN indexes are already sync,
1254    /// brute-force uses sync mmap reads.
1255    pub fn search_dense_vector_sync(
1256        &self,
1257        field: Field,
1258        query: &[f32],
1259        k: usize,
1260        nprobe: usize,
1261        rerank_factor: f32,
1262        combiner: crate::query::MultiValueCombiner,
1263    ) -> Result<Vec<VectorSearchResult>> {
1264        let ann_index = self.vector_indexes.get(&field.0);
1265        let lazy_flat = self.flat_vectors.get(&field.0);
1266
1267        if ann_index.is_none() && lazy_flat.is_none() {
1268            return Ok(Vec::new());
1269        }
1270
1271        let unit_norm = self
1272            .schema
1273            .get_field_entry(field)
1274            .and_then(|e| e.dense_vector_config.as_ref())
1275            .is_some_and(|c| c.unit_norm);
1276
1277        const BRUTE_FORCE_BATCH: usize = 4096;
1278        let fetch_k = (k as f32 * rerank_factor.max(1.0)).ceil() as usize;
1279
1280        let mut results: Vec<(u32, u16, f32)> = if let Some(index) = ann_index {
1281            // ANN search (already sync)
1282            match index {
1283                VectorIndex::RaBitQ(lazy) => {
1284                    let rabitq = lazy.get().ok_or_else(|| {
1285                        Error::Schema("RaBitQ index deserialization failed".to_string())
1286                    })?;
1287                    rabitq
1288                        .search(query, fetch_k)
1289                        .into_iter()
1290                        .map(|(doc_id, ordinal, dist)| (doc_id, ordinal, 1.0 / (1.0 + dist)))
1291                        .collect()
1292                }
1293                VectorIndex::IVF(lazy) => {
1294                    let (index, codebook) = lazy.get().ok_or_else(|| {
1295                        Error::Schema("IVF index deserialization failed".to_string())
1296                    })?;
1297                    let centroids = self.coarse_centroids.get(&field.0).ok_or_else(|| {
1298                        Error::Schema(format!(
1299                            "IVF index requires coarse centroids for field {}",
1300                            field.0
1301                        ))
1302                    })?;
1303                    let effective_nprobe = if nprobe > 0 { nprobe } else { 32 };
1304                    index
1305                        .search(centroids, codebook, query, fetch_k, Some(effective_nprobe))
1306                        .into_iter()
1307                        .map(|(doc_id, ordinal, dist)| (doc_id, ordinal, 1.0 / (1.0 + dist)))
1308                        .collect()
1309                }
1310                VectorIndex::ScaNN(lazy) => {
1311                    let (index, codebook) = lazy.get().ok_or_else(|| {
1312                        Error::Schema("ScaNN index deserialization failed".to_string())
1313                    })?;
1314                    let centroids = self.coarse_centroids.get(&field.0).ok_or_else(|| {
1315                        Error::Schema(format!(
1316                            "ScaNN index requires coarse centroids for field {}",
1317                            field.0
1318                        ))
1319                    })?;
1320                    let effective_nprobe = if nprobe > 0 { nprobe } else { 32 };
1321                    index
1322                        .search(centroids, codebook, query, fetch_k, Some(effective_nprobe))
1323                        .into_iter()
1324                        .map(|(doc_id, ordinal, dist)| (doc_id, ordinal, 1.0 / (1.0 + dist)))
1325                        .collect()
1326                }
1327            }
1328        } else if let Some(lazy_flat) = lazy_flat {
1329            // Batched brute-force (sync mmap reads)
1330            let dim = lazy_flat.dim;
1331            let n = lazy_flat.num_vectors;
1332            let quant = lazy_flat.quantization;
1333            let mut collector = crate::query::ScoreCollector::new(fetch_k);
1334            let mut scores = vec![0f32; BRUTE_FORCE_BATCH];
1335
1336            for batch_start in (0..n).step_by(BRUTE_FORCE_BATCH) {
1337                let batch_count = BRUTE_FORCE_BATCH.min(n - batch_start);
1338                let batch_bytes = lazy_flat
1339                    .read_vectors_batch_sync(batch_start, batch_count)
1340                    .map_err(crate::Error::Io)?;
1341                let raw = batch_bytes.as_slice();
1342
1343                Self::score_quantized_batch(
1344                    query,
1345                    raw,
1346                    quant,
1347                    dim,
1348                    &mut scores[..batch_count],
1349                    unit_norm,
1350                );
1351
1352                for (i, &score) in scores.iter().enumerate().take(batch_count) {
1353                    let (doc_id, ordinal) = lazy_flat.get_doc_id(batch_start + i);
1354                    collector.insert_with_ordinal(doc_id, score, ordinal);
1355                }
1356            }
1357
1358            collector
1359                .into_sorted_results()
1360                .into_iter()
1361                .map(|(doc_id, score, ordinal)| (doc_id, ordinal, score))
1362                .collect()
1363        } else {
1364            return Ok(Vec::new());
1365        };
1366
1367        // Rerank ANN candidates using raw vectors (sync)
1368        if ann_index.is_some()
1369            && !results.is_empty()
1370            && let Some(lazy_flat) = lazy_flat
1371        {
1372            let dim = lazy_flat.dim;
1373            let quant = lazy_flat.quantization;
1374            let vbs = lazy_flat.vector_byte_size();
1375
1376            let mut resolved: Vec<(usize, usize)> = Vec::new();
1377            for (ri, c) in results.iter().enumerate() {
1378                let (start, entries) = lazy_flat.flat_indexes_for_doc(c.0);
1379                for (j, &(_, ord)) in entries.iter().enumerate() {
1380                    if ord == c.1 {
1381                        resolved.push((ri, start + j));
1382                        break;
1383                    }
1384                }
1385            }
1386
1387            if !resolved.is_empty() {
1388                resolved.sort_unstable_by_key(|&(_, flat_idx)| flat_idx);
1389                let mut raw_buf = vec![0u8; resolved.len() * vbs];
1390                for (buf_idx, &(_, flat_idx)) in resolved.iter().enumerate() {
1391                    let _ = lazy_flat.read_vector_raw_into_sync(
1392                        flat_idx,
1393                        &mut raw_buf[buf_idx * vbs..(buf_idx + 1) * vbs],
1394                    );
1395                }
1396
1397                let mut scores = vec![0f32; resolved.len()];
1398                Self::score_quantized_batch(query, &raw_buf, quant, dim, &mut scores, unit_norm);
1399
1400                for (buf_idx, &(ri, _)) in resolved.iter().enumerate() {
1401                    results[ri].2 = scores[buf_idx];
1402                }
1403            }
1404
1405            if results.len() > fetch_k {
1406                results.select_nth_unstable_by(fetch_k, |a, b| b.2.total_cmp(&a.2));
1407                results.truncate(fetch_k);
1408            }
1409            results.sort_unstable_by(|a, b| b.2.total_cmp(&a.2));
1410        }
1411
1412        Ok(combine_ordinal_results(results, combiner, k))
1413    }
1414}