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