Skip to main content

aft_store/vector/
search.rs

1//! Exact meaning search over the vectors of one model.
2//!
3//! A search scans the int8 codes of the members' vectors, which gives every
4//! member an interval its exact score is proven to lie in. A member whose
5//! upper bound is below the k-th highest lower bound cannot reach the top
6//! k, so only the rest (the guaranteed set) can. Those are rescored from
7//! their f32 rows with today's exact arithmetic, highest upper bound first,
8//! stopping once no remaining bound can reach the k-th exact score. The
9//! answer is today's f32 brute-force answer by construction, not by a tuned
10//! window. When the guaranteed set is too large to be worth reading row by
11//! row, the search reads every member's f32 row instead, which is just as
12//! exact, and says so.
13
14use std::cmp::Ordering;
15use std::collections::hash_map::Entry;
16use std::collections::{BinaryHeap, HashMap};
17use std::ops::Range;
18use std::sync::Arc;
19use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
20
21use super::VectorError;
22use super::model::{ModelId, ModelIdentity, TextDigest};
23use super::score::{QueryTerms, approx_kernel, dot_product, rank_order, score};
24use super::sections::{
25    Chunk, FileDetails, VectorSegment, VectorSegmentParts, f32s, scan_codes, scan_params,
26    scan_row_len,
27};
28use crate::ids::ContentKey;
29use crate::segment::{BLOCK_LEN, Segment};
30
31/// Bytes of scan rows or f32 rows read per call while scanning: one block,
32/// so the copy stays in the core's own cache while the scan reads it.
33const READ_BYTES: usize = BLOCK_LEN;
34
35/// Where one vector is: a segment of a [`VectorIndex`] and the vector's
36/// ordinal within it.
37#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
38pub struct UnitRef {
39    /// Position of the segment in the index's segment list.
40    pub segment: u32,
41    pub ordinal: u32,
42}
43
44/// The vectors of one model across a family's segments.
45///
46/// Built once per segment set; every search and every checkout reading the
47/// same segments shares it, and its segments read through the shared block
48/// cache.
49#[derive(Debug)]
50pub struct VectorIndex<'s> {
51    token: u64,
52    model: ModelIdentity,
53    model_id: ModelId,
54    segments: Vec<VectorSegment<'s>>,
55    /// Shared with every index lent by the same [`SharedVectorIndex`].
56    by_text: Arc<HashMap<TextDigest, UnitRef>>,
57}
58
59impl<'s> VectorIndex<'s> {
60    /// The vectors of `model` in `segments`, which are in the order a
61    /// snapshot lists them: by ascending id, so newer segments come later.
62    /// Segments of other models are left out.
63    ///
64    /// # Errors
65    ///
66    /// When a segment cannot be read.
67    pub fn build(
68        segments: impl IntoIterator<Item = VectorSegment<'s>>,
69        model: &ModelIdentity,
70    ) -> Result<Self, VectorError> {
71        static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1);
72        let segments: Vec<_> = segments
73            .into_iter()
74            .filter(|segment| segment.model() == model)
75            .collect();
76        if u32::try_from(segments.len()).is_err() {
77            return Err(VectorError::TooManySegments);
78        }
79        let mut by_text = HashMap::new();
80        for (index, segment) in segments.iter().enumerate() {
81            let index = u32::try_from(index).expect("checked above");
82            for (ordinal, text) in segment.texts()?.into_iter().enumerate() {
83                let ordinal = u32::try_from(ordinal).expect("a segment holds below 2^32 units");
84                // A text embedded again in a newer segment is found there.
85                by_text.insert(
86                    text,
87                    UnitRef {
88                        segment: index,
89                        ordinal,
90                    },
91                );
92            }
93        }
94        Ok(Self {
95            token: NEXT_TOKEN.fetch_add(1, AtomicOrdering::Relaxed),
96            model: model.clone(),
97            model_id: model.id(),
98            segments,
99            by_text: Arc::new(by_text),
100        })
101    }
102
103    #[must_use]
104    pub fn model(&self) -> &ModelIdentity {
105        &self.model
106    }
107
108    /// How many distinct vectors of the model the segments hold. Zero means
109    /// no vectors for this model at all, which a search reports as
110    /// [`VectorError::NoVectors`] rather than as an empty answer.
111    #[must_use]
112    pub fn vectors(&self) -> usize {
113        self.by_text.len()
114    }
115
116    #[must_use]
117    pub fn segments(&self) -> &[VectorSegment<'s>] {
118        &self.segments
119    }
120
121    /// Where the vector embedded for `text` is.
122    #[must_use]
123    pub fn locate(&self, text: TextDigest) -> Option<UnitRef> {
124        self.by_text.get(&text).copied()
125    }
126
127    /// The stored f32 vector at `unit`.
128    ///
129    /// # Errors
130    ///
131    /// When `unit` is not in the index, or a read fails.
132    pub fn vector(&self, unit: UnitRef) -> Result<Vec<f32>, VectorError> {
133        let segment = self.segment_of(unit)?;
134        Ok(segment.vector(unit.ordinal)?)
135    }
136
137    /// The chunks of the file at `path` with `content`, in chunk order, each
138    /// with its vector if one is stored. `None` when no segment has a chunk
139    /// map for the file: its chunks were never embedded under this model.
140    ///
141    /// # Errors
142    ///
143    /// When a read fails or a map is malformed.
144    pub fn chunk_map(
145        &self,
146        content: ContentKey,
147        path: &[u8],
148    ) -> Result<Option<Vec<MappedChunk>>, VectorError> {
149        for segment in self.segments.iter().rev() {
150            if let Some(chunks) = segment.chunk_map(content, path)? {
151                return Ok(Some(
152                    chunks
153                        .into_iter()
154                        .map(|chunk| MappedChunk {
155                            chunk,
156                            unit: self.locate(chunk.text),
157                        })
158                        .collect(),
159                ));
160            }
161        }
162        Ok(None)
163    }
164
165    /// The details recorded with the chunk map [`chunk_map`](Self::chunk_map)
166    /// returns for the same file: `None` when no segment has a map for it,
167    /// or its map was stored without details.
168    ///
169    /// # Errors
170    ///
171    /// When a read fails or the details are malformed.
172    pub fn chunk_details(
173        &self,
174        content: ContentKey,
175        path: &[u8],
176    ) -> Result<Option<FileDetails>, VectorError> {
177        for segment in self.segments.iter().rev() {
178            if segment.chunk_map(content, path)?.is_some() {
179                return Ok(segment.chunk_details(content, path)?);
180            }
181        }
182        Ok(None)
183    }
184
185    /// The members of a set of files, in the order given and then in chunk
186    /// order, with how much of them has vectors.
187    ///
188    /// # Errors
189    ///
190    /// When a read fails or a map is malformed.
191    pub fn file_members<'p>(
192        &self,
193        files: impl IntoIterator<Item = (ContentKey, &'p [u8])>,
194    ) -> Result<FileMembers, VectorError> {
195        let mut found = FileMembers::default();
196        for (content, path) in files {
197            found.coverage.files += 1;
198            let Some(chunks) = self.chunk_map(content, path)? else {
199                continue;
200            };
201            found.coverage.files_mapped += 1;
202            found.coverage.chunks += chunks.len();
203            for MappedChunk { chunk, unit } in chunks {
204                if let Some(unit) = unit {
205                    found.coverage.chunks_embedded += 1;
206                    found.members.push(Member {
207                        unit,
208                        exported: chunk.exported,
209                    });
210                }
211            }
212        }
213        Ok(found)
214    }
215
216    /// Prepares `members` for searching. Their order is the tie-break:
217    /// among equal scores, the member listed first ranks first, as the entry
218    /// enumerated first does in today's index.
219    ///
220    /// # Errors
221    ///
222    /// When a member names a vector the index does not have.
223    pub fn member_set(&self, members: Vec<Member>) -> Result<MemberSet, VectorError> {
224        if u32::try_from(members.len()).is_err() {
225            return Err(VectorError::TooManyMembers);
226        }
227        for member in &members {
228            self.segment_of(member.unit)?;
229        }
230        let mut order: Vec<u32> = (0..members.len())
231            .map(|index| u32::try_from(index).expect("checked above"))
232            .collect();
233        order.sort_unstable_by_key(|index| members[*index as usize].unit);
234        let mut slot_of = vec![0; members.len()];
235        let mut slots: Vec<UnitRef> = Vec::new();
236        for index in order {
237            let unit = members[index as usize].unit;
238            if slots.last() != Some(&unit) {
239                slots.push(unit);
240            }
241            slot_of[index as usize] = u32::try_from(slots.len() - 1).expect("checked above");
242        }
243        let mut segment_slots = vec![0..0; self.segments.len()];
244        let mut start = 0;
245        while start < slots.len() {
246            let segment = slots[start].segment;
247            let end = start + slots[start..].partition_point(|unit| unit.segment == segment);
248            segment_slots[segment as usize] = start..end;
249            start = end;
250        }
251        Ok(MemberSet {
252            index_token: self.token,
253            members,
254            slot_of,
255            slots,
256            segment_slots,
257        })
258    }
259
260    /// The exact top `k` members for `request`: today's f32 scores, in
261    /// today's order, ties broken by member position.
262    ///
263    /// # Errors
264    ///
265    /// [`VectorError::NoVectors`] when the segments hold no vector of this
266    /// model; [`VectorError::DimensionMismatch`] or
267    /// [`VectorError::NonFinite`] for a query the model cannot score;
268    /// [`VectorError::ForeignMembers`] for a member set prepared by another
269    /// index; otherwise when a read fails or a block fails its checksum.
270    pub fn search(
271        &self,
272        members: &MemberSet,
273        request: &SearchRequest<'_>,
274    ) -> Result<SearchResult, VectorError> {
275        let query = request.query;
276        self.check(members, query)?;
277        let mut report = SearchReport {
278            members: members.members.len(),
279            ..SearchReport::default()
280        };
281        let k = request.k.min(members.members.len());
282        if k == 0 {
283            return Ok(SearchResult {
284                hits: Vec::new(),
285                report,
286            });
287        }
288        let terms = QueryTerms::new(query);
289        let bounds = self.scan(members, &terms, query, &mut report)?;
290        report.units_scanned = members.slots.len();
291        let (lower, upper, bounded) = member_bounds(members, &terms, &bounds);
292        if !bounded {
293            report.full_scan = Some(FullScan::Unbounded);
294            return self.full_scan(members, &terms, query, k, report);
295        }
296
297        // Every member below the k-th highest lower bound is beaten by at
298        // least k members with strictly higher exact scores.
299        let threshold = if k < lower.len() {
300            let mut lows = lower.clone();
301            lows.select_nth_unstable_by(k - 1, |a, b| b.total_cmp(a));
302            lows[k - 1]
303        } else {
304            f32::NEG_INFINITY
305        };
306        let mut guaranteed: Vec<u32> = (0..members.members.len())
307            .filter(|index| upper[*index] >= threshold)
308            .map(|index| u32::try_from(index).expect("member count fits in u32"))
309            .collect();
310        report.guaranteed = guaranteed.len();
311        let limit = request.rescore_limit.unwrap_or_else(|| {
312            default_rescore_limit(members.slots.len(), self.model.dimensions as usize, k)
313        });
314        if guaranteed.len() > limit {
315            report.full_scan = Some(FullScan::GuaranteedSetTooLarge { limit });
316            return self.full_scan(members, &terms, query, k, report);
317        }
318
319        guaranteed.sort_unstable_by(|a, b| {
320            upper[*b as usize]
321                .total_cmp(&upper[*a as usize])
322                .then(a.cmp(b))
323        });
324        let mut top: BinaryHeap<Ranked> = BinaryHeap::with_capacity(k + 1);
325        let mut exact_dots: HashMap<u32, f32> = HashMap::new();
326        let mut bytes = vec![0; query.len() * 4];
327        for index in guaranteed {
328            let position = index as usize;
329            if top.len() == k
330                && let Some(worst) = top.peek()
331                && upper[position] < worst.score
332            {
333                break;
334            }
335            let slot = members.slot_of[position];
336            let dot = match exact_dots.entry(slot) {
337                Entry::Occupied(entry) => *entry.get(),
338                Entry::Vacant(entry) => {
339                    let unit = members.slots[slot as usize];
340                    self.segments[unit.segment as usize].read_vector(unit.ordinal, &mut bytes)?;
341                    report.rescored += 1;
342                    report.f32_bytes_read += bytes.len() as u64;
343                    *entry.insert(dot_product(query, &f32s(&bytes)))
344                }
345            };
346            let denom = terms.norm * bounds[slot as usize].norm;
347            let ranked = Ranked {
348                score: score(dot, denom, members.members[position].exported),
349                position: index,
350            };
351            if top.len() < k {
352                top.push(ranked);
353            } else if top
354                .peek()
355                .is_some_and(|worst| ranked.cmp(worst) == Ordering::Less)
356            {
357                top.pop();
358                top.push(ranked);
359            }
360        }
361        Ok(SearchResult {
362            hits: top
363                .into_sorted_vec()
364                .into_iter()
365                .map(|ranked| members.hit(ranked))
366                .collect(),
367            report,
368        })
369    }
370
371    /// The interval each member's exact score is proven to lie in, from the
372    /// int8 scan alone, in member order. A search excludes members by these
373    /// same bounds; gates use this to check that the bounds hold.
374    ///
375    /// # Errors
376    ///
377    /// As [`search`](Self::search).
378    pub fn bounds(
379        &self,
380        members: &MemberSet,
381        query: &[f32],
382    ) -> Result<Vec<ScoreBounds>, VectorError> {
383        self.check(members, query)?;
384        let terms = QueryTerms::new(query);
385        let bounds = self.scan(members, &terms, query, &mut SearchReport::default())?;
386        let (lower, upper, _) = member_bounds(members, &terms, &bounds);
387        Ok(lower
388            .into_iter()
389            .zip(upper)
390            .map(|(low, high)| ScoreBounds { low, high })
391            .collect())
392    }
393
394    fn check(&self, members: &MemberSet, query: &[f32]) -> Result<(), VectorError> {
395        if self.by_text.is_empty() {
396            return Err(VectorError::NoVectors(self.model_id));
397        }
398        if members.index_token != self.token {
399            return Err(VectorError::ForeignMembers);
400        }
401        if query.len() != self.model.dimensions as usize {
402            return Err(VectorError::DimensionMismatch {
403                expected: self.model.dimensions,
404                found: query.len(),
405            });
406        }
407        if query.iter().any(|value| !value.is_finite()) {
408            return Err(VectorError::NonFinite);
409        }
410        Ok(())
411    }
412
413    /// Scans the int8 codes of every member's vector, in segment and
414    /// ordinal order, giving each distinct vector bounds on its exact dot
415    /// product with the query.
416    fn scan(
417        &self,
418        members: &MemberSet,
419        terms: &QueryTerms,
420        query: &[f32],
421        report: &mut SearchReport,
422    ) -> Result<Vec<UnitBounds>, VectorError> {
423        let dimensions = query.len();
424        let row_len = scan_row_len(dimensions);
425        let approx_dot = approx_kernel();
426        let mut bounds = Vec::with_capacity(members.slots.len());
427        let mut buf = Vec::new();
428        for (segment, range) in self.segments.iter().zip(&members.segment_slots) {
429            if range.is_empty() {
430                continue;
431            }
432            let center = terms.center(query, segment.center());
433            for_each_window(
434                &members.slots[range.clone()],
435                (READ_BYTES / row_len).max(1),
436                |window| {
437                    let first = window[0].ordinal;
438                    let rows = (window[window.len() - 1].ordinal - first) as usize + 1;
439                    buf.resize(rows * row_len, 0);
440                    segment.read_scan_rows(first, &mut buf)?;
441                    report.scan_bytes += buf.len() as u64;
442                    for unit in window {
443                        let at = (unit.ordinal - first) as usize * row_len;
444                        let row = &buf[at..at + row_len];
445                        let params = scan_params(row);
446                        let approx = approx_dot(query, scan_codes(row, dimensions));
447                        let (low, high) = terms.dot_bounds(approx, &params, &center);
448                        bounds.push(UnitBounds {
449                            low,
450                            high,
451                            norm: params.norm,
452                        });
453                    }
454                    Ok::<_, VectorError>(())
455                },
456            )?;
457        }
458        Ok(bounds)
459    }
460
461    /// Today's brute force over the members' f32 rows, read in segment and
462    /// ordinal order.
463    fn full_scan(
464        &self,
465        members: &MemberSet,
466        terms: &QueryTerms,
467        query: &[f32],
468        k: usize,
469        mut report: SearchReport,
470    ) -> Result<SearchResult, VectorError> {
471        let row_bytes = query.len() * 4;
472        let mut dots = Vec::with_capacity(members.slots.len());
473        let mut norms = Vec::with_capacity(members.slots.len());
474        let mut buf = Vec::new();
475        for (segment, range) in self.segments.iter().zip(&members.segment_slots) {
476            for_each_window(
477                &members.slots[range.clone()],
478                (READ_BYTES / row_bytes).max(1),
479                |window| {
480                    let first = window[0].ordinal;
481                    let rows = (window[window.len() - 1].ordinal - first) as usize + 1;
482                    buf.resize(rows * row_bytes, 0);
483                    segment.read_vectors(first, &mut buf)?;
484                    report.f32_bytes_read += buf.len() as u64;
485                    for unit in window {
486                        let at = (unit.ordinal - first) as usize * row_bytes;
487                        let vector = f32s(&buf[at..at + row_bytes]);
488                        dots.push(dot_product(query, &vector));
489                        norms.push(super::score::vector_norm(&vector));
490                    }
491                    Ok::<_, VectorError>(())
492                },
493            )?;
494        }
495        report.rescored = members.slots.len();
496        let mut scored: Vec<(f32, u32)> = members
497            .members
498            .iter()
499            .zip(&members.slot_of)
500            .enumerate()
501            .map(|(index, (member, slot))| {
502                let denom = terms.norm * norms[*slot as usize];
503                (
504                    score(dots[*slot as usize], denom, member.exported),
505                    u32::try_from(index).expect("member count fits in u32"),
506                )
507            })
508            .collect();
509        let order = |a: &(f32, u32), b: &(f32, u32)| rank_order(*a, *b);
510        if k < scored.len() {
511            scored.select_nth_unstable_by(k, order);
512            scored.truncate(k);
513        }
514        scored.sort_by(order);
515        Ok(SearchResult {
516            hits: scored
517                .into_iter()
518                .map(|(score, position)| members.hit(Ranked { score, position }))
519                .collect(),
520            report,
521        })
522    }
523
524    fn segment_of(&self, unit: UnitRef) -> Result<&VectorSegment<'s>, VectorError> {
525        self.segments
526            .get(unit.segment as usize)
527            .filter(|segment| unit.ordinal < segment.len())
528            .ok_or(VectorError::UnknownUnit(unit))
529    }
530}
531
532/// A [`VectorIndex`] that owns its segments, so it can be kept between
533/// searches and shared by threads. Building it opens and checks every
534/// segment and reads every vector key once; [`index`](Self::index) then
535/// lends an index over the same open segments without reading anything.
536/// Member sets prepared through one lent index serve every other.
537#[derive(Debug)]
538pub struct SharedVectorIndex {
539    token: u64,
540    model: ModelIdentity,
541    model_id: ModelId,
542    /// This model's segments, in the order given, each with what opening its
543    /// vector sections found.
544    segments: Vec<(Arc<Segment>, VectorSegmentParts)>,
545    by_text: Arc<HashMap<TextDigest, UnitRef>>,
546}
547
548impl SharedVectorIndex {
549    /// The vectors of `model` in `segments`, which are in the order a
550    /// snapshot lists them (see [`VectorIndex::build`]). Segments without
551    /// vector sections, or with another model's, are left out.
552    ///
553    /// # Errors
554    ///
555    /// When a segment cannot be read.
556    pub fn build(
557        segments: impl IntoIterator<Item = Arc<Segment>>,
558        model: &ModelIdentity,
559    ) -> Result<Self, VectorError> {
560        Self::assemble(segments, model, None)
561    }
562
563    /// The vectors of the same model in `segments`, reusing what building
564    /// this index read for each segment it already holds (the same open
565    /// segment, not just the same file), so only the others are opened and
566    /// checked. Member sets prepared for this index do not serve the new one.
567    ///
568    /// # Errors
569    ///
570    /// When a segment cannot be read.
571    pub fn rebuild(
572        &self,
573        segments: impl IntoIterator<Item = Arc<Segment>>,
574    ) -> Result<Self, VectorError> {
575        Self::assemble(segments, &self.model, Some(self))
576    }
577
578    fn assemble(
579        segments: impl IntoIterator<Item = Arc<Segment>>,
580        model: &ModelIdentity,
581        previous: Option<&Self>,
582    ) -> Result<Self, VectorError> {
583        let mut kept = Vec::new();
584        for segment in segments {
585            let reused = previous.and_then(|previous| {
586                previous
587                    .segments
588                    .iter()
589                    .find(|(held, _)| Arc::ptr_eq(held, &segment))
590                    .map(|(_, parts)| parts.clone())
591            });
592            let parts = match reused {
593                Some(parts) => parts,
594                None => match VectorSegment::open(&segment)? {
595                    Some(opened) if opened.model() == model => opened.parts(),
596                    _ => continue,
597                },
598            };
599            kept.push((segment, parts));
600        }
601        let (token, model_id, by_text) = {
602            let index = VectorIndex::build(
603                kept.iter().map(|(segment, parts)| reopened(segment, parts)),
604                model,
605            )?;
606            (index.token, index.model_id, Arc::clone(&index.by_text))
607        };
608        Ok(Self {
609            token,
610            model: model.clone(),
611            model_id,
612            segments: kept,
613            by_text,
614        })
615    }
616
617    /// An index over the same open segments, sharing everything building
618    /// this one read. Cheap: it reads nothing.
619    #[must_use]
620    pub fn index(&self) -> VectorIndex<'_> {
621        VectorIndex {
622            token: self.token,
623            model: self.model.clone(),
624            model_id: self.model_id,
625            segments: self
626                .segments
627                .iter()
628                .map(|(segment, parts)| reopened(segment, parts))
629                .collect(),
630            by_text: Arc::clone(&self.by_text),
631        }
632    }
633
634    #[must_use]
635    pub fn model(&self) -> &ModelIdentity {
636        &self.model
637    }
638
639    /// How many distinct vectors of the model the segments hold.
640    #[must_use]
641    pub fn vectors(&self) -> usize {
642        self.by_text.len()
643    }
644
645    /// The segments holding this model's vectors, in index order: a
646    /// [`UnitRef::segment`] is a position in this list.
647    pub fn segments(&self) -> impl Iterator<Item = &Arc<Segment>> {
648        self.segments.iter().map(|(segment, _)| segment)
649    }
650}
651
652/// `segment`'s vector sections from `parts`, which opening that very segment
653/// produced.
654fn reopened<'s>(segment: &'s Segment, parts: &VectorSegmentParts) -> VectorSegment<'s> {
655    VectorSegment::reopen(segment, parts).expect("the parts came from opening this segment")
656}
657
658/// Each member's lower and upper score bound, and whether every bound is
659/// finite. Today's score is a non-decreasing function of the dot product, so
660/// the dot product's bounds, scored as today scores, bound the score.
661fn member_bounds(
662    members: &MemberSet,
663    terms: &QueryTerms,
664    bounds: &[UnitBounds],
665) -> (Vec<f32>, Vec<f32>, bool) {
666    let mut lower = Vec::with_capacity(members.members.len());
667    let mut upper = Vec::with_capacity(members.members.len());
668    let mut bounded = terms.norm.is_finite();
669    for (member, slot) in members.members.iter().zip(&members.slot_of) {
670        let unit = &bounds[*slot as usize];
671        let denom = terms.norm * unit.norm;
672        let low = score(unit.low, denom, member.exported);
673        let high = score(unit.high, denom, member.exported);
674        bounded &= high.is_finite() && low.is_finite() && denom.is_finite();
675        lower.push(low);
676        upper.push(high);
677    }
678    (lower, upper, bounded)
679}
680
681/// Splits ascending `units` of one segment into runs whose ordinals span at
682/// most `rows`, and calls `each` with every run, so consecutive members are
683/// read together and isolated ones alone.
684fn for_each_window<E>(
685    units: &[UnitRef],
686    rows: usize,
687    mut each: impl FnMut(&[UnitRef]) -> Result<(), E>,
688) -> Result<(), E> {
689    let mut start = 0;
690    while start < units.len() {
691        let first = units[start].ordinal as usize;
692        let end =
693            start + units[start..].partition_point(|unit| (unit.ordinal as usize) < first + rows);
694        each(&units[start..end])?;
695        start = end;
696    }
697    Ok(())
698}
699
700/// How many vectors a search rescores one row at a time before it reads
701/// every member's f32 row instead. Rescoring reads whole 64 KiB blocks, so
702/// once the candidates outnumber the blocks the members' rows span, they
703/// touch most of those blocks anyway and one sequential pass costs no more.
704#[must_use]
705pub fn default_rescore_limit(units: usize, dimensions: usize, k: usize) -> usize {
706    let blocks = (units * dimensions * 4).div_ceil(BLOCK_LEN);
707    blocks.max(k.saturating_mul(4))
708}
709
710/// The interval a member's exact score is proven to lie in.
711#[derive(Clone, Copy, PartialEq, Debug)]
712pub struct ScoreBounds {
713    pub low: f32,
714    pub high: f32,
715}
716
717/// Bounds on one vector's exact dot product with the query.
718#[derive(Clone, Copy, Debug)]
719struct UnitBounds {
720    low: f32,
721    high: f32,
722    norm: f32,
723}
724
725/// An exact score and its member, ordered as today ranks them: a smaller
726/// value ranks first.
727#[derive(Clone, Copy, Debug)]
728struct Ranked {
729    score: f32,
730    position: u32,
731}
732
733impl PartialEq for Ranked {
734    fn eq(&self, other: &Self) -> bool {
735        self.cmp(other) == Ordering::Equal
736    }
737}
738
739impl Eq for Ranked {}
740
741impl PartialOrd for Ranked {
742    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
743        Some(self.cmp(other))
744    }
745}
746
747impl Ord for Ranked {
748    fn cmp(&self, other: &Self) -> Ordering {
749        rank_order((self.score, self.position), (other.score, other.position))
750    }
751}
752
753/// One chunk of a file's chunk map, with where its vector is, if stored.
754#[derive(Clone, Copy, PartialEq, Eq, Debug)]
755pub struct MappedChunk {
756    pub chunk: Chunk,
757    /// `None` until the chunk's text is embedded under the model.
758    pub unit: Option<UnitRef>,
759}
760
761/// One chunk that a search may return.
762#[derive(Clone, Copy, PartialEq, Eq, Debug)]
763pub struct Member {
764    pub unit: UnitRef,
765    /// Whether today's exported-chunk boost applies.
766    pub exported: bool,
767}
768
769/// Members prepared for searching one [`VectorIndex`]: the chunks a
770/// checkout may return, in tie-break order. Built once per checkout state
771/// and shared by its searches.
772#[derive(Clone, Debug)]
773pub struct MemberSet {
774    index_token: u64,
775    members: Vec<Member>,
776    /// The distinct vector each member uses.
777    slot_of: Vec<u32>,
778    /// Distinct vectors, ascending.
779    slots: Vec<UnitRef>,
780    /// Each segment's run of `slots`.
781    segment_slots: Vec<Range<usize>>,
782}
783
784impl MemberSet {
785    #[must_use]
786    pub fn members(&self) -> &[Member] {
787        &self.members
788    }
789
790    /// How many distinct vectors the members use.
791    #[must_use]
792    pub fn units(&self) -> usize {
793        self.slots.len()
794    }
795
796    fn hit(&self, ranked: Ranked) -> Hit {
797        Hit {
798            member: ranked.position,
799            unit: self.members[ranked.position as usize].unit,
800            score: ranked.score,
801        }
802    }
803}
804
805/// The members of a set of files, and how many of their chunks have
806/// vectors.
807#[derive(Clone, Debug, Default)]
808pub struct FileMembers {
809    pub members: Vec<Member>,
810    pub coverage: Coverage,
811}
812
813/// How much of a set of files meaning search can see.
814#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
815pub struct Coverage {
816    pub files: usize,
817    /// Files with a chunk map under the model.
818    pub files_mapped: usize,
819    /// Chunks of the mapped files.
820    pub chunks: usize,
821    /// Chunks whose vector is stored.
822    pub chunks_embedded: usize,
823}
824
825/// What to search for.
826#[derive(Clone, Copy, Debug)]
827pub struct SearchRequest<'q> {
828    pub query: &'q [f32],
829    /// How many members to return.
830    pub k: usize,
831    /// The largest guaranteed set rescored row by row; `None` for
832    /// [`default_rescore_limit`].
833    pub rescore_limit: Option<usize>,
834}
835
836/// One member in the answer.
837#[derive(Clone, Copy, PartialEq, Debug)]
838pub struct Hit {
839    /// The member's position in its [`MemberSet`].
840    pub member: u32,
841    pub unit: UnitRef,
842    /// Today's exact f32 score, bit for bit.
843    pub score: f32,
844}
845
846/// Why a search read every member's f32 row.
847#[derive(Clone, Copy, PartialEq, Eq, Debug)]
848pub enum FullScan {
849    /// More members could reach the top k than the rescore limit allows.
850    GuaranteedSetTooLarge { limit: usize },
851    /// A bound was not finite, so it could not exclude anything: a query or
852    /// vector so large that its scores overflow.
853    Unbounded,
854}
855
856/// The work one search did.
857#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
858pub struct SearchReport {
859    pub members: usize,
860    /// Distinct vectors whose int8 codes were scanned.
861    pub units_scanned: usize,
862    /// Bytes of scan rows read.
863    pub scan_bytes: u64,
864    /// Members that could reach the top k after the scan.
865    pub guaranteed: usize,
866    /// Distinct vectors whose f32 rows were read.
867    pub rescored: usize,
868    /// Bytes of f32 rows read.
869    pub f32_bytes_read: u64,
870    /// Set when the search fell back to reading every member's f32 row.
871    pub full_scan: Option<FullScan>,
872}
873
874/// A search's answer and the work it took.
875#[derive(Clone, Debug)]
876pub struct SearchResult {
877    /// Best first.
878    pub hits: Vec<Hit>,
879    pub report: SearchReport,
880}
881
882crate::heap_bytes_none!(UnitRef, Member);
883crate::heap_bytes_of_fields!(SharedVectorIndex {
884    token,
885    model,
886    model_id,
887    segments,
888    by_text,
889});
890crate::heap_bytes_of_fields!(MemberSet {
891    index_token,
892    members,
893    slot_of,
894    slots,
895    segment_slots,
896});