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