Skip to main content

itzma_core/
query.rs

1//! The query engine: everything about a query that is the same
2//! whichever index algorithm a segment has.
3//!
4//! The engine treats the namespace as a list of *sources*, oldest to newest.
5//! Each live segment that the manifest gives an index (of a kind this build
6//! knows) is an indexed source, read in pieces. Every run of segments without
7//! one is folded into one in-memory layer and scanned flat, and so is the WAL
8//! tail, which the handle keeps folded between queries and which is
9//! always its own, newest source. A source proposes its closest rows, and the engine does the rest:
10//!
11//! 1. drop every proposal that a newer source holds as a document or as a
12//!    tombstone (an id's newest holder decides it, so this is what an overwrite
13//!    or a delete means),
14//! 2. fetch the exact vectors of what is left and rescore them, which is the
15//!    rerank, so the answer never carries an approximate distance,
16//! 3. merge the sources, keep the closest `top_k` and fetch their attributes.
17//!
18//! A source that ends up with fewer than `top_k` live proposals while it has more
19//! rows to give pulls another, bigger batch from its cursor, so
20//! shadowing costs requests and never an answer. A source stops widening once it
21//! has `top_k` live rows, its cursor is exhausted, or the shared top-k bound
22//! proves the rest of it cannot beat what other sources have already
23//! found. An index algorithm only proposes rows through a
24//! [`Cursor`](crate::index::Cursor) (see [`index::Algorithm`](crate::index)), and
25//! its output is checked: a row past the segment is `CorruptIndex`, and a row
26//! repeated across batches is too.
27//!
28//! Every byte read is charged to one [`ReadBudget`] for the whole query, so a
29//! namespace bigger than the budget can be queried through its indexes while
30//! reading it whole is refused.
31
32use std::collections::HashMap;
33use std::sync::Arc;
34
35use futures::future::try_join_all;
36use futures::stream::{self, StreamExt, TryStreamExt};
37use object_store::ObjectStore;
38use object_store::path::Path;
39use serde::{Deserialize, Serialize};
40
41use crate::budget::ReadBudget;
42use crate::cpu::{self, Cost, Lane};
43use crate::decoded::DecodedRef;
44use crate::document::Metric;
45use crate::error::{ItzmaError, Result};
46use crate::fetch::FetchPolicy;
47use crate::index::{self, Algorithm, Candidate, Probe};
48use crate::layer::Layer;
49use crate::manifest::Manifest;
50use crate::predicate::Predicate;
51use crate::search::{self, Hit};
52use crate::segment::{self, Held, RangedSegment, SegmentView};
53
54/// The default for [`QueryOptions::rerank`], a guess until the recall harness
55/// has measured one.
56pub const DEFAULT_RERANK: usize = 4;
57
58/// Requests in flight at once when a step fans out over blocks or ids.
59const FETCH_CONCURRENCY: usize = 16;
60/// How much bigger each batch a source is asked for grows, when it is still
61/// short of `top_k` live rows and the bound has not ruled out the rest.
62const WIDEN: usize = 8;
63
64/// Settings for [`Namespace::query_with`](crate::Namespace::query_with).
65///
66/// New fields may be added, so build one from `default()` and the setters.
67///
68/// # Examples
69///
70/// ```
71/// use itzma_core::QueryOptions;
72///
73/// let every_row = QueryOptions::default().rerank(None);
74/// assert_eq!(every_row.rerank, None);
75/// assert_eq!(QueryOptions::default().rerank, Some(4));
76/// ```
77#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
78#[serde(default)]
79#[non_exhaustive]
80pub struct QueryOptions {
81    /// How many candidates an index gives for each hit wanted: an indexed
82    /// segment proposes `rerank * top_k` rows by approximate distance, and those
83    /// are rescored against the exact vectors. Bigger is slower and closer to the
84    /// exact answer. `None` proposes every row, which makes the answer equal the
85    /// flat scan's. Must be at least 1.
86    pub rerank: Option<usize>,
87    /// How many partitions of an index to search. `None` lets the index
88    /// choose from how many partitions it has. A bigger value costs more and
89    /// finds more true neighbors. Must be at least 1.
90    pub nprobe: Option<usize>,
91    /// Ignore every index and scan flat. The ground truth for measuring recall,
92    /// and a way through a damaged index.
93    pub exact: bool,
94    /// Keep only documents whose attributes match this predicate.
95    /// Checked against the namespace's attribute schema before any read, so an
96    /// undeclared field or an operator that does not fit its type is an error.
97    /// The result has fewer than `top_k` hits only when fewer live documents
98    /// match. A very selective filter can read the whole namespace, bounded by
99    /// the read budget.
100    pub filter: Option<Predicate>,
101}
102
103impl Default for QueryOptions {
104    fn default() -> Self {
105        Self {
106            rerank: Some(DEFAULT_RERANK),
107            nprobe: None,
108            exact: false,
109            filter: None,
110        }
111    }
112}
113
114impl QueryOptions {
115    /// Set [`rerank`](Self::rerank).
116    #[must_use]
117    pub fn rerank(mut self, rerank: Option<usize>) -> Self {
118        self.rerank = rerank;
119        self
120    }
121
122    /// Set [`nprobe`](Self::nprobe).
123    #[must_use]
124    pub fn nprobe(mut self, nprobe: Option<usize>) -> Self {
125        self.nprobe = nprobe;
126        self
127    }
128
129    /// Set [`exact`](Self::exact).
130    #[must_use]
131    pub fn exact(mut self, exact: bool) -> Self {
132        self.exact = exact;
133        self
134    }
135
136    /// Set [`filter`](Self::filter).
137    #[must_use]
138    pub fn filter(mut self, filter: Option<Predicate>) -> Self {
139        self.filter = filter;
140        self
141    }
142
143    /// Refuse options that cannot be run, before any storage call.
144    pub(crate) fn validate(&self) -> Result<()> {
145        if self.rerank == Some(0) {
146            return Err(ItzmaError::InvalidQuery("rerank must be at least 1"));
147        }
148        if self.nprobe == Some(0) {
149            return Err(ItzmaError::InvalidQuery("nprobe must be at least 1"));
150        }
151        Ok(())
152    }
153}
154
155/// Which code searches an index of a given kind name. A manifest may name a kind
156/// this build does not have (a newer build published it), and the engine then
157/// reads that segment flat like any unindexed one: an index is derived data, so
158/// not knowing one costs speed and never a right answer.
159pub(crate) trait Registry: Sync {
160    fn algorithm(&self, kind: &str) -> Option<&dyn Algorithm>;
161}
162
163/// The kinds this build has.
164pub(crate) struct Builtin;
165
166impl Registry for Builtin {
167    fn algorithm(&self, kind: &str) -> Option<&dyn Algorithm> {
168        index::Kind::from_name(kind).map(index::Kind::algorithm)
169    }
170}
171
172/// Whether any live segment has an index this build can search. Without one
173/// every segment is one flat step.
174fn uses_indexes(manifest: &Manifest, registry: &dyn Registry) -> bool {
175    manifest.live_segments.iter().any(|id| {
176        manifest
177            .indexes
178            .get(id)
179            .is_some_and(|entry| registry.algorithm(&entry.kind).is_some())
180    })
181}
182
183/// One query against one manifest.
184pub(crate) struct Query<'a> {
185    pub(crate) store: &'a dyn ObjectStore,
186    pub(crate) namespace: &'a str,
187    pub(crate) dim: usize,
188    pub(crate) metric: Metric,
189    pub(crate) vector: &'a [f32],
190    pub(crate) top_k: usize,
191    pub(crate) options: &'a QueryOptions,
192    pub(crate) budget: &'a ReadBudget,
193    pub(crate) policy: &'a FetchPolicy,
194    pub(crate) registry: &'a dyn Registry,
195    /// Parsed structures kept between queries, if the handle has a
196    /// decoded cache.
197    pub(crate) decoded: Option<&'a DecodedRef>,
198}
199
200impl Query<'_> {
201    /// The predicate the query filters by, if any.
202    fn filter(&self) -> Option<&Predicate> {
203        self.options.filter.as_ref()
204    }
205}
206
207/// What the manifest's live segments turn into.
208enum Step<'a> {
209    /// A segment with an index this build can search.
210    Indexed {
211        id: &'a str,
212        generation: u32,
213        algorithm: &'a dyn Algorithm,
214    },
215    /// A run of consecutive segments without one.
216    Flat(&'a [String]),
217}
218
219/// A place a document can come from, newest last.
220enum Source<'a> {
221    Indexed(Box<Indexed<'a>>),
222    /// A run of consecutive unindexed version 2 or 3 segments.
223    Columnar(Run),
224    /// A run of consecutive version 1 segments overlaid into one layer, or
225    /// the WAL tail.
226    Flat(Arc<Layer>),
227}
228
229/// Consecutive unindexed version 2 or 3 segments, oldest first.
230struct Run {
231    views: Vec<Arc<SegmentView>>,
232}
233
234impl Run {
235    /// Whether any segment of the run holds `id` as a document or a
236    /// tombstone: either hides it in every older source.
237    fn holds(&self, id: &str) -> bool {
238        self.views.iter().any(|view| view.holds(id))
239    }
240}
241
242struct Indexed<'a> {
243    segment: RangedSegment<'a>,
244    algorithm: &'a dyn Algorithm,
245    index_path: Path,
246}
247
248/// Where a hit's attributes are: already in memory, in the data object, or
249/// in a view of a columnar run.
250enum Attrs {
251    Have(Option<serde_json::Value>),
252    Row(u32),
253    /// A row of one view of a columnar run, parsed only if it is a final hit.
254    InView {
255        view: usize,
256        row: usize,
257    },
258}
259
260/// A live candidate with its exact distance.
261struct Scored {
262    distance: f32,
263    id: String,
264    source: usize,
265    attrs: Attrs,
266}
267
268/// Group the live segments into steps, oldest first. Consecutive unindexed
269/// segments stay together, since overlaying them gives their net effect and
270/// nothing between them needs a separate shadow check.
271fn plan<'a>(q: &Query<'a>, manifest: &'a Manifest) -> Vec<Step<'a>> {
272    let live = &manifest.live_segments;
273    // The exact path, and a namespace with nothing this build can search:
274    // every segment is read flat, through the same engine.
275    if q.options.exact || !uses_indexes(manifest, q.registry) {
276        return if live.is_empty() {
277            Vec::new()
278        } else {
279            vec![Step::Flat(live)]
280        };
281    }
282    let registry: &'a dyn Registry = q.registry;
283    let mut steps = Vec::new();
284    let mut run_start = 0;
285    for (at, id) in live.iter().enumerate() {
286        let known = manifest.indexes.get(id).and_then(|entry| {
287            registry
288                .algorithm(&entry.kind)
289                .map(|algorithm| (entry.generation, algorithm))
290        });
291        if let Some((generation, algorithm)) = known {
292            if run_start < at {
293                steps.push(Step::Flat(&live[run_start..at]));
294            }
295            steps.push(Step::Indexed {
296                id,
297                generation,
298                algorithm,
299            });
300            run_start = at + 1;
301        }
302    }
303    if run_start < live.len() {
304        steps.push(Step::Flat(&live[run_start..]));
305    }
306    steps
307}
308
309/// Run the query over `manifest`, reading indexed segments in pieces and the
310/// rest whole.
311///
312/// # Errors
313///
314/// The errors of reading segments, indexes and the tail (a missing segment or
315/// index, or a fenced WAL object, is what the caller reloads the manifest for),
316/// [`ItzmaError::CorruptIndex`] for a damaged index or a row an index made up,
317/// and [`ItzmaError::ReadBudgetExceeded`].
318pub(crate) async fn run<'a>(
319    q: &Query<'a>,
320    manifest: &'a Manifest,
321    tail: impl Future<Output = Result<Arc<Layer>>>,
322) -> Result<Vec<Hit>> {
323    if q.top_k == 0 {
324        return Ok(Vec::new());
325    }
326    // A fresh bound per attempt, never reused across a stale-read retry: a
327    // bound built from the old manifest's sources could come from a
328    // document the new manifest shadows.
329    let bound = crate::bound::Bound::new(q.top_k);
330    let steps = plan(q, manifest);
331    // The tail is read alongside the segments, and it is always its own,
332    // newest source: the handle's view shares it between queries,
333    // and shadowing between it and the newest unindexed run goes through
334    // `Layer::holds`, which costs nothing.
335    let (mut sources, tail) = futures::try_join!(open_sources(q, steps), tail)?;
336    if !tail.is_empty() {
337        sources.push(Source::Flat(tail));
338    }
339
340    let sources = &sources;
341    let mut live: Vec<Scored> =
342        try_join_all((0..sources.len()).map(|at| search_source(q, sources, at, &bound)))
343            .await?
344            .into_iter()
345            .flatten()
346            .collect();
347    live.sort_by(|a, b| {
348        a.distance
349            .total_cmp(&b.distance)
350            .then_with(|| a.id.cmp(&b.id))
351    });
352    live.truncate(q.top_k);
353    finish(sources, live).await
354}
355
356async fn open_sources<'a>(q: &Query<'a>, steps: Vec<Step<'a>>) -> Result<Vec<Source<'a>>> {
357    // Indexed by position, not mapped over the owned `Step` values: a closure
358    // whose parameter type itself borrows `'a` is inferred as higher-ranked
359    // (for any lifetime), which then fails to prove the stream `Send` even
360    // though every call in fact shares the same `'a` (see `segment::read_all`
361    // for the same shape of fix with an owned id instead of a borrowed one).
362    let opened: Vec<Vec<Source<'a>>> = stream::iter(0..steps.len())
363        .map(|at| open_source(q, &steps[at]))
364        .buffered(FETCH_CONCURRENCY)
365        .try_collect()
366        .await?;
367    Ok(opened.into_iter().flatten().collect())
368}
369
370/// The sources one step opens to: one for an indexed segment; for a run of
371/// unindexed segments, a columnar run per stretch of version 2 or 3 segments and
372/// a layer per stretch of version 1 ones, in manifest order.
373async fn open_source<'a>(q: &Query<'a>, step: &Step<'a>) -> Result<Vec<Source<'a>>> {
374    match *step {
375        Step::Indexed {
376            id,
377            generation,
378            algorithm,
379        } => {
380            let segment = RangedSegment::open(
381                q.store,
382                q.namespace,
383                id,
384                q.dim,
385                q.budget,
386                q.policy,
387                q.decoded,
388            )
389            .await?;
390            Ok(vec![Source::Indexed(Box::new(Indexed {
391                segment,
392                algorithm,
393                index_path: index::index_path(q.namespace, id, generation),
394            }))])
395        }
396        Step::Flat(ids) => {
397            let views = segment::read_flat(
398                q.store,
399                q.namespace,
400                ids,
401                q.dim,
402                q.budget,
403                q.policy,
404                Lane::Query,
405                q.decoded,
406            )
407            .await?;
408            if views.is_empty() {
409                return Ok(Vec::new());
410            }
411            Ok(vec![Source::Columnar(Run { views })])
412        }
413    }
414}
415
416/// The live candidates of source `at`.
417async fn search_source(
418    q: &Query<'_>,
419    sources: &[Source<'_>],
420    at: usize,
421    bound: &crate::bound::Bound,
422) -> Result<Vec<Scored>> {
423    match &sources[at] {
424        Source::Indexed(source) => search_indexed(q, sources, at, source, bound).await,
425        Source::Columnar(run) => search_columnar(q, sources, at, run, bound).await,
426        Source::Flat(layer) => search_flat(q, sources, at, layer, bound).await,
427    }
428}
429
430/// Pull candidates from the index's cursor in growing batches, dropping
431/// those the bound proves cannot matter, running the shadow check and the
432/// predicate on new rows only, and stopping as soon as `top_k` live rows are
433/// in hand, the cursor is exhausted, or the rest of the cursor cannot beat
434/// the bound — replaces the old `Round`/`MAX_WIDENINGS`
435/// re-ask-from-scratch loop.
436async fn search_indexed(
437    q: &Query<'_>,
438    sources: &[Source<'_>],
439    at: usize,
440    source: &Indexed<'_>,
441    bound: &crate::bound::Bound,
442) -> Result<Vec<Scored>> {
443    let rows = source.segment.doc_count();
444    let probe = Probe {
445        store: q.store,
446        budget: q.budget,
447        policy: q.policy,
448        path: &source.index_path,
449        dim: q.dim,
450        rows,
451        data_size: source.segment.data_size(),
452        metric: q.metric,
453        query: q.vector,
454        want: match q.options.rerank {
455            Some(rerank) => rerank.saturating_mul(q.top_k),
456            None => usize::MAX,
457        },
458        nprobe: q.options.nprobe,
459        decoded: q.decoded,
460    };
461    let mut cursor = source.algorithm.cursor(probe).await?;
462    let mut n = probe.want;
463    let mut live: Vec<Scored> = Vec::new();
464    let mut seen: std::collections::HashSet<u32> = std::collections::HashSet::new();
465    loop {
466        let batch = cursor.next(n).await?;
467        for c in &batch.candidates {
468            if u64::from(c.row) >= rows {
469                return Err(index::corrupt(
470                    source.index_path.as_ref(),
471                    format!("the index proposed row {}, the segment has {rows}", c.row),
472                ));
473            }
474            if !seen.insert(c.row) {
475                return Err(index::corrupt(
476                    source.index_path.as_ref(),
477                    format!("the index proposed row {} more than once", c.row),
478                ));
479            }
480        }
481        let candidates: Vec<Candidate> = batch
482            .candidates
483            .into_iter()
484            .filter(|c| {
485                source
486                    .algorithm
487                    .lower_bound(&probe, c.distance)
488                    .is_none_or(|lb| !bound.beats(lb))
489            })
490            .collect();
491        let scored = evaluate_candidates(q, sources, at, source, candidates).await?;
492        bound.offer(&scored.iter().map(|s| s.distance).collect::<Vec<_>>());
493        live.extend(scored);
494        if live.len() >= q.top_k || batch.exhausted {
495            return Ok(live);
496        }
497        if let Some(rest) = batch.rest_lower_bound {
498            if bound.beats(rest) {
499                return Ok(live);
500            }
501        }
502        n = n.saturating_mul(WIDEN);
503    }
504}
505
506/// The shadow check, the predicate, and the exact rerank for one batch of
507/// fresh candidates — the body `evaluate_indexed` used to run once per
508/// widening round, now run once per cursor batch on new rows only.
509async fn evaluate_candidates(
510    q: &Query<'_>,
511    sources: &[Source<'_>],
512    at: usize,
513    source: &Indexed<'_>,
514    candidates: Vec<Candidate>,
515) -> Result<Vec<Scored>> {
516    let rows: Vec<u32> = candidates.iter().map(|c| c.row).collect();
517    let ids = source.segment.ids_of(&rows).await?;
518    let live = unshadowed(sources, at, &ids).await?;
519
520    let kept: Vec<(u32, String)> = rows
521        .into_iter()
522        .zip(ids)
523        .zip(live)
524        .filter_map(|(pair, live)| live.then_some(pair))
525        .collect();
526    // Test the predicate before fetching vectors, so a selective filter does
527    // not pay for rows it throws away. The attributes fetched here stay on the
528    // hit and `finish` does not fetch them again.
529    let (kept, attrs): (Vec<(u32, String)>, Vec<Attrs>) = match q.filter() {
530        None => {
531            let attrs = kept.iter().map(|(row, _)| Attrs::Row(*row)).collect();
532            (kept, attrs)
533        }
534        Some(predicate) => {
535            let rows: Vec<u32> = kept.iter().map(|(row, _)| *row).collect();
536            // A version 3 segment decides from its zone maps and the
537            // predicate's columns, and the attributes of the rows that pass
538            // wait for `finish`.
539            match source.segment.eligible_of(predicate, &rows).await? {
540                Some(decided) => kept
541                    .into_iter()
542                    .zip(decided)
543                    .filter(|(_, eligible)| *eligible)
544                    .map(|(pair, _)| {
545                        let attrs = Attrs::Row(pair.0);
546                        (pair, attrs)
547                    })
548                    .unzip(),
549                None => {
550                    let fetched = source.segment.attrs_of(&rows).await?;
551                    kept.into_iter()
552                        .zip(fetched)
553                        .filter(|(_, attrs)| predicate.matches(attrs.as_ref()))
554                        .map(|(pair, attrs)| (pair, Attrs::Have(attrs)))
555                        .unzip()
556                }
557            }
558        }
559    };
560    let kept_rows: Vec<u32> = kept.iter().map(|(row, _)| *row).collect();
561    let vectors = source.segment.vectors_of(&kept_rows).await?;
562    Ok(kept
563        .into_iter()
564        .enumerate()
565        .zip(attrs)
566        .map(|((i, (_, id)), attrs)| Scored {
567            distance: search::distance(q.metric, q.vector, vectors.row(i)),
568            id,
569            source: at,
570            attrs,
571        })
572        .collect())
573}
574
575/// The same shape for a layer held in memory, whose distances are already
576/// exact: sort every filtered document once, then slice growing batches off
577/// the front, stopping early the same three ways `search_indexed` does.
578/// Order used to rank `(distance, doc)` pairs in [`search_flat`]: closest
579/// first, ties by id.
580fn by_distance_then_id(
581    a: &(f32, &crate::document::Document),
582    b: &(f32, &crate::document::Document),
583) -> std::cmp::Ordering {
584    a.0.total_cmp(&b.0).then_with(|| a.1.id.cmp(&b.1.id))
585}
586
587async fn search_flat(
588    q: &Query<'_>,
589    sources: &[Source<'_>],
590    at: usize,
591    layer: &Arc<Layer>,
592    bound: &crate::bound::Bound,
593) -> Result<Vec<Scored>> {
594    // Distances computed once; each widening round *partitions* the
595    // not-yet-returned suffix (`select_nth_unstable_by`, O(remaining)) for
596    // just the rows this round newly needs, then sorts only that small new
597    // slice — never a full O(N log N) sort of the whole filtered layer up
598    // front. A full sort here was a real, measured regression (up to +280%
599    // at 20k rows on an unindexed/flat query), since the common case needs
600    // only `top_k` rows, not every row in order.
601    let (owned, query, filter, metric) = (
602        layer.clone(),
603        q.vector.to_vec(),
604        q.filter().cloned(),
605        q.metric,
606    );
607    let cost = Cost::Distances {
608        rows: layer.doc_count(),
609        dim: q.vector.len(),
610    };
611    let distances = cpu::run(Lane::Query, cost, move || {
612        flat_distances(&owned, metric, &query, filter.as_ref())
613    })
614    .await;
615    // `Layer::docs` keeps its order while the layer is unchanged (its
616    // contract), so this second pass lines up with the one on the pool.
617    debug_assert_eq!(distances.len(), layer.doc_count());
618    let mut scored: Vec<(f32, &crate::document::Document)> = layer
619        .docs()
620        .zip(distances)
621        .filter_map(|(doc, distance)| distance.map(|d| (d, doc)))
622        .collect();
623
624    let mut live: Vec<Scored> = Vec::new();
625    let mut returned = 0usize;
626    let mut n = q.top_k;
627    loop {
628        let take = n.min(scored.len());
629        if take > returned {
630            scored[returned..].select_nth_unstable_by(take - returned - 1, by_distance_then_id);
631            scored[returned..take].sort_by(by_distance_then_id);
632        }
633        let batch = &scored[returned..take];
634        let ids: Vec<String> = batch.iter().map(|(_, doc)| doc.id.clone()).collect();
635        let shadow = unshadowed(sources, at, &ids).await?;
636        let scored_batch: Vec<Scored> = batch
637            .iter()
638            .zip(shadow)
639            .filter(|(_, live)| *live)
640            .map(|((distance, doc), _)| Scored {
641                distance: *distance,
642                id: doc.id.clone(),
643                source: at,
644                attrs: Attrs::Have(doc.attrs.clone()),
645            })
646            .collect();
647        bound.offer(&scored_batch.iter().map(|s| s.distance).collect::<Vec<_>>());
648        returned = take;
649        live.extend(scored_batch);
650        let exhausted = returned >= scored.len();
651        if live.len() >= q.top_k || exhausted {
652            return Ok(live);
653        }
654        // The rows past `returned` are in no order after the partial select;
655        // the batch's largest distance is a true lower bound for all of them.
656        let rest_lower_bound = scored[returned - 1].0;
657        if bound.beats(rest_lower_bound) {
658            return Ok(live);
659        }
660        n = n.saturating_mul(WIDEN);
661    }
662}
663
664/// Rows per span of a columnar scan handed to one pool task: the same
665/// constant as the layer path, so neither depends on the thread count.
666const SPAN: usize = cpu::FLAT_CHUNK;
667
668/// The distance to every surviving row of `views` that `filter` keeps, as
669/// (distance, view, row), views in order and rows ascending in each.
670/// Survivors first, then the predicate (attributes parsed only for
671/// survivors), then the kernel on the row's slice of the matrix.
672///
673/// # Errors
674///
675/// [`ItzmaError::CorruptSegment`] for attribute JSON that does not parse.
676pub(crate) fn columnar_distances(
677    views: &[Arc<SegmentView>],
678    metric: Metric,
679    query: &[f32],
680    filter: Option<&Predicate>,
681) -> Result<Vec<(f32, usize, usize)>> {
682    // One segment shadows nothing of its own: every row survives.
683    let live = if views.len() == 1 {
684        None
685    } else {
686        let sorted: Vec<crate::layer::SortedIds<'_>> =
687            views.iter().map(|view| view.sorted_ids()).collect();
688        Some(crate::layer::survivors(&sorted))
689    };
690    let spans: Vec<(usize, usize, usize)> = views
691        .iter()
692        .enumerate()
693        .flat_map(|(v, view)| {
694            (0..view.rows())
695                .step_by(SPAN)
696                .map(move |start| (v, start, (start + SPAN).min(view.rows())))
697        })
698        .collect();
699    let chunks = cpu::chunked(&spans, 1, |chunk| {
700        let mut out = Vec::new();
701        for &(v, start, end) in chunk {
702            for row in start..end {
703                if live.as_ref().is_some_and(|live| !live[v].get(row)) {
704                    continue;
705                }
706                if let Some(predicate) = filter {
707                    if !predicate.matches(views[v].attrs(row)?.as_ref()) {
708                        continue;
709                    }
710                }
711                out.push((
712                    search::distance(metric, query, views[v].vector(row)),
713                    v,
714                    row,
715                ));
716            }
717        }
718        Ok::<_, ItzmaError>(out)
719    });
720    let mut out = Vec::with_capacity(
721        chunks
722            .iter()
723            .map(|chunk| chunk.as_ref().map_or(0, Vec::len))
724            .sum(),
725    );
726    for chunk in chunks {
727        out.extend(chunk?);
728    }
729    Ok(out)
730}
731
732/// [`search_flat`]'s loop over a columnar run: distances on the pool once,
733/// then growing batches off the front, each checked against newer sources.
734async fn search_columnar(
735    q: &Query<'_>,
736    sources: &[Source<'_>],
737    at: usize,
738    run: &Run,
739    bound: &crate::bound::Bound,
740) -> Result<Vec<Scored>> {
741    // The views are `Arc` clones: dropping them on the pool frees nothing,
742    // the run keeps them (the rule).
743    let (views, query, filter, metric) = (
744        run.views.clone(),
745        q.vector.to_vec(),
746        q.filter().cloned(),
747        q.metric,
748    );
749    let cost = Cost::Distances {
750        rows: run.views.iter().map(|view| view.rows()).sum(),
751        dim: q.vector.len(),
752    };
753    let mut scored = cpu::run(Lane::Query, cost, move || {
754        columnar_distances(&views, metric, &query, filter.as_ref())
755    })
756    .await?;
757    let id = |&(_, v, row): &(f32, usize, usize)| run.views[v].id(row);
758    let by = |a: &(f32, usize, usize), b: &(f32, usize, usize)| {
759        a.0.total_cmp(&b.0).then_with(|| id(a).cmp(id(b)))
760    };
761
762    let mut live: Vec<Scored> = Vec::new();
763    let mut returned = 0usize;
764    let mut n = q.top_k;
765    loop {
766        let take = n.min(scored.len());
767        if take > returned {
768            scored[returned..].select_nth_unstable_by(take - returned - 1, by);
769            scored[returned..take].sort_by(by);
770        }
771        let batch = &scored[returned..take];
772        let ids: Vec<String> = batch.iter().map(|s| id(s).to_owned()).collect();
773        let shadow = unshadowed(sources, at, &ids).await?;
774        let mut scored_batch = Vec::new();
775        for (&(distance, v, row), (id, live)) in batch.iter().zip(ids.into_iter().zip(shadow)) {
776            if live {
777                scored_batch.push(Scored {
778                    distance,
779                    id,
780                    source: at,
781                    attrs: Attrs::InView { view: v, row },
782                });
783            }
784        }
785        bound.offer(&scored_batch.iter().map(|s| s.distance).collect::<Vec<_>>());
786        returned = take;
787        live.extend(scored_batch);
788        if live.len() >= q.top_k || returned >= scored.len() {
789            return Ok(live);
790        }
791        // The rows past `returned` are in no order after the partial select;
792        // the batch's largest distance is a true lower bound for all of them.
793        let rest_lower_bound = scored[returned - 1].0;
794        if bound.beats(rest_lower_bound) {
795            return Ok(live);
796        }
797        n = n.saturating_mul(WIDEN);
798    }
799}
800
801/// The distance from `query` to every document of `layer`, in `layer.docs()`
802/// order, `None` where `filter` drops the document. Chunked so that on a pool
803/// thread the chunks run on several cores; a chunk is a run of
804/// documents in that order, so the result is the same either way.
805pub(crate) fn flat_distances(
806    layer: &Layer,
807    metric: Metric,
808    query: &[f32],
809    filter: Option<&Predicate>,
810) -> Vec<Option<f32>> {
811    let docs: Vec<&crate::document::Document> = layer.docs().collect();
812    distances_of(&docs, metric, query, filter)
813}
814
815/// [`flat_distances`] over a list of documents, in its order.
816fn distances_of(
817    docs: &[&crate::document::Document],
818    metric: Metric,
819    query: &[f32],
820    filter: Option<&Predicate>,
821) -> Vec<Option<f32>> {
822    let chunks = cpu::chunked(docs, cpu::FLAT_CHUNK, |chunk| {
823        chunk
824            .iter()
825            .map(|doc| {
826                filter
827                    .is_none_or(|p| p.matches(doc.attrs.as_ref()))
828                    .then(|| search::distance(metric, query, &doc.vector))
829            })
830            .collect::<Vec<_>>()
831    });
832    let mut out = Vec::with_capacity(docs.len());
833    for chunk in chunks {
834        out.extend(chunk);
835    }
836    out
837}
838
839/// For each of `ids`, proposed by source `at`: whether it is still the live
840/// version, that is, no newer source holds the id as a document or a tombstone.
841async fn unshadowed(sources: &[Source<'_>], at: usize, ids: &[String]) -> Result<Vec<bool>> {
842    // Owned ids: a closure over `&String` is inferred as higher-ranked, which
843    // makes the stream not provably `Send` (see `segment::read_all`).
844    stream::iter(ids.iter().cloned())
845        .map(|id| async move { is_live(sources, at, &id).await })
846        .buffered(FETCH_CONCURRENCY)
847        .try_collect()
848        .await
849}
850
851async fn is_live(sources: &[Source<'_>], at: usize, id: &str) -> Result<bool> {
852    let newer = &sources[at + 1..];
853    // Runs and layers in memory first: they cost no request.
854    if newer.iter().any(|source| match source {
855        Source::Flat(layer) => layer.holds(id),
856        Source::Columnar(run) => run.holds(id),
857        Source::Indexed(_) => false,
858    }) {
859        return Ok(false);
860    }
861    for source in newer {
862        if let Source::Indexed(newer) = source {
863            if newer.segment.holds(id).await? != Held::No {
864                return Ok(false);
865            }
866        }
867    }
868    Ok(true)
869}
870
871/// Fetch the attributes the final hits still lack, one request per block, and
872/// build the hits.
873async fn finish(sources: &[Source<'_>], live: Vec<Scored>) -> Result<Vec<Hit>> {
874    let mut wanted: HashMap<usize, Vec<u32>> = HashMap::new();
875    for hit in &live {
876        if let Attrs::Row(row) = hit.attrs {
877            wanted.entry(hit.source).or_default().push(row);
878        }
879    }
880    let fetched = try_join_all(
881        wanted
882            .into_iter()
883            .map(|(at, rows)| fetch_attrs(sources, at, rows)),
884    )
885    .await?;
886    let mut attrs: HashMap<(usize, u32), Option<serde_json::Value>> = HashMap::new();
887    for (at, rows, values) in fetched {
888        attrs.extend(rows.into_iter().zip(values).map(|(row, v)| ((at, row), v)));
889    }
890    live.into_iter()
891        .map(|hit| {
892            let attrs = match hit.attrs {
893                Attrs::Have(value) => value,
894                Attrs::Row(row) => attrs.remove(&(hit.source, row)).flatten(),
895                Attrs::InView { view, row } => match &sources[hit.source] {
896                    Source::Columnar(run) => run.views[view].attrs(row)?,
897                    _ => None,
898                },
899            };
900            Ok(Hit {
901                attrs,
902                id: hit.id,
903                distance: hit.distance,
904            })
905        })
906        .collect()
907}
908
909async fn fetch_attrs(
910    sources: &[Source<'_>],
911    at: usize,
912    rows: Vec<u32>,
913) -> Result<(usize, Vec<u32>, Vec<Option<serde_json::Value>>)> {
914    let Source::Indexed(source) = &sources[at] else {
915        return Ok((at, rows, Vec::new()));
916    };
917    let values = source.segment.attrs_of(&rows).await?;
918    Ok((at, rows, values))
919}
920
921/// Unit tests for [`Indexed::propose`] with a stub kind, so the engine's own
922/// checks on what an algorithm returns are tested without a real index object:
923/// nothing here names SQ8. The engine tests that need a real, published index
924/// are integration tests in `tests/query.rs`.
925#[cfg(test)]
926mod tests {
927    use futures::FutureExt;
928    use futures::future::BoxFuture;
929    use object_store::ObjectStoreExt;
930    use object_store::memory::InMemory;
931
932    use super::*;
933    use crate::document::{Document, WalOp};
934    use crate::segment::{self, SegmentView};
935
936    const DIM: usize = 2;
937
938    fn doc(id: &str, x: f32, y: f32) -> Document {
939        Document {
940            id: id.into(),
941            vector: vec![x, y],
942            attrs: None,
943            sparse: None,
944        }
945    }
946
947    /// `n` documents with the same vector of length `dim`, every other one
948    /// `active`, so every distance ties and the filter drops half.
949    fn layer_of_identical(n: usize, dim: usize) -> Layer {
950        let mut layer = Layer::new();
951        for i in 0..n {
952            layer.apply(WalOp::Upsert(Document {
953                id: format!("d{i:06}"),
954                vector: vec![1.0; dim],
955                attrs: Some(serde_json::json!({ "active": i % 2 == 0 })),
956                sparse: None,
957            }));
958        }
959        layer
960    }
961
962    fn view_of(layer: &Layer, dim: usize) -> Arc<SegmentView> {
963        let bytes = segment::encode_as(layer, dim, 2).unwrap();
964        Arc::new(SegmentView::decode("p", bytes, dim).unwrap())
965    }
966
967    /// The distance from `query` to every document of `layer` that `filter`
968    /// keeps, by id: the reference the columnar scan is held to.
969    fn reference(layer: &Layer, query: &[f32], filter: Option<&Predicate>) -> Vec<(String, f32)> {
970        let mut out: Vec<(String, f32)> = layer
971            .docs()
972            .filter(|d| filter.is_none_or(|p| p.matches(d.attrs.as_ref())))
973            .map(|d| (d.id.clone(), search::distance(Metric::L2, query, &d.vector)))
974            .collect();
975        out.sort_by(|a, b| a.0.cmp(&b.0));
976        out
977    }
978
979    /// Random runs: the columnar distances are the flat ones over the
980    /// overlaid layer, as (id, distance) sets, with and without a filter.
981    #[test]
982    fn columnar_distances_equal_flat_distances_over_the_overlay() {
983        let dim = 4;
984        let mut state = 0x0043_0005_u64;
985        let mut next = move |n: u64| {
986            state ^= state << 13;
987            state ^= state >> 7;
988            state ^= state << 17;
989            state % n
990        };
991        let filter = Predicate::is_true("active");
992        for case in 0..50 {
993            let layers: Vec<Layer> = (0..1 + next(4))
994                .map(|s| {
995                    let mut layer = Layer::new();
996                    for i in 0..next(700) {
997                        let id = format!("i{:04}", next(500));
998                        if next(5) == 0 {
999                            layer.apply(WalOp::Delete(id));
1000                        } else {
1001                            let x = (s * 1000 + i) as f32;
1002                            layer.apply(WalOp::Upsert(Document {
1003                                id,
1004                                vector: vec![x, -x, 0.5, 1.0],
1005                                attrs: Some(serde_json::json!({ "active": next(2) == 0 })),
1006                                sparse: None,
1007                            }));
1008                        }
1009                    }
1010                    layer
1011                })
1012                .collect();
1013            let views: Vec<Arc<SegmentView>> = layers.iter().map(|l| view_of(l, dim)).collect();
1014            let mut overlaid = Layer::new();
1015            for l in layers.iter().cloned() {
1016                overlaid.overlay(l);
1017            }
1018            let query = [3.0, 1.0, 0.0, -2.0];
1019            for filter in [None, Some(&filter)] {
1020                let mut got: Vec<(String, f32)> =
1021                    columnar_distances(&views, Metric::L2, &query, filter)
1022                        .unwrap()
1023                        .into_iter()
1024                        .map(|(d, v, row)| (views[v].id(row).to_owned(), d))
1025                        .collect();
1026                got.sort_by(|a, b| a.0.cmp(&b.0));
1027                assert_eq!(got, reference(&overlaid, &query, filter), "case {case}");
1028            }
1029        }
1030    }
1031
1032    #[tokio::test]
1033    async fn columnar_distances_on_the_pool_equal_the_inline_ones_across_chunks() {
1034        let dim = 64;
1035        let layer = layer_of_identical(crate::cpu::FLAT_CHUNK * 2 + 7, dim);
1036        let views = vec![view_of(&layer, dim)];
1037        let query = vec![0.5f32; dim];
1038        for filter in [None, Some(Predicate::is_true("active"))] {
1039            let inline = columnar_distances(&views, Metric::L2, &query, filter.as_ref()).unwrap();
1040            let (v, q, f) = (views.clone(), query.clone(), filter.clone());
1041            let cost = crate::cpu::Cost::Distances {
1042                rows: layer.doc_count(),
1043                dim,
1044            };
1045            let pooled = crate::cpu::run(crate::cpu::Lane::Query, cost, move || {
1046                columnar_distances(&v, Metric::L2, &q, f.as_ref())
1047            })
1048            .await
1049            .unwrap();
1050            assert_eq!(pooled, inline);
1051            let expected = if filter.is_some() {
1052                layer.doc_count().div_ceil(2)
1053            } else {
1054                layer.doc_count()
1055            };
1056            assert_eq!(inline.len(), expected);
1057        }
1058    }
1059
1060    #[tokio::test]
1061    async fn flat_distances_on_the_pool_equal_the_inline_ones_across_chunks() {
1062        let dim = 64;
1063        let layer = Arc::new(layer_of_identical(crate::cpu::FLAT_CHUNK * 2 + 7, dim));
1064        let query = vec![0.5f32; dim];
1065        let filter = Predicate::is_true("active");
1066        for filter in [None, Some(filter)] {
1067            let inline = flat_distances(&layer, Metric::L2, &query, filter.as_ref());
1068            assert_eq!(inline.len(), layer.doc_count());
1069            let (l, q, f) = (layer.clone(), query.clone(), filter.clone());
1070            let cost = crate::cpu::Cost::Distances {
1071                rows: layer.doc_count(),
1072                dim,
1073            };
1074            let pooled = crate::cpu::run(crate::cpu::Lane::Query, cost, move || {
1075                flat_distances(&l, Metric::L2, &q, f.as_ref())
1076            })
1077            .await;
1078            assert_eq!(pooled, inline);
1079            let kept = inline.iter().filter(|d| d.is_some()).count();
1080            let expected = if filter.is_some() {
1081                layer.doc_count().div_ceil(2)
1082            } else {
1083                layer.doc_count()
1084            };
1085            assert_eq!(kept, expected);
1086        }
1087    }
1088
1089    /// A version 2 segment of 3 documents at rows 0, 1, 2, written under `docs`.
1090    async fn small_segment(store: &dyn ObjectStore) -> String {
1091        let mut layer = Layer::new();
1092        for d in [doc("a", 0.0, 0.0), doc("b", 1.0, 0.0), doc("c", 2.0, 0.0)] {
1093            layer.apply(WalOp::Upsert(d));
1094        }
1095        layer.drop_tombstones();
1096        let id = segment::segment_id(1, 1);
1097        let bytes = segment::encode_as(&layer, DIM, 2).expect("encode");
1098        store
1099            .put(&segment::segment_path("docs", &id), bytes.into())
1100            .await
1101            .expect("put segment");
1102        id
1103    }
1104
1105    /// An algorithm that returns exactly the rows it is built with, ignoring
1106    /// `want`: good enough to stand in for a real kind, and easy to make lie,
1107    /// since `propose`'s own dedup and cut have something to do.
1108    struct Stub(Vec<Candidate>);
1109
1110    impl Algorithm for Stub {
1111        fn search<'a>(&'a self, probe: &'a Probe<'_>) -> BoxFuture<'a, Result<Vec<Candidate>>> {
1112            let _ = probe;
1113            let rows = self.0.clone();
1114            async move { Ok(rows) }.boxed()
1115        }
1116    }
1117
1118    /// Build the pieces `Indexed::propose` needs against `id`'s segment. The
1119    /// query is a placeholder: `propose` never looks past what the stub gives it.
1120    fn probe_query<'a>(
1121        store: &'a dyn ObjectStore,
1122        vector: &'a [f32],
1123        budget: &'a ReadBudget,
1124        policy: &'a FetchPolicy,
1125        options: &'a QueryOptions,
1126    ) -> Query<'a> {
1127        Query {
1128            store,
1129            namespace: "docs",
1130            dim: DIM,
1131            metric: Metric::L2,
1132            vector,
1133            top_k: 1,
1134            options,
1135            budget,
1136            policy,
1137            registry: &Builtin,
1138            decoded: None,
1139        }
1140    }
1141
1142    #[tokio::test]
1143    async fn a_row_past_the_segment_is_corrupt_index() {
1144        let store = InMemory::new();
1145        let id = small_segment(&store).await;
1146        let budget = ReadBudget::unlimited();
1147        let policy = FetchPolicy::local();
1148        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1149            .await
1150            .expect("open");
1151        let stub = Stub(vec![Candidate {
1152            row: 3, // the segment only has rows 0..3
1153            distance: 0.0,
1154        }]);
1155        let path = index::index_path("docs", &id, 1);
1156        let probe = Probe {
1157            store: &store,
1158            budget: &budget,
1159            policy: &policy,
1160            path: &path,
1161            dim: DIM,
1162            rows: segment.doc_count(),
1163            data_size: segment.data_size(),
1164            metric: Metric::L2,
1165            query: &[0.0, 0.0],
1166            want: 1,
1167            nprobe: None,
1168            decoded: None,
1169        };
1170
1171        // `DefaultCursor` is what now owns the checks `Indexed::propose` used
1172        // to run on whatever an algorithm hands back.
1173        let mut cursor = stub.cursor(probe).await.expect("cursor");
1174        let err = cursor.next(1).await.unwrap_err();
1175        assert!(
1176            matches!(err, ItzmaError::CorruptIndex { .. }),
1177            "a dishonest kind must not be trusted: {err:?}"
1178        );
1179    }
1180
1181    #[tokio::test]
1182    async fn a_filter_that_matches_no_candidate_leaves_no_live_rows() {
1183        let store = InMemory::new();
1184        let id = small_segment(&store).await;
1185        let budget = ReadBudget::unlimited();
1186        let policy = FetchPolicy::local();
1187        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1188            .await
1189            .expect("open");
1190        let stub = Stub((0..3).map(|row| Candidate { row, distance: 0.0 }).collect());
1191        let sources = vec![Source::Indexed(Box::new(Indexed {
1192            segment,
1193            algorithm: &stub,
1194            index_path: index::index_path("docs", &id, 1),
1195        }))];
1196
1197        // The documents have no attributes, so no one of them is `x = true`.
1198        let none = QueryOptions::default().filter(Some(Predicate::is_true("x")));
1199        let q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &none);
1200        let bound = crate::bound::Bound::new(q.top_k);
1201        let live = search_source(&q, &sources, 0, &bound)
1202            .await
1203            .expect("search");
1204        assert!(live.is_empty());
1205
1206        // All of them are `x is null`, and the attributes fetched for the test
1207        // stay on the hit so `finish` does not fetch them again.
1208        let all = QueryOptions::default().filter(Some(Predicate::IsNull("x".into())));
1209        let q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &all);
1210        let bound = crate::bound::Bound::new(q.top_k);
1211        let live = search_source(&q, &sources, 0, &bound)
1212            .await
1213            .expect("search");
1214        assert_eq!(live.len(), 3);
1215        assert!(
1216            live.iter()
1217                .all(|hit| matches!(hit.attrs, Attrs::Have(None)))
1218        );
1219
1220        let plain = QueryOptions::default();
1221        let q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &plain);
1222        let bound = crate::bound::Bound::new(q.top_k);
1223        let live = search_source(&q, &sources, 0, &bound)
1224            .await
1225            .expect("search");
1226        assert_eq!(live.len(), 3, "without a filter all three are live");
1227        assert!(
1228            live.iter().all(|hit| matches!(hit.attrs, Attrs::Row(_))),
1229            "and their attributes are left for `finish`"
1230        );
1231    }
1232
1233    #[tokio::test]
1234    async fn asking_for_every_row_gives_every_row_even_if_the_algorithm_cannot_reach_one() {
1235        // A graph index can leave a row with no way in. The widest ask is the
1236        // last resort of the widening loop, so it has to mean every row, or a
1237        // filter that only that row matches would find nothing.
1238        let store = InMemory::new();
1239        let id = small_segment(&store).await;
1240        let budget = ReadBudget::unlimited();
1241        let policy = FetchPolicy::local();
1242        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1243            .await
1244            .expect("open");
1245        let stub = Stub(vec![Candidate {
1246            row: 0,
1247            distance: 1.0,
1248        }]);
1249        let path = index::index_path("docs", &id, 1);
1250        let probe = Probe {
1251            store: &store,
1252            budget: &budget,
1253            policy: &policy,
1254            path: &path,
1255            dim: DIM,
1256            rows: segment.doc_count(),
1257            data_size: segment.data_size(),
1258            metric: Metric::L2,
1259            query: &[0.0, 0.0],
1260            want: usize::MAX,
1261            nprobe: None,
1262            decoded: None,
1263        };
1264
1265        let mut cursor = stub.cursor(probe).await.expect("cursor");
1266        let rows: Vec<u32> = cursor
1267            .next(usize::MAX)
1268            .await
1269            .expect("next")
1270            .candidates
1271            .iter()
1272            .map(|c| c.row)
1273            .collect();
1274        assert_eq!(rows, [0, 1, 2], "the reachable row first, then the rest");
1275    }
1276
1277    #[tokio::test]
1278    async fn an_index_that_gave_less_than_asked_is_next_asked_for_every_row() {
1279        // An index that proposed fewer rows than `want` returns the same rows for
1280        // any bigger `want` (it only probes some partitions), so the next ask has
1281        // to be for every row, not for eight times as many, twice more, in vain.
1282        struct Counting(std::sync::atomic::AtomicUsize);
1283        impl Algorithm for Counting {
1284            fn search<'a>(&'a self, probe: &'a Probe<'_>) -> BoxFuture<'a, Result<Vec<Candidate>>> {
1285                let _ = probe;
1286                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1287                async move {
1288                    Ok(vec![Candidate {
1289                        row: 0,
1290                        distance: 0.0,
1291                    }])
1292                }
1293                .boxed()
1294            }
1295        }
1296
1297        let store = InMemory::new();
1298        let id = small_segment(&store).await;
1299        let budget = ReadBudget::unlimited();
1300        let policy = FetchPolicy::local();
1301        let options = QueryOptions::default();
1302        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1303            .await
1304            .expect("open");
1305        let counting = Counting(std::sync::atomic::AtomicUsize::new(0));
1306        let sources = vec![Source::Indexed(Box::new(Indexed {
1307            segment,
1308            algorithm: &counting,
1309            index_path: index::index_path("docs", &id, 1),
1310        }))];
1311        let mut q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &options);
1312        q.top_k = 5;
1313
1314        let bound = crate::bound::Bound::new(q.top_k);
1315        let live = search_source(&q, &sources, 0, &bound)
1316            .await
1317            .expect("search");
1318        assert_eq!(live.len(), 3, "the fill-in reaches every row");
1319        assert_eq!(
1320            counting.0.load(std::sync::atomic::Ordering::SeqCst),
1321            2,
1322            "one ask for a shortlist, one for every row"
1323        );
1324    }
1325
1326    #[tokio::test]
1327    async fn duplicate_rows_count_once_and_extra_rows_are_cut() {
1328        let store = InMemory::new();
1329        let id = small_segment(&store).await;
1330        let budget = ReadBudget::unlimited();
1331        let policy = FetchPolicy::local();
1332        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1333            .await
1334            .expect("open");
1335        let stub = Stub(vec![
1336            Candidate {
1337                row: 1,
1338                distance: 5.0,
1339            },
1340            Candidate {
1341                row: 1,
1342                distance: 5.0,
1343            }, // repeated: counts once
1344            Candidate {
1345                row: 0,
1346                distance: 1.0,
1347            },
1348            Candidate {
1349                row: 2,
1350                distance: 9.0,
1351            }, // more than `want`: cut
1352        ]);
1353        let path = index::index_path("docs", &id, 1);
1354        let probe = Probe {
1355            store: &store,
1356            budget: &budget,
1357            policy: &policy,
1358            path: &path,
1359            dim: DIM,
1360            rows: segment.doc_count(),
1361            data_size: segment.data_size(),
1362            metric: Metric::L2,
1363            query: &[0.0, 0.0],
1364            want: 3,
1365            nprobe: None,
1366            decoded: None,
1367        };
1368
1369        // `want` matches the number of distinct rows, so a duplicate that
1370        // survived would show up in the result rather than being cut by
1371        // truncation alone.
1372        let found = stub
1373            .cursor(probe)
1374            .await
1375            .expect("cursor")
1376            .next(3)
1377            .await
1378            .expect("next")
1379            .candidates;
1380        assert_eq!(
1381            found,
1382            vec![
1383                Candidate {
1384                    row: 0,
1385                    distance: 1.0
1386                },
1387                Candidate {
1388                    row: 1,
1389                    distance: 5.0
1390                },
1391                Candidate {
1392                    row: 2,
1393                    distance: 9.0
1394                },
1395            ]
1396        );
1397    }
1398
1399    /// Regression: a cursor that repeats a row across batches is
1400    /// `CorruptIndex`. A cursor's own internal dedup (`DefaultCursor`'s
1401    /// `returned` set, `Sq8Cursor`'s drain) guards against this for the
1402    /// two cursors this crate ships, but `search_indexed`'s own `seen`
1403    /// check is what the engine actually relies on — this test drives
1404    /// that check directly with a dishonest `Cursor` that repeats a row
1405    /// across two `next` calls, bypassing both real cursors entirely.
1406    #[tokio::test]
1407    async fn a_cursor_that_repeats_a_row_across_batches_is_corrupt_index() {
1408        struct RepeatsRowZero;
1409        impl Algorithm for RepeatsRowZero {
1410            fn search<'a>(&'a self, probe: &'a Probe<'_>) -> BoxFuture<'a, Result<Vec<Candidate>>> {
1411                let _ = probe;
1412                async move { Ok(Vec::new()) }.boxed()
1413            }
1414
1415            fn cursor<'a>(
1416                &'a self,
1417                probe: Probe<'a>,
1418            ) -> BoxFuture<'a, Result<Box<dyn index::Cursor + 'a>>> {
1419                struct Dishonest(u32);
1420                impl index::Cursor for Dishonest {
1421                    fn next<'a>(&'a mut self, n: usize) -> BoxFuture<'a, Result<index::Batch>> {
1422                        let _ = n;
1423                        let row = self.0;
1424                        self.0 += 1; // never actually advances past row 0
1425                        async move {
1426                            Ok(index::Batch {
1427                                candidates: vec![Candidate {
1428                                    row: 0, // the same row, every batch
1429                                    distance: row as f32,
1430                                }],
1431                                rest_lower_bound: None,
1432                                exhausted: false,
1433                            })
1434                        }
1435                        .boxed()
1436                    }
1437                }
1438                let _ = probe;
1439                async move { Ok(Box::new(Dishonest(0)) as Box<dyn index::Cursor>) }.boxed()
1440            }
1441        }
1442
1443        let store = InMemory::new();
1444        let id = small_segment(&store).await;
1445        let budget = ReadBudget::unlimited();
1446        let policy = FetchPolicy::local();
1447        // rerank 1 makes want = 1 per batch, forcing a second next() call.
1448        let options = QueryOptions::default().rerank(Some(1));
1449        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1450            .await
1451            .expect("open");
1452        let dishonest = RepeatsRowZero;
1453        let sources = vec![Source::Indexed(Box::new(Indexed {
1454            segment,
1455            algorithm: &dishonest,
1456            index_path: index::index_path("docs", &id, 1),
1457        }))];
1458        let mut q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &options);
1459        q.top_k = 3; // more than the dishonest cursor will ever truly deliver
1460
1461        let bound = crate::bound::Bound::new(q.top_k);
1462        let err = match search_source(&q, &sources, 0, &bound).await {
1463            Ok(_) => panic!("a cursor that repeats a row across batches must not be trusted"),
1464            Err(e) => e,
1465        };
1466        assert!(
1467            matches!(err, ItzmaError::CorruptIndex { .. }),
1468            "a cursor that repeats a row across batches must not be trusted: {err:?}"
1469        );
1470    }
1471}