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            let fetched = source.segment.attrs_of(&rows).await?;
537            kept.into_iter()
538                .zip(fetched)
539                .filter(|(_, attrs)| predicate.matches(attrs.as_ref()))
540                .map(|(pair, attrs)| (pair, Attrs::Have(attrs)))
541                .unzip()
542        }
543    };
544    let kept_rows: Vec<u32> = kept.iter().map(|(row, _)| *row).collect();
545    let vectors = source.segment.vectors_of(&kept_rows).await?;
546    Ok(kept
547        .into_iter()
548        .enumerate()
549        .zip(attrs)
550        .map(|((i, (_, id)), attrs)| Scored {
551            distance: search::distance(q.metric, q.vector, vectors.row(i)),
552            id,
553            source: at,
554            attrs,
555        })
556        .collect())
557}
558
559/// The same shape for a layer held in memory, whose distances are already
560/// exact: sort every filtered document once, then slice growing batches off
561/// the front, stopping early the same three ways `search_indexed` does.
562/// Order used to rank `(distance, doc)` pairs in [`search_flat`]: closest
563/// first, ties by id.
564fn by_distance_then_id(
565    a: &(f32, &crate::document::Document),
566    b: &(f32, &crate::document::Document),
567) -> std::cmp::Ordering {
568    a.0.total_cmp(&b.0).then_with(|| a.1.id.cmp(&b.1.id))
569}
570
571async fn search_flat(
572    q: &Query<'_>,
573    sources: &[Source<'_>],
574    at: usize,
575    layer: &Arc<Layer>,
576    bound: &crate::bound::Bound,
577) -> Result<Vec<Scored>> {
578    // Distances computed once; each widening round *partitions* the
579    // not-yet-returned suffix (`select_nth_unstable_by`, O(remaining)) for
580    // just the rows this round newly needs, then sorts only that small new
581    // slice — never a full O(N log N) sort of the whole filtered layer up
582    // front. A full sort here was a real, measured regression (up to +280%
583    // at 20k rows on an unindexed/flat query), since the common case needs
584    // only `top_k` rows, not every row in order.
585    let (owned, query, filter, metric) = (
586        layer.clone(),
587        q.vector.to_vec(),
588        q.filter().cloned(),
589        q.metric,
590    );
591    let cost = Cost::Distances {
592        rows: layer.doc_count(),
593        dim: q.vector.len(),
594    };
595    let distances = cpu::run(Lane::Query, cost, move || {
596        flat_distances(&owned, metric, &query, filter.as_ref())
597    })
598    .await;
599    // `Layer::docs` keeps its order while the layer is unchanged (its
600    // contract), so this second pass lines up with the one on the pool.
601    debug_assert_eq!(distances.len(), layer.doc_count());
602    let mut scored: Vec<(f32, &crate::document::Document)> = layer
603        .docs()
604        .zip(distances)
605        .filter_map(|(doc, distance)| distance.map(|d| (d, doc)))
606        .collect();
607
608    let mut live: Vec<Scored> = Vec::new();
609    let mut returned = 0usize;
610    let mut n = q.top_k;
611    loop {
612        let take = n.min(scored.len());
613        if take > returned {
614            scored[returned..].select_nth_unstable_by(take - returned - 1, by_distance_then_id);
615            scored[returned..take].sort_by(by_distance_then_id);
616        }
617        let batch = &scored[returned..take];
618        let ids: Vec<String> = batch.iter().map(|(_, doc)| doc.id.clone()).collect();
619        let shadow = unshadowed(sources, at, &ids).await?;
620        let scored_batch: Vec<Scored> = batch
621            .iter()
622            .zip(shadow)
623            .filter(|(_, live)| *live)
624            .map(|((distance, doc), _)| Scored {
625                distance: *distance,
626                id: doc.id.clone(),
627                source: at,
628                attrs: Attrs::Have(doc.attrs.clone()),
629            })
630            .collect();
631        bound.offer(&scored_batch.iter().map(|s| s.distance).collect::<Vec<_>>());
632        returned = take;
633        live.extend(scored_batch);
634        let exhausted = returned >= scored.len();
635        if live.len() >= q.top_k || exhausted {
636            return Ok(live);
637        }
638        // The rows past `returned` are in no order after the partial select;
639        // the batch's largest distance is a true lower bound for all of them.
640        let rest_lower_bound = scored[returned - 1].0;
641        if bound.beats(rest_lower_bound) {
642            return Ok(live);
643        }
644        n = n.saturating_mul(WIDEN);
645    }
646}
647
648/// Rows per span of a columnar scan handed to one pool task: the same
649/// constant as the layer path, so neither depends on the thread count.
650const SPAN: usize = cpu::FLAT_CHUNK;
651
652/// The distance to every surviving row of `views` that `filter` keeps, as
653/// (distance, view, row), views in order and rows ascending in each.
654/// Survivors first, then the predicate (attributes parsed only for
655/// survivors), then the kernel on the row's slice of the matrix.
656///
657/// # Errors
658///
659/// [`ItzmaError::CorruptSegment`] for attribute JSON that does not parse.
660pub(crate) fn columnar_distances(
661    views: &[Arc<SegmentView>],
662    metric: Metric,
663    query: &[f32],
664    filter: Option<&Predicate>,
665) -> Result<Vec<(f32, usize, usize)>> {
666    // One segment shadows nothing of its own: every row survives.
667    let live = if views.len() == 1 {
668        None
669    } else {
670        let sorted: Vec<crate::layer::SortedIds<'_>> =
671            views.iter().map(|view| view.sorted_ids()).collect();
672        Some(crate::layer::survivors(&sorted))
673    };
674    let spans: Vec<(usize, usize, usize)> = views
675        .iter()
676        .enumerate()
677        .flat_map(|(v, view)| {
678            (0..view.rows())
679                .step_by(SPAN)
680                .map(move |start| (v, start, (start + SPAN).min(view.rows())))
681        })
682        .collect();
683    let chunks = cpu::chunked(&spans, 1, |chunk| {
684        let mut out = Vec::new();
685        for &(v, start, end) in chunk {
686            for row in start..end {
687                if live.as_ref().is_some_and(|live| !live[v].get(row)) {
688                    continue;
689                }
690                if let Some(predicate) = filter {
691                    if !predicate.matches(views[v].attrs(row)?.as_ref()) {
692                        continue;
693                    }
694                }
695                out.push((
696                    search::distance(metric, query, views[v].vector(row)),
697                    v,
698                    row,
699                ));
700            }
701        }
702        Ok::<_, ItzmaError>(out)
703    });
704    let mut out = Vec::with_capacity(
705        chunks
706            .iter()
707            .map(|chunk| chunk.as_ref().map_or(0, Vec::len))
708            .sum(),
709    );
710    for chunk in chunks {
711        out.extend(chunk?);
712    }
713    Ok(out)
714}
715
716/// [`search_flat`]'s loop over a columnar run: distances on the pool once,
717/// then growing batches off the front, each checked against newer sources.
718async fn search_columnar(
719    q: &Query<'_>,
720    sources: &[Source<'_>],
721    at: usize,
722    run: &Run,
723    bound: &crate::bound::Bound,
724) -> Result<Vec<Scored>> {
725    // The views are `Arc` clones: dropping them on the pool frees nothing,
726    // the run keeps them (the rule).
727    let (views, query, filter, metric) = (
728        run.views.clone(),
729        q.vector.to_vec(),
730        q.filter().cloned(),
731        q.metric,
732    );
733    let cost = Cost::Distances {
734        rows: run.views.iter().map(|view| view.rows()).sum(),
735        dim: q.vector.len(),
736    };
737    let mut scored = cpu::run(Lane::Query, cost, move || {
738        columnar_distances(&views, metric, &query, filter.as_ref())
739    })
740    .await?;
741    let id = |&(_, v, row): &(f32, usize, usize)| run.views[v].id(row);
742    let by = |a: &(f32, usize, usize), b: &(f32, usize, usize)| {
743        a.0.total_cmp(&b.0).then_with(|| id(a).cmp(id(b)))
744    };
745
746    let mut live: Vec<Scored> = Vec::new();
747    let mut returned = 0usize;
748    let mut n = q.top_k;
749    loop {
750        let take = n.min(scored.len());
751        if take > returned {
752            scored[returned..].select_nth_unstable_by(take - returned - 1, by);
753            scored[returned..take].sort_by(by);
754        }
755        let batch = &scored[returned..take];
756        let ids: Vec<String> = batch.iter().map(|s| id(s).to_owned()).collect();
757        let shadow = unshadowed(sources, at, &ids).await?;
758        let mut scored_batch = Vec::new();
759        for (&(distance, v, row), (id, live)) in batch.iter().zip(ids.into_iter().zip(shadow)) {
760            if live {
761                scored_batch.push(Scored {
762                    distance,
763                    id,
764                    source: at,
765                    attrs: Attrs::InView { view: v, row },
766                });
767            }
768        }
769        bound.offer(&scored_batch.iter().map(|s| s.distance).collect::<Vec<_>>());
770        returned = take;
771        live.extend(scored_batch);
772        if live.len() >= q.top_k || returned >= scored.len() {
773            return Ok(live);
774        }
775        // The rows past `returned` are in no order after the partial select;
776        // the batch's largest distance is a true lower bound for all of them.
777        let rest_lower_bound = scored[returned - 1].0;
778        if bound.beats(rest_lower_bound) {
779            return Ok(live);
780        }
781        n = n.saturating_mul(WIDEN);
782    }
783}
784
785/// The distance from `query` to every document of `layer`, in `layer.docs()`
786/// order, `None` where `filter` drops the document. Chunked so that on a pool
787/// thread the chunks run on several cores; a chunk is a run of
788/// documents in that order, so the result is the same either way.
789pub(crate) fn flat_distances(
790    layer: &Layer,
791    metric: Metric,
792    query: &[f32],
793    filter: Option<&Predicate>,
794) -> Vec<Option<f32>> {
795    let docs: Vec<&crate::document::Document> = layer.docs().collect();
796    distances_of(&docs, metric, query, filter)
797}
798
799/// [`flat_distances`] over a list of documents, in its order.
800fn distances_of(
801    docs: &[&crate::document::Document],
802    metric: Metric,
803    query: &[f32],
804    filter: Option<&Predicate>,
805) -> Vec<Option<f32>> {
806    let chunks = cpu::chunked(docs, cpu::FLAT_CHUNK, |chunk| {
807        chunk
808            .iter()
809            .map(|doc| {
810                filter
811                    .is_none_or(|p| p.matches(doc.attrs.as_ref()))
812                    .then(|| search::distance(metric, query, &doc.vector))
813            })
814            .collect::<Vec<_>>()
815    });
816    let mut out = Vec::with_capacity(docs.len());
817    for chunk in chunks {
818        out.extend(chunk);
819    }
820    out
821}
822
823/// For each of `ids`, proposed by source `at`: whether it is still the live
824/// version, that is, no newer source holds the id as a document or a tombstone.
825async fn unshadowed(sources: &[Source<'_>], at: usize, ids: &[String]) -> Result<Vec<bool>> {
826    // Owned ids: a closure over `&String` is inferred as higher-ranked, which
827    // makes the stream not provably `Send` (see `segment::read_all`).
828    stream::iter(ids.iter().cloned())
829        .map(|id| async move { is_live(sources, at, &id).await })
830        .buffered(FETCH_CONCURRENCY)
831        .try_collect()
832        .await
833}
834
835async fn is_live(sources: &[Source<'_>], at: usize, id: &str) -> Result<bool> {
836    let newer = &sources[at + 1..];
837    // Runs and layers in memory first: they cost no request.
838    if newer.iter().any(|source| match source {
839        Source::Flat(layer) => layer.holds(id),
840        Source::Columnar(run) => run.holds(id),
841        Source::Indexed(_) => false,
842    }) {
843        return Ok(false);
844    }
845    for source in newer {
846        if let Source::Indexed(newer) = source {
847            if newer.segment.holds(id).await? != Held::No {
848                return Ok(false);
849            }
850        }
851    }
852    Ok(true)
853}
854
855/// Fetch the attributes the final hits still lack, one request per block, and
856/// build the hits.
857async fn finish(sources: &[Source<'_>], live: Vec<Scored>) -> Result<Vec<Hit>> {
858    let mut wanted: HashMap<usize, Vec<u32>> = HashMap::new();
859    for hit in &live {
860        if let Attrs::Row(row) = hit.attrs {
861            wanted.entry(hit.source).or_default().push(row);
862        }
863    }
864    let fetched = try_join_all(
865        wanted
866            .into_iter()
867            .map(|(at, rows)| fetch_attrs(sources, at, rows)),
868    )
869    .await?;
870    let mut attrs: HashMap<(usize, u32), Option<serde_json::Value>> = HashMap::new();
871    for (at, rows, values) in fetched {
872        attrs.extend(rows.into_iter().zip(values).map(|(row, v)| ((at, row), v)));
873    }
874    live.into_iter()
875        .map(|hit| {
876            let attrs = match hit.attrs {
877                Attrs::Have(value) => value,
878                Attrs::Row(row) => attrs.remove(&(hit.source, row)).flatten(),
879                Attrs::InView { view, row } => match &sources[hit.source] {
880                    Source::Columnar(run) => run.views[view].attrs(row)?,
881                    _ => None,
882                },
883            };
884            Ok(Hit {
885                attrs,
886                id: hit.id,
887                distance: hit.distance,
888            })
889        })
890        .collect()
891}
892
893async fn fetch_attrs(
894    sources: &[Source<'_>],
895    at: usize,
896    rows: Vec<u32>,
897) -> Result<(usize, Vec<u32>, Vec<Option<serde_json::Value>>)> {
898    let Source::Indexed(source) = &sources[at] else {
899        return Ok((at, rows, Vec::new()));
900    };
901    let values = source.segment.attrs_of(&rows).await?;
902    Ok((at, rows, values))
903}
904
905/// Unit tests for [`Indexed::propose`] with a stub kind, so the engine's own
906/// checks on what an algorithm returns are tested without a real index object:
907/// nothing here names SQ8. The engine tests that need a real, published index
908/// are integration tests in `tests/query.rs`.
909#[cfg(test)]
910mod tests {
911    use futures::FutureExt;
912    use futures::future::BoxFuture;
913    use object_store::ObjectStoreExt;
914    use object_store::memory::InMemory;
915
916    use super::*;
917    use crate::document::{Document, WalOp};
918    use crate::segment::{self, SegmentView};
919
920    const DIM: usize = 2;
921
922    fn doc(id: &str, x: f32, y: f32) -> Document {
923        Document {
924            id: id.into(),
925            vector: vec![x, y],
926            attrs: None,
927            sparse: None,
928        }
929    }
930
931    /// `n` documents with the same vector of length `dim`, every other one
932    /// `active`, so every distance ties and the filter drops half.
933    fn layer_of_identical(n: usize, dim: usize) -> Layer {
934        let mut layer = Layer::new();
935        for i in 0..n {
936            layer.apply(WalOp::Upsert(Document {
937                id: format!("d{i:06}"),
938                vector: vec![1.0; dim],
939                attrs: Some(serde_json::json!({ "active": i % 2 == 0 })),
940                sparse: None,
941            }));
942        }
943        layer
944    }
945
946    fn view_of(layer: &Layer, dim: usize) -> Arc<SegmentView> {
947        let bytes = segment::encode_as(layer, dim, 2).unwrap();
948        Arc::new(SegmentView::decode("p", bytes, dim).unwrap())
949    }
950
951    /// The distance from `query` to every document of `layer` that `filter`
952    /// keeps, by id: the reference the columnar scan is held to.
953    fn reference(layer: &Layer, query: &[f32], filter: Option<&Predicate>) -> Vec<(String, f32)> {
954        let mut out: Vec<(String, f32)> = layer
955            .docs()
956            .filter(|d| filter.is_none_or(|p| p.matches(d.attrs.as_ref())))
957            .map(|d| (d.id.clone(), search::distance(Metric::L2, query, &d.vector)))
958            .collect();
959        out.sort_by(|a, b| a.0.cmp(&b.0));
960        out
961    }
962
963    /// Random runs: the columnar distances are the flat ones over the
964    /// overlaid layer, as (id, distance) sets, with and without a filter.
965    #[test]
966    fn columnar_distances_equal_flat_distances_over_the_overlay() {
967        let dim = 4;
968        let mut state = 0x0043_0005_u64;
969        let mut next = move |n: u64| {
970            state ^= state << 13;
971            state ^= state >> 7;
972            state ^= state << 17;
973            state % n
974        };
975        let filter = Predicate::is_true("active");
976        for case in 0..50 {
977            let layers: Vec<Layer> = (0..1 + next(4))
978                .map(|s| {
979                    let mut layer = Layer::new();
980                    for i in 0..next(700) {
981                        let id = format!("i{:04}", next(500));
982                        if next(5) == 0 {
983                            layer.apply(WalOp::Delete(id));
984                        } else {
985                            let x = (s * 1000 + i) as f32;
986                            layer.apply(WalOp::Upsert(Document {
987                                id,
988                                vector: vec![x, -x, 0.5, 1.0],
989                                attrs: Some(serde_json::json!({ "active": next(2) == 0 })),
990                                sparse: None,
991                            }));
992                        }
993                    }
994                    layer
995                })
996                .collect();
997            let views: Vec<Arc<SegmentView>> = layers.iter().map(|l| view_of(l, dim)).collect();
998            let mut overlaid = Layer::new();
999            for l in layers.iter().cloned() {
1000                overlaid.overlay(l);
1001            }
1002            let query = [3.0, 1.0, 0.0, -2.0];
1003            for filter in [None, Some(&filter)] {
1004                let mut got: Vec<(String, f32)> =
1005                    columnar_distances(&views, Metric::L2, &query, filter)
1006                        .unwrap()
1007                        .into_iter()
1008                        .map(|(d, v, row)| (views[v].id(row).to_owned(), d))
1009                        .collect();
1010                got.sort_by(|a, b| a.0.cmp(&b.0));
1011                assert_eq!(got, reference(&overlaid, &query, filter), "case {case}");
1012            }
1013        }
1014    }
1015
1016    #[tokio::test]
1017    async fn columnar_distances_on_the_pool_equal_the_inline_ones_across_chunks() {
1018        let dim = 64;
1019        let layer = layer_of_identical(crate::cpu::FLAT_CHUNK * 2 + 7, dim);
1020        let views = vec![view_of(&layer, dim)];
1021        let query = vec![0.5f32; dim];
1022        for filter in [None, Some(Predicate::is_true("active"))] {
1023            let inline = columnar_distances(&views, Metric::L2, &query, filter.as_ref()).unwrap();
1024            let (v, q, f) = (views.clone(), query.clone(), filter.clone());
1025            let cost = crate::cpu::Cost::Distances {
1026                rows: layer.doc_count(),
1027                dim,
1028            };
1029            let pooled = crate::cpu::run(crate::cpu::Lane::Query, cost, move || {
1030                columnar_distances(&v, Metric::L2, &q, f.as_ref())
1031            })
1032            .await
1033            .unwrap();
1034            assert_eq!(pooled, inline);
1035            let expected = if filter.is_some() {
1036                layer.doc_count().div_ceil(2)
1037            } else {
1038                layer.doc_count()
1039            };
1040            assert_eq!(inline.len(), expected);
1041        }
1042    }
1043
1044    #[tokio::test]
1045    async fn flat_distances_on_the_pool_equal_the_inline_ones_across_chunks() {
1046        let dim = 64;
1047        let layer = Arc::new(layer_of_identical(crate::cpu::FLAT_CHUNK * 2 + 7, dim));
1048        let query = vec![0.5f32; dim];
1049        let filter = Predicate::is_true("active");
1050        for filter in [None, Some(filter)] {
1051            let inline = flat_distances(&layer, Metric::L2, &query, filter.as_ref());
1052            assert_eq!(inline.len(), layer.doc_count());
1053            let (l, q, f) = (layer.clone(), query.clone(), filter.clone());
1054            let cost = crate::cpu::Cost::Distances {
1055                rows: layer.doc_count(),
1056                dim,
1057            };
1058            let pooled = crate::cpu::run(crate::cpu::Lane::Query, cost, move || {
1059                flat_distances(&l, Metric::L2, &q, f.as_ref())
1060            })
1061            .await;
1062            assert_eq!(pooled, inline);
1063            let kept = inline.iter().filter(|d| d.is_some()).count();
1064            let expected = if filter.is_some() {
1065                layer.doc_count().div_ceil(2)
1066            } else {
1067                layer.doc_count()
1068            };
1069            assert_eq!(kept, expected);
1070        }
1071    }
1072
1073    /// A version 2 segment of 3 documents at rows 0, 1, 2, written under `docs`.
1074    async fn small_segment(store: &dyn ObjectStore) -> String {
1075        let mut layer = Layer::new();
1076        for d in [doc("a", 0.0, 0.0), doc("b", 1.0, 0.0), doc("c", 2.0, 0.0)] {
1077            layer.apply(WalOp::Upsert(d));
1078        }
1079        layer.drop_tombstones();
1080        let id = segment::segment_id(1, 1);
1081        let bytes = segment::encode_as(&layer, DIM, 2).expect("encode");
1082        store
1083            .put(&segment::segment_path("docs", &id), bytes.into())
1084            .await
1085            .expect("put segment");
1086        id
1087    }
1088
1089    /// An algorithm that returns exactly the rows it is built with, ignoring
1090    /// `want`: good enough to stand in for a real kind, and easy to make lie,
1091    /// since `propose`'s own dedup and cut have something to do.
1092    struct Stub(Vec<Candidate>);
1093
1094    impl Algorithm for Stub {
1095        fn search<'a>(&'a self, probe: &'a Probe<'_>) -> BoxFuture<'a, Result<Vec<Candidate>>> {
1096            let _ = probe;
1097            let rows = self.0.clone();
1098            async move { Ok(rows) }.boxed()
1099        }
1100    }
1101
1102    /// Build the pieces `Indexed::propose` needs against `id`'s segment. The
1103    /// query is a placeholder: `propose` never looks past what the stub gives it.
1104    fn probe_query<'a>(
1105        store: &'a dyn ObjectStore,
1106        vector: &'a [f32],
1107        budget: &'a ReadBudget,
1108        policy: &'a FetchPolicy,
1109        options: &'a QueryOptions,
1110    ) -> Query<'a> {
1111        Query {
1112            store,
1113            namespace: "docs",
1114            dim: DIM,
1115            metric: Metric::L2,
1116            vector,
1117            top_k: 1,
1118            options,
1119            budget,
1120            policy,
1121            registry: &Builtin,
1122            decoded: None,
1123        }
1124    }
1125
1126    #[tokio::test]
1127    async fn a_row_past_the_segment_is_corrupt_index() {
1128        let store = InMemory::new();
1129        let id = small_segment(&store).await;
1130        let budget = ReadBudget::unlimited();
1131        let policy = FetchPolicy::local();
1132        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1133            .await
1134            .expect("open");
1135        let stub = Stub(vec![Candidate {
1136            row: 3, // the segment only has rows 0..3
1137            distance: 0.0,
1138        }]);
1139        let path = index::index_path("docs", &id, 1);
1140        let probe = Probe {
1141            store: &store,
1142            budget: &budget,
1143            policy: &policy,
1144            path: &path,
1145            dim: DIM,
1146            rows: segment.doc_count(),
1147            data_size: segment.data_size(),
1148            metric: Metric::L2,
1149            query: &[0.0, 0.0],
1150            want: 1,
1151            nprobe: None,
1152            decoded: None,
1153        };
1154
1155        // `DefaultCursor` is what now owns the checks `Indexed::propose` used
1156        // to run on whatever an algorithm hands back.
1157        let mut cursor = stub.cursor(probe).await.expect("cursor");
1158        let err = cursor.next(1).await.unwrap_err();
1159        assert!(
1160            matches!(err, ItzmaError::CorruptIndex { .. }),
1161            "a dishonest kind must not be trusted: {err:?}"
1162        );
1163    }
1164
1165    #[tokio::test]
1166    async fn a_filter_that_matches_no_candidate_leaves_no_live_rows() {
1167        let store = InMemory::new();
1168        let id = small_segment(&store).await;
1169        let budget = ReadBudget::unlimited();
1170        let policy = FetchPolicy::local();
1171        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1172            .await
1173            .expect("open");
1174        let stub = Stub((0..3).map(|row| Candidate { row, distance: 0.0 }).collect());
1175        let sources = vec![Source::Indexed(Box::new(Indexed {
1176            segment,
1177            algorithm: &stub,
1178            index_path: index::index_path("docs", &id, 1),
1179        }))];
1180
1181        // The documents have no attributes, so no one of them is `x = true`.
1182        let none = QueryOptions::default().filter(Some(Predicate::is_true("x")));
1183        let q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &none);
1184        let bound = crate::bound::Bound::new(q.top_k);
1185        let live = search_source(&q, &sources, 0, &bound)
1186            .await
1187            .expect("search");
1188        assert!(live.is_empty());
1189
1190        // All of them are `x is null`, and the attributes fetched for the test
1191        // stay on the hit so `finish` does not fetch them again.
1192        let all = QueryOptions::default().filter(Some(Predicate::IsNull("x".into())));
1193        let q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &all);
1194        let bound = crate::bound::Bound::new(q.top_k);
1195        let live = search_source(&q, &sources, 0, &bound)
1196            .await
1197            .expect("search");
1198        assert_eq!(live.len(), 3);
1199        assert!(
1200            live.iter()
1201                .all(|hit| matches!(hit.attrs, Attrs::Have(None)))
1202        );
1203
1204        let plain = QueryOptions::default();
1205        let q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &plain);
1206        let bound = crate::bound::Bound::new(q.top_k);
1207        let live = search_source(&q, &sources, 0, &bound)
1208            .await
1209            .expect("search");
1210        assert_eq!(live.len(), 3, "without a filter all three are live");
1211        assert!(
1212            live.iter().all(|hit| matches!(hit.attrs, Attrs::Row(_))),
1213            "and their attributes are left for `finish`"
1214        );
1215    }
1216
1217    #[tokio::test]
1218    async fn asking_for_every_row_gives_every_row_even_if_the_algorithm_cannot_reach_one() {
1219        // A graph index can leave a row with no way in. The widest ask is the
1220        // last resort of the widening loop, so it has to mean every row, or a
1221        // filter that only that row matches would find nothing.
1222        let store = InMemory::new();
1223        let id = small_segment(&store).await;
1224        let budget = ReadBudget::unlimited();
1225        let policy = FetchPolicy::local();
1226        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1227            .await
1228            .expect("open");
1229        let stub = Stub(vec![Candidate {
1230            row: 0,
1231            distance: 1.0,
1232        }]);
1233        let path = index::index_path("docs", &id, 1);
1234        let probe = Probe {
1235            store: &store,
1236            budget: &budget,
1237            policy: &policy,
1238            path: &path,
1239            dim: DIM,
1240            rows: segment.doc_count(),
1241            data_size: segment.data_size(),
1242            metric: Metric::L2,
1243            query: &[0.0, 0.0],
1244            want: usize::MAX,
1245            nprobe: None,
1246            decoded: None,
1247        };
1248
1249        let mut cursor = stub.cursor(probe).await.expect("cursor");
1250        let rows: Vec<u32> = cursor
1251            .next(usize::MAX)
1252            .await
1253            .expect("next")
1254            .candidates
1255            .iter()
1256            .map(|c| c.row)
1257            .collect();
1258        assert_eq!(rows, [0, 1, 2], "the reachable row first, then the rest");
1259    }
1260
1261    #[tokio::test]
1262    async fn an_index_that_gave_less_than_asked_is_next_asked_for_every_row() {
1263        // An index that proposed fewer rows than `want` returns the same rows for
1264        // any bigger `want` (it only probes some partitions), so the next ask has
1265        // to be for every row, not for eight times as many, twice more, in vain.
1266        struct Counting(std::sync::atomic::AtomicUsize);
1267        impl Algorithm for Counting {
1268            fn search<'a>(&'a self, probe: &'a Probe<'_>) -> BoxFuture<'a, Result<Vec<Candidate>>> {
1269                let _ = probe;
1270                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1271                async move {
1272                    Ok(vec![Candidate {
1273                        row: 0,
1274                        distance: 0.0,
1275                    }])
1276                }
1277                .boxed()
1278            }
1279        }
1280
1281        let store = InMemory::new();
1282        let id = small_segment(&store).await;
1283        let budget = ReadBudget::unlimited();
1284        let policy = FetchPolicy::local();
1285        let options = QueryOptions::default();
1286        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1287            .await
1288            .expect("open");
1289        let counting = Counting(std::sync::atomic::AtomicUsize::new(0));
1290        let sources = vec![Source::Indexed(Box::new(Indexed {
1291            segment,
1292            algorithm: &counting,
1293            index_path: index::index_path("docs", &id, 1),
1294        }))];
1295        let mut q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &options);
1296        q.top_k = 5;
1297
1298        let bound = crate::bound::Bound::new(q.top_k);
1299        let live = search_source(&q, &sources, 0, &bound)
1300            .await
1301            .expect("search");
1302        assert_eq!(live.len(), 3, "the fill-in reaches every row");
1303        assert_eq!(
1304            counting.0.load(std::sync::atomic::Ordering::SeqCst),
1305            2,
1306            "one ask for a shortlist, one for every row"
1307        );
1308    }
1309
1310    #[tokio::test]
1311    async fn duplicate_rows_count_once_and_extra_rows_are_cut() {
1312        let store = InMemory::new();
1313        let id = small_segment(&store).await;
1314        let budget = ReadBudget::unlimited();
1315        let policy = FetchPolicy::local();
1316        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1317            .await
1318            .expect("open");
1319        let stub = Stub(vec![
1320            Candidate {
1321                row: 1,
1322                distance: 5.0,
1323            },
1324            Candidate {
1325                row: 1,
1326                distance: 5.0,
1327            }, // repeated: counts once
1328            Candidate {
1329                row: 0,
1330                distance: 1.0,
1331            },
1332            Candidate {
1333                row: 2,
1334                distance: 9.0,
1335            }, // more than `want`: cut
1336        ]);
1337        let path = index::index_path("docs", &id, 1);
1338        let probe = Probe {
1339            store: &store,
1340            budget: &budget,
1341            policy: &policy,
1342            path: &path,
1343            dim: DIM,
1344            rows: segment.doc_count(),
1345            data_size: segment.data_size(),
1346            metric: Metric::L2,
1347            query: &[0.0, 0.0],
1348            want: 3,
1349            nprobe: None,
1350            decoded: None,
1351        };
1352
1353        // `want` matches the number of distinct rows, so a duplicate that
1354        // survived would show up in the result rather than being cut by
1355        // truncation alone.
1356        let found = stub
1357            .cursor(probe)
1358            .await
1359            .expect("cursor")
1360            .next(3)
1361            .await
1362            .expect("next")
1363            .candidates;
1364        assert_eq!(
1365            found,
1366            vec![
1367                Candidate {
1368                    row: 0,
1369                    distance: 1.0
1370                },
1371                Candidate {
1372                    row: 1,
1373                    distance: 5.0
1374                },
1375                Candidate {
1376                    row: 2,
1377                    distance: 9.0
1378                },
1379            ]
1380        );
1381    }
1382
1383    /// Regression: a cursor that repeats a row across batches is
1384    /// `CorruptIndex`. A cursor's own internal dedup (`DefaultCursor`'s
1385    /// `returned` set, `Sq8Cursor`'s drain) guards against this for the
1386    /// two cursors this crate ships, but `search_indexed`'s own `seen`
1387    /// check is what the engine actually relies on — this test drives
1388    /// that check directly with a dishonest `Cursor` that repeats a row
1389    /// across two `next` calls, bypassing both real cursors entirely.
1390    #[tokio::test]
1391    async fn a_cursor_that_repeats_a_row_across_batches_is_corrupt_index() {
1392        struct RepeatsRowZero;
1393        impl Algorithm for RepeatsRowZero {
1394            fn search<'a>(&'a self, probe: &'a Probe<'_>) -> BoxFuture<'a, Result<Vec<Candidate>>> {
1395                let _ = probe;
1396                async move { Ok(Vec::new()) }.boxed()
1397            }
1398
1399            fn cursor<'a>(
1400                &'a self,
1401                probe: Probe<'a>,
1402            ) -> BoxFuture<'a, Result<Box<dyn index::Cursor + 'a>>> {
1403                struct Dishonest(u32);
1404                impl index::Cursor for Dishonest {
1405                    fn next<'a>(&'a mut self, n: usize) -> BoxFuture<'a, Result<index::Batch>> {
1406                        let _ = n;
1407                        let row = self.0;
1408                        self.0 += 1; // never actually advances past row 0
1409                        async move {
1410                            Ok(index::Batch {
1411                                candidates: vec![Candidate {
1412                                    row: 0, // the same row, every batch
1413                                    distance: row as f32,
1414                                }],
1415                                rest_lower_bound: None,
1416                                exhausted: false,
1417                            })
1418                        }
1419                        .boxed()
1420                    }
1421                }
1422                let _ = probe;
1423                async move { Ok(Box::new(Dishonest(0)) as Box<dyn index::Cursor>) }.boxed()
1424            }
1425        }
1426
1427        let store = InMemory::new();
1428        let id = small_segment(&store).await;
1429        let budget = ReadBudget::unlimited();
1430        let policy = FetchPolicy::local();
1431        // rerank 1 makes want = 1 per batch, forcing a second next() call.
1432        let options = QueryOptions::default().rerank(Some(1));
1433        let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1434            .await
1435            .expect("open");
1436        let dishonest = RepeatsRowZero;
1437        let sources = vec![Source::Indexed(Box::new(Indexed {
1438            segment,
1439            algorithm: &dishonest,
1440            index_path: index::index_path("docs", &id, 1),
1441        }))];
1442        let mut q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &options);
1443        q.top_k = 3; // more than the dishonest cursor will ever truly deliver
1444
1445        let bound = crate::bound::Bound::new(q.top_k);
1446        let err = match search_source(&q, &sources, 0, &bound).await {
1447            Ok(_) => panic!("a cursor that repeats a row across batches must not be trusted"),
1448            Err(e) => e,
1449        };
1450        assert!(
1451            matches!(err, ItzmaError::CorruptIndex { .. }),
1452            "a cursor that repeats a row across batches must not be trusted: {err:?}"
1453        );
1454    }
1455}