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 match source.segment.eligible_of(predicate, &rows).await? {
540 Some(decided) => kept
541 .into_iter()
542 .zip(decided)
543 .filter(|(_, eligible)| *eligible)
544 .map(|(pair, _)| {
545 let attrs = Attrs::Row(pair.0);
546 (pair, attrs)
547 })
548 .unzip(),
549 None => {
550 let fetched = source.segment.attrs_of(&rows).await?;
551 kept.into_iter()
552 .zip(fetched)
553 .filter(|(_, attrs)| predicate.matches(attrs.as_ref()))
554 .map(|(pair, attrs)| (pair, Attrs::Have(attrs)))
555 .unzip()
556 }
557 }
558 }
559 };
560 let kept_rows: Vec<u32> = kept.iter().map(|(row, _)| *row).collect();
561 let vectors = source.segment.vectors_of(&kept_rows).await?;
562 Ok(kept
563 .into_iter()
564 .enumerate()
565 .zip(attrs)
566 .map(|((i, (_, id)), attrs)| Scored {
567 distance: search::distance(q.metric, q.vector, vectors.row(i)),
568 id,
569 source: at,
570 attrs,
571 })
572 .collect())
573}
574
575fn by_distance_then_id(
581 a: &(f32, &crate::document::Document),
582 b: &(f32, &crate::document::Document),
583) -> std::cmp::Ordering {
584 a.0.total_cmp(&b.0).then_with(|| a.1.id.cmp(&b.1.id))
585}
586
587async fn search_flat(
588 q: &Query<'_>,
589 sources: &[Source<'_>],
590 at: usize,
591 layer: &Arc<Layer>,
592 bound: &crate::bound::Bound,
593) -> Result<Vec<Scored>> {
594 let (owned, query, filter, metric) = (
602 layer.clone(),
603 q.vector.to_vec(),
604 q.filter().cloned(),
605 q.metric,
606 );
607 let cost = Cost::Distances {
608 rows: layer.doc_count(),
609 dim: q.vector.len(),
610 };
611 let distances = cpu::run(Lane::Query, cost, move || {
612 flat_distances(&owned, metric, &query, filter.as_ref())
613 })
614 .await;
615 debug_assert_eq!(distances.len(), layer.doc_count());
618 let mut scored: Vec<(f32, &crate::document::Document)> = layer
619 .docs()
620 .zip(distances)
621 .filter_map(|(doc, distance)| distance.map(|d| (d, doc)))
622 .collect();
623
624 let mut live: Vec<Scored> = Vec::new();
625 let mut returned = 0usize;
626 let mut n = q.top_k;
627 loop {
628 let take = n.min(scored.len());
629 if take > returned {
630 scored[returned..].select_nth_unstable_by(take - returned - 1, by_distance_then_id);
631 scored[returned..take].sort_by(by_distance_then_id);
632 }
633 let batch = &scored[returned..take];
634 let ids: Vec<String> = batch.iter().map(|(_, doc)| doc.id.clone()).collect();
635 let shadow = unshadowed(sources, at, &ids).await?;
636 let scored_batch: Vec<Scored> = batch
637 .iter()
638 .zip(shadow)
639 .filter(|(_, live)| *live)
640 .map(|((distance, doc), _)| Scored {
641 distance: *distance,
642 id: doc.id.clone(),
643 source: at,
644 attrs: Attrs::Have(doc.attrs.clone()),
645 })
646 .collect();
647 bound.offer(&scored_batch.iter().map(|s| s.distance).collect::<Vec<_>>());
648 returned = take;
649 live.extend(scored_batch);
650 let exhausted = returned >= scored.len();
651 if live.len() >= q.top_k || exhausted {
652 return Ok(live);
653 }
654 let rest_lower_bound = scored[returned - 1].0;
657 if bound.beats(rest_lower_bound) {
658 return Ok(live);
659 }
660 n = n.saturating_mul(WIDEN);
661 }
662}
663
664const SPAN: usize = cpu::FLAT_CHUNK;
667
668pub(crate) fn columnar_distances(
677 views: &[Arc<SegmentView>],
678 metric: Metric,
679 query: &[f32],
680 filter: Option<&Predicate>,
681) -> Result<Vec<(f32, usize, usize)>> {
682 let live = if views.len() == 1 {
684 None
685 } else {
686 let sorted: Vec<crate::layer::SortedIds<'_>> =
687 views.iter().map(|view| view.sorted_ids()).collect();
688 Some(crate::layer::survivors(&sorted))
689 };
690 let spans: Vec<(usize, usize, usize)> = views
691 .iter()
692 .enumerate()
693 .flat_map(|(v, view)| {
694 (0..view.rows())
695 .step_by(SPAN)
696 .map(move |start| (v, start, (start + SPAN).min(view.rows())))
697 })
698 .collect();
699 let chunks = cpu::chunked(&spans, 1, |chunk| {
700 let mut out = Vec::new();
701 for &(v, start, end) in chunk {
702 for row in start..end {
703 if live.as_ref().is_some_and(|live| !live[v].get(row)) {
704 continue;
705 }
706 if let Some(predicate) = filter {
707 if !predicate.matches(views[v].attrs(row)?.as_ref()) {
708 continue;
709 }
710 }
711 out.push((
712 search::distance(metric, query, views[v].vector(row)),
713 v,
714 row,
715 ));
716 }
717 }
718 Ok::<_, ItzmaError>(out)
719 });
720 let mut out = Vec::with_capacity(
721 chunks
722 .iter()
723 .map(|chunk| chunk.as_ref().map_or(0, Vec::len))
724 .sum(),
725 );
726 for chunk in chunks {
727 out.extend(chunk?);
728 }
729 Ok(out)
730}
731
732async fn search_columnar(
735 q: &Query<'_>,
736 sources: &[Source<'_>],
737 at: usize,
738 run: &Run,
739 bound: &crate::bound::Bound,
740) -> Result<Vec<Scored>> {
741 let (views, query, filter, metric) = (
744 run.views.clone(),
745 q.vector.to_vec(),
746 q.filter().cloned(),
747 q.metric,
748 );
749 let cost = Cost::Distances {
750 rows: run.views.iter().map(|view| view.rows()).sum(),
751 dim: q.vector.len(),
752 };
753 let mut scored = cpu::run(Lane::Query, cost, move || {
754 columnar_distances(&views, metric, &query, filter.as_ref())
755 })
756 .await?;
757 let id = |&(_, v, row): &(f32, usize, usize)| run.views[v].id(row);
758 let by = |a: &(f32, usize, usize), b: &(f32, usize, usize)| {
759 a.0.total_cmp(&b.0).then_with(|| id(a).cmp(id(b)))
760 };
761
762 let mut live: Vec<Scored> = Vec::new();
763 let mut returned = 0usize;
764 let mut n = q.top_k;
765 loop {
766 let take = n.min(scored.len());
767 if take > returned {
768 scored[returned..].select_nth_unstable_by(take - returned - 1, by);
769 scored[returned..take].sort_by(by);
770 }
771 let batch = &scored[returned..take];
772 let ids: Vec<String> = batch.iter().map(|s| id(s).to_owned()).collect();
773 let shadow = unshadowed(sources, at, &ids).await?;
774 let mut scored_batch = Vec::new();
775 for (&(distance, v, row), (id, live)) in batch.iter().zip(ids.into_iter().zip(shadow)) {
776 if live {
777 scored_batch.push(Scored {
778 distance,
779 id,
780 source: at,
781 attrs: Attrs::InView { view: v, row },
782 });
783 }
784 }
785 bound.offer(&scored_batch.iter().map(|s| s.distance).collect::<Vec<_>>());
786 returned = take;
787 live.extend(scored_batch);
788 if live.len() >= q.top_k || returned >= scored.len() {
789 return Ok(live);
790 }
791 let rest_lower_bound = scored[returned - 1].0;
794 if bound.beats(rest_lower_bound) {
795 return Ok(live);
796 }
797 n = n.saturating_mul(WIDEN);
798 }
799}
800
801pub(crate) fn flat_distances(
806 layer: &Layer,
807 metric: Metric,
808 query: &[f32],
809 filter: Option<&Predicate>,
810) -> Vec<Option<f32>> {
811 let docs: Vec<&crate::document::Document> = layer.docs().collect();
812 distances_of(&docs, metric, query, filter)
813}
814
815fn distances_of(
817 docs: &[&crate::document::Document],
818 metric: Metric,
819 query: &[f32],
820 filter: Option<&Predicate>,
821) -> Vec<Option<f32>> {
822 let chunks = cpu::chunked(docs, cpu::FLAT_CHUNK, |chunk| {
823 chunk
824 .iter()
825 .map(|doc| {
826 filter
827 .is_none_or(|p| p.matches(doc.attrs.as_ref()))
828 .then(|| search::distance(metric, query, &doc.vector))
829 })
830 .collect::<Vec<_>>()
831 });
832 let mut out = Vec::with_capacity(docs.len());
833 for chunk in chunks {
834 out.extend(chunk);
835 }
836 out
837}
838
839async fn unshadowed(sources: &[Source<'_>], at: usize, ids: &[String]) -> Result<Vec<bool>> {
842 stream::iter(ids.iter().cloned())
845 .map(|id| async move { is_live(sources, at, &id).await })
846 .buffered(FETCH_CONCURRENCY)
847 .try_collect()
848 .await
849}
850
851async fn is_live(sources: &[Source<'_>], at: usize, id: &str) -> Result<bool> {
852 let newer = &sources[at + 1..];
853 if newer.iter().any(|source| match source {
855 Source::Flat(layer) => layer.holds(id),
856 Source::Columnar(run) => run.holds(id),
857 Source::Indexed(_) => false,
858 }) {
859 return Ok(false);
860 }
861 for source in newer {
862 if let Source::Indexed(newer) = source {
863 if newer.segment.holds(id).await? != Held::No {
864 return Ok(false);
865 }
866 }
867 }
868 Ok(true)
869}
870
871async fn finish(sources: &[Source<'_>], live: Vec<Scored>) -> Result<Vec<Hit>> {
874 let mut wanted: HashMap<usize, Vec<u32>> = HashMap::new();
875 for hit in &live {
876 if let Attrs::Row(row) = hit.attrs {
877 wanted.entry(hit.source).or_default().push(row);
878 }
879 }
880 let fetched = try_join_all(
881 wanted
882 .into_iter()
883 .map(|(at, rows)| fetch_attrs(sources, at, rows)),
884 )
885 .await?;
886 let mut attrs: HashMap<(usize, u32), Option<serde_json::Value>> = HashMap::new();
887 for (at, rows, values) in fetched {
888 attrs.extend(rows.into_iter().zip(values).map(|(row, v)| ((at, row), v)));
889 }
890 live.into_iter()
891 .map(|hit| {
892 let attrs = match hit.attrs {
893 Attrs::Have(value) => value,
894 Attrs::Row(row) => attrs.remove(&(hit.source, row)).flatten(),
895 Attrs::InView { view, row } => match &sources[hit.source] {
896 Source::Columnar(run) => run.views[view].attrs(row)?,
897 _ => None,
898 },
899 };
900 Ok(Hit {
901 attrs,
902 id: hit.id,
903 distance: hit.distance,
904 })
905 })
906 .collect()
907}
908
909async fn fetch_attrs(
910 sources: &[Source<'_>],
911 at: usize,
912 rows: Vec<u32>,
913) -> Result<(usize, Vec<u32>, Vec<Option<serde_json::Value>>)> {
914 let Source::Indexed(source) = &sources[at] else {
915 return Ok((at, rows, Vec::new()));
916 };
917 let values = source.segment.attrs_of(&rows).await?;
918 Ok((at, rows, values))
919}
920
921#[cfg(test)]
926mod tests {
927 use futures::FutureExt;
928 use futures::future::BoxFuture;
929 use object_store::ObjectStoreExt;
930 use object_store::memory::InMemory;
931
932 use super::*;
933 use crate::document::{Document, WalOp};
934 use crate::segment::{self, SegmentView};
935
936 const DIM: usize = 2;
937
938 fn doc(id: &str, x: f32, y: f32) -> Document {
939 Document {
940 id: id.into(),
941 vector: vec![x, y],
942 attrs: None,
943 sparse: None,
944 }
945 }
946
947 fn layer_of_identical(n: usize, dim: usize) -> Layer {
950 let mut layer = Layer::new();
951 for i in 0..n {
952 layer.apply(WalOp::Upsert(Document {
953 id: format!("d{i:06}"),
954 vector: vec![1.0; dim],
955 attrs: Some(serde_json::json!({ "active": i % 2 == 0 })),
956 sparse: None,
957 }));
958 }
959 layer
960 }
961
962 fn view_of(layer: &Layer, dim: usize) -> Arc<SegmentView> {
963 let bytes = segment::encode_as(layer, dim, 2).unwrap();
964 Arc::new(SegmentView::decode("p", bytes, dim).unwrap())
965 }
966
967 fn reference(layer: &Layer, query: &[f32], filter: Option<&Predicate>) -> Vec<(String, f32)> {
970 let mut out: Vec<(String, f32)> = layer
971 .docs()
972 .filter(|d| filter.is_none_or(|p| p.matches(d.attrs.as_ref())))
973 .map(|d| (d.id.clone(), search::distance(Metric::L2, query, &d.vector)))
974 .collect();
975 out.sort_by(|a, b| a.0.cmp(&b.0));
976 out
977 }
978
979 #[test]
982 fn columnar_distances_equal_flat_distances_over_the_overlay() {
983 let dim = 4;
984 let mut state = 0x0043_0005_u64;
985 let mut next = move |n: u64| {
986 state ^= state << 13;
987 state ^= state >> 7;
988 state ^= state << 17;
989 state % n
990 };
991 let filter = Predicate::is_true("active");
992 for case in 0..50 {
993 let layers: Vec<Layer> = (0..1 + next(4))
994 .map(|s| {
995 let mut layer = Layer::new();
996 for i in 0..next(700) {
997 let id = format!("i{:04}", next(500));
998 if next(5) == 0 {
999 layer.apply(WalOp::Delete(id));
1000 } else {
1001 let x = (s * 1000 + i) as f32;
1002 layer.apply(WalOp::Upsert(Document {
1003 id,
1004 vector: vec![x, -x, 0.5, 1.0],
1005 attrs: Some(serde_json::json!({ "active": next(2) == 0 })),
1006 sparse: None,
1007 }));
1008 }
1009 }
1010 layer
1011 })
1012 .collect();
1013 let views: Vec<Arc<SegmentView>> = layers.iter().map(|l| view_of(l, dim)).collect();
1014 let mut overlaid = Layer::new();
1015 for l in layers.iter().cloned() {
1016 overlaid.overlay(l);
1017 }
1018 let query = [3.0, 1.0, 0.0, -2.0];
1019 for filter in [None, Some(&filter)] {
1020 let mut got: Vec<(String, f32)> =
1021 columnar_distances(&views, Metric::L2, &query, filter)
1022 .unwrap()
1023 .into_iter()
1024 .map(|(d, v, row)| (views[v].id(row).to_owned(), d))
1025 .collect();
1026 got.sort_by(|a, b| a.0.cmp(&b.0));
1027 assert_eq!(got, reference(&overlaid, &query, filter), "case {case}");
1028 }
1029 }
1030 }
1031
1032 #[tokio::test]
1033 async fn columnar_distances_on_the_pool_equal_the_inline_ones_across_chunks() {
1034 let dim = 64;
1035 let layer = layer_of_identical(crate::cpu::FLAT_CHUNK * 2 + 7, dim);
1036 let views = vec![view_of(&layer, dim)];
1037 let query = vec![0.5f32; dim];
1038 for filter in [None, Some(Predicate::is_true("active"))] {
1039 let inline = columnar_distances(&views, Metric::L2, &query, filter.as_ref()).unwrap();
1040 let (v, q, f) = (views.clone(), query.clone(), filter.clone());
1041 let cost = crate::cpu::Cost::Distances {
1042 rows: layer.doc_count(),
1043 dim,
1044 };
1045 let pooled = crate::cpu::run(crate::cpu::Lane::Query, cost, move || {
1046 columnar_distances(&v, Metric::L2, &q, f.as_ref())
1047 })
1048 .await
1049 .unwrap();
1050 assert_eq!(pooled, inline);
1051 let expected = if filter.is_some() {
1052 layer.doc_count().div_ceil(2)
1053 } else {
1054 layer.doc_count()
1055 };
1056 assert_eq!(inline.len(), expected);
1057 }
1058 }
1059
1060 #[tokio::test]
1061 async fn flat_distances_on_the_pool_equal_the_inline_ones_across_chunks() {
1062 let dim = 64;
1063 let layer = Arc::new(layer_of_identical(crate::cpu::FLAT_CHUNK * 2 + 7, dim));
1064 let query = vec![0.5f32; dim];
1065 let filter = Predicate::is_true("active");
1066 for filter in [None, Some(filter)] {
1067 let inline = flat_distances(&layer, Metric::L2, &query, filter.as_ref());
1068 assert_eq!(inline.len(), layer.doc_count());
1069 let (l, q, f) = (layer.clone(), query.clone(), filter.clone());
1070 let cost = crate::cpu::Cost::Distances {
1071 rows: layer.doc_count(),
1072 dim,
1073 };
1074 let pooled = crate::cpu::run(crate::cpu::Lane::Query, cost, move || {
1075 flat_distances(&l, Metric::L2, &q, f.as_ref())
1076 })
1077 .await;
1078 assert_eq!(pooled, inline);
1079 let kept = inline.iter().filter(|d| d.is_some()).count();
1080 let expected = if filter.is_some() {
1081 layer.doc_count().div_ceil(2)
1082 } else {
1083 layer.doc_count()
1084 };
1085 assert_eq!(kept, expected);
1086 }
1087 }
1088
1089 async fn small_segment(store: &dyn ObjectStore) -> String {
1091 let mut layer = Layer::new();
1092 for d in [doc("a", 0.0, 0.0), doc("b", 1.0, 0.0), doc("c", 2.0, 0.0)] {
1093 layer.apply(WalOp::Upsert(d));
1094 }
1095 layer.drop_tombstones();
1096 let id = segment::segment_id(1, 1);
1097 let bytes = segment::encode_as(&layer, DIM, 2).expect("encode");
1098 store
1099 .put(&segment::segment_path("docs", &id), bytes.into())
1100 .await
1101 .expect("put segment");
1102 id
1103 }
1104
1105 struct Stub(Vec<Candidate>);
1109
1110 impl Algorithm for Stub {
1111 fn search<'a>(&'a self, probe: &'a Probe<'_>) -> BoxFuture<'a, Result<Vec<Candidate>>> {
1112 let _ = probe;
1113 let rows = self.0.clone();
1114 async move { Ok(rows) }.boxed()
1115 }
1116 }
1117
1118 fn probe_query<'a>(
1121 store: &'a dyn ObjectStore,
1122 vector: &'a [f32],
1123 budget: &'a ReadBudget,
1124 policy: &'a FetchPolicy,
1125 options: &'a QueryOptions,
1126 ) -> Query<'a> {
1127 Query {
1128 store,
1129 namespace: "docs",
1130 dim: DIM,
1131 metric: Metric::L2,
1132 vector,
1133 top_k: 1,
1134 options,
1135 budget,
1136 policy,
1137 registry: &Builtin,
1138 decoded: None,
1139 }
1140 }
1141
1142 #[tokio::test]
1143 async fn a_row_past_the_segment_is_corrupt_index() {
1144 let store = InMemory::new();
1145 let id = small_segment(&store).await;
1146 let budget = ReadBudget::unlimited();
1147 let policy = FetchPolicy::local();
1148 let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1149 .await
1150 .expect("open");
1151 let stub = Stub(vec![Candidate {
1152 row: 3, distance: 0.0,
1154 }]);
1155 let path = index::index_path("docs", &id, 1);
1156 let probe = Probe {
1157 store: &store,
1158 budget: &budget,
1159 policy: &policy,
1160 path: &path,
1161 dim: DIM,
1162 rows: segment.doc_count(),
1163 data_size: segment.data_size(),
1164 metric: Metric::L2,
1165 query: &[0.0, 0.0],
1166 want: 1,
1167 nprobe: None,
1168 decoded: None,
1169 };
1170
1171 let mut cursor = stub.cursor(probe).await.expect("cursor");
1174 let err = cursor.next(1).await.unwrap_err();
1175 assert!(
1176 matches!(err, ItzmaError::CorruptIndex { .. }),
1177 "a dishonest kind must not be trusted: {err:?}"
1178 );
1179 }
1180
1181 #[tokio::test]
1182 async fn a_filter_that_matches_no_candidate_leaves_no_live_rows() {
1183 let store = InMemory::new();
1184 let id = small_segment(&store).await;
1185 let budget = ReadBudget::unlimited();
1186 let policy = FetchPolicy::local();
1187 let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1188 .await
1189 .expect("open");
1190 let stub = Stub((0..3).map(|row| Candidate { row, distance: 0.0 }).collect());
1191 let sources = vec![Source::Indexed(Box::new(Indexed {
1192 segment,
1193 algorithm: &stub,
1194 index_path: index::index_path("docs", &id, 1),
1195 }))];
1196
1197 let none = QueryOptions::default().filter(Some(Predicate::is_true("x")));
1199 let q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &none);
1200 let bound = crate::bound::Bound::new(q.top_k);
1201 let live = search_source(&q, &sources, 0, &bound)
1202 .await
1203 .expect("search");
1204 assert!(live.is_empty());
1205
1206 let all = QueryOptions::default().filter(Some(Predicate::IsNull("x".into())));
1209 let q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &all);
1210 let bound = crate::bound::Bound::new(q.top_k);
1211 let live = search_source(&q, &sources, 0, &bound)
1212 .await
1213 .expect("search");
1214 assert_eq!(live.len(), 3);
1215 assert!(
1216 live.iter()
1217 .all(|hit| matches!(hit.attrs, Attrs::Have(None)))
1218 );
1219
1220 let plain = QueryOptions::default();
1221 let q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &plain);
1222 let bound = crate::bound::Bound::new(q.top_k);
1223 let live = search_source(&q, &sources, 0, &bound)
1224 .await
1225 .expect("search");
1226 assert_eq!(live.len(), 3, "without a filter all three are live");
1227 assert!(
1228 live.iter().all(|hit| matches!(hit.attrs, Attrs::Row(_))),
1229 "and their attributes are left for `finish`"
1230 );
1231 }
1232
1233 #[tokio::test]
1234 async fn asking_for_every_row_gives_every_row_even_if_the_algorithm_cannot_reach_one() {
1235 let store = InMemory::new();
1239 let id = small_segment(&store).await;
1240 let budget = ReadBudget::unlimited();
1241 let policy = FetchPolicy::local();
1242 let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1243 .await
1244 .expect("open");
1245 let stub = Stub(vec![Candidate {
1246 row: 0,
1247 distance: 1.0,
1248 }]);
1249 let path = index::index_path("docs", &id, 1);
1250 let probe = Probe {
1251 store: &store,
1252 budget: &budget,
1253 policy: &policy,
1254 path: &path,
1255 dim: DIM,
1256 rows: segment.doc_count(),
1257 data_size: segment.data_size(),
1258 metric: Metric::L2,
1259 query: &[0.0, 0.0],
1260 want: usize::MAX,
1261 nprobe: None,
1262 decoded: None,
1263 };
1264
1265 let mut cursor = stub.cursor(probe).await.expect("cursor");
1266 let rows: Vec<u32> = cursor
1267 .next(usize::MAX)
1268 .await
1269 .expect("next")
1270 .candidates
1271 .iter()
1272 .map(|c| c.row)
1273 .collect();
1274 assert_eq!(rows, [0, 1, 2], "the reachable row first, then the rest");
1275 }
1276
1277 #[tokio::test]
1278 async fn an_index_that_gave_less_than_asked_is_next_asked_for_every_row() {
1279 struct Counting(std::sync::atomic::AtomicUsize);
1283 impl Algorithm for Counting {
1284 fn search<'a>(&'a self, probe: &'a Probe<'_>) -> BoxFuture<'a, Result<Vec<Candidate>>> {
1285 let _ = probe;
1286 self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1287 async move {
1288 Ok(vec![Candidate {
1289 row: 0,
1290 distance: 0.0,
1291 }])
1292 }
1293 .boxed()
1294 }
1295 }
1296
1297 let store = InMemory::new();
1298 let id = small_segment(&store).await;
1299 let budget = ReadBudget::unlimited();
1300 let policy = FetchPolicy::local();
1301 let options = QueryOptions::default();
1302 let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1303 .await
1304 .expect("open");
1305 let counting = Counting(std::sync::atomic::AtomicUsize::new(0));
1306 let sources = vec![Source::Indexed(Box::new(Indexed {
1307 segment,
1308 algorithm: &counting,
1309 index_path: index::index_path("docs", &id, 1),
1310 }))];
1311 let mut q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &options);
1312 q.top_k = 5;
1313
1314 let bound = crate::bound::Bound::new(q.top_k);
1315 let live = search_source(&q, &sources, 0, &bound)
1316 .await
1317 .expect("search");
1318 assert_eq!(live.len(), 3, "the fill-in reaches every row");
1319 assert_eq!(
1320 counting.0.load(std::sync::atomic::Ordering::SeqCst),
1321 2,
1322 "one ask for a shortlist, one for every row"
1323 );
1324 }
1325
1326 #[tokio::test]
1327 async fn duplicate_rows_count_once_and_extra_rows_are_cut() {
1328 let store = InMemory::new();
1329 let id = small_segment(&store).await;
1330 let budget = ReadBudget::unlimited();
1331 let policy = FetchPolicy::local();
1332 let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1333 .await
1334 .expect("open");
1335 let stub = Stub(vec![
1336 Candidate {
1337 row: 1,
1338 distance: 5.0,
1339 },
1340 Candidate {
1341 row: 1,
1342 distance: 5.0,
1343 }, Candidate {
1345 row: 0,
1346 distance: 1.0,
1347 },
1348 Candidate {
1349 row: 2,
1350 distance: 9.0,
1351 }, ]);
1353 let path = index::index_path("docs", &id, 1);
1354 let probe = Probe {
1355 store: &store,
1356 budget: &budget,
1357 policy: &policy,
1358 path: &path,
1359 dim: DIM,
1360 rows: segment.doc_count(),
1361 data_size: segment.data_size(),
1362 metric: Metric::L2,
1363 query: &[0.0, 0.0],
1364 want: 3,
1365 nprobe: None,
1366 decoded: None,
1367 };
1368
1369 let found = stub
1373 .cursor(probe)
1374 .await
1375 .expect("cursor")
1376 .next(3)
1377 .await
1378 .expect("next")
1379 .candidates;
1380 assert_eq!(
1381 found,
1382 vec![
1383 Candidate {
1384 row: 0,
1385 distance: 1.0
1386 },
1387 Candidate {
1388 row: 1,
1389 distance: 5.0
1390 },
1391 Candidate {
1392 row: 2,
1393 distance: 9.0
1394 },
1395 ]
1396 );
1397 }
1398
1399 #[tokio::test]
1407 async fn a_cursor_that_repeats_a_row_across_batches_is_corrupt_index() {
1408 struct RepeatsRowZero;
1409 impl Algorithm for RepeatsRowZero {
1410 fn search<'a>(&'a self, probe: &'a Probe<'_>) -> BoxFuture<'a, Result<Vec<Candidate>>> {
1411 let _ = probe;
1412 async move { Ok(Vec::new()) }.boxed()
1413 }
1414
1415 fn cursor<'a>(
1416 &'a self,
1417 probe: Probe<'a>,
1418 ) -> BoxFuture<'a, Result<Box<dyn index::Cursor + 'a>>> {
1419 struct Dishonest(u32);
1420 impl index::Cursor for Dishonest {
1421 fn next<'a>(&'a mut self, n: usize) -> BoxFuture<'a, Result<index::Batch>> {
1422 let _ = n;
1423 let row = self.0;
1424 self.0 += 1; async move {
1426 Ok(index::Batch {
1427 candidates: vec![Candidate {
1428 row: 0, distance: row as f32,
1430 }],
1431 rest_lower_bound: None,
1432 exhausted: false,
1433 })
1434 }
1435 .boxed()
1436 }
1437 }
1438 let _ = probe;
1439 async move { Ok(Box::new(Dishonest(0)) as Box<dyn index::Cursor>) }.boxed()
1440 }
1441 }
1442
1443 let store = InMemory::new();
1444 let id = small_segment(&store).await;
1445 let budget = ReadBudget::unlimited();
1446 let policy = FetchPolicy::local();
1447 let options = QueryOptions::default().rerank(Some(1));
1449 let segment = RangedSegment::open(&store, "docs", &id, DIM, &budget, &policy, None)
1450 .await
1451 .expect("open");
1452 let dishonest = RepeatsRowZero;
1453 let sources = vec![Source::Indexed(Box::new(Indexed {
1454 segment,
1455 algorithm: &dishonest,
1456 index_path: index::index_path("docs", &id, 1),
1457 }))];
1458 let mut q = probe_query(&store, &[0.0, 0.0], &budget, &policy, &options);
1459 q.top_k = 3; let bound = crate::bound::Bound::new(q.top_k);
1462 let err = match search_source(&q, &sources, 0, &bound).await {
1463 Ok(_) => panic!("a cursor that repeats a row across batches must not be trusted"),
1464 Err(e) => e,
1465 };
1466 assert!(
1467 matches!(err, ItzmaError::CorruptIndex { .. }),
1468 "a cursor that repeats a row across batches must not be trusted: {err:?}"
1469 );
1470 }
1471}