1use 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
54pub const DEFAULT_RERANK: usize = 4;
57
58const FETCH_CONCURRENCY: usize = 16;
60const WIDEN: usize = 8;
63
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
78#[serde(default)]
79#[non_exhaustive]
80pub struct QueryOptions {
81 pub rerank: Option<usize>,
87 pub nprobe: Option<usize>,
91 pub exact: bool,
94 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 #[must_use]
117 pub fn rerank(mut self, rerank: Option<usize>) -> Self {
118 self.rerank = rerank;
119 self
120 }
121
122 #[must_use]
124 pub fn nprobe(mut self, nprobe: Option<usize>) -> Self {
125 self.nprobe = nprobe;
126 self
127 }
128
129 #[must_use]
131 pub fn exact(mut self, exact: bool) -> Self {
132 self.exact = exact;
133 self
134 }
135
136 #[must_use]
138 pub fn filter(mut self, filter: Option<Predicate>) -> Self {
139 self.filter = filter;
140 self
141 }
142
143 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
155pub(crate) trait Registry: Sync {
160 fn algorithm(&self, kind: &str) -> Option<&dyn Algorithm>;
161}
162
163pub(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
172fn 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
183pub(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 pub(crate) decoded: Option<&'a DecodedRef>,
198}
199
200impl Query<'_> {
201 fn filter(&self) -> Option<&Predicate> {
203 self.options.filter.as_ref()
204 }
205}
206
207enum Step<'a> {
209 Indexed {
211 id: &'a str,
212 generation: u32,
213 algorithm: &'a dyn Algorithm,
214 },
215 Flat(&'a [String]),
217}
218
219enum Source<'a> {
221 Indexed(Box<Indexed<'a>>),
222 Columnar(Run),
224 Flat(Arc<Layer>),
227}
228
229struct Run {
231 views: Vec<Arc<SegmentView>>,
232}
233
234impl Run {
235 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
248enum Attrs {
251 Have(Option<serde_json::Value>),
252 Row(u32),
253 InView {
255 view: usize,
256 row: usize,
257 },
258}
259
260struct Scored {
262 distance: f32,
263 id: String,
264 source: usize,
265 attrs: Attrs,
266}
267
268fn plan<'a>(q: &Query<'a>, manifest: &'a Manifest) -> Vec<Step<'a>> {
272 let live = &manifest.live_segments;
273 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
309pub(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 let bound = crate::bound::Bound::new(q.top_k);
330 let steps = plan(q, manifest);
331 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 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
370async 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
416async 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
430async 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
506async 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 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
559fn 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 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 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 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
648const SPAN: usize = cpu::FLAT_CHUNK;
651
652pub(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 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
716async 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 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 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
785pub(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
799fn 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
823async fn unshadowed(sources: &[Source<'_>], at: usize, ids: &[String]) -> Result<Vec<bool>> {
826 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 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
855async 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#[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 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 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 #[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 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 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 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, 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 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 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 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 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 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 }, Candidate {
1329 row: 0,
1330 distance: 1.0,
1331 },
1332 Candidate {
1333 row: 2,
1334 distance: 9.0,
1335 }, ]);
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 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 #[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; async move {
1410 Ok(index::Batch {
1411 candidates: vec![Candidate {
1412 row: 0, 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 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; 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}