1use 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
56pub const DEFAULT_RERANK: usize = 4;
59
60const FETCH_CONCURRENCY: usize = 16;
62const WIDEN: usize = 8;
65
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80#[serde(default)]
81#[non_exhaustive]
82pub struct QueryOptions {
83 pub rerank: Option<usize>,
89 pub nprobe: Option<usize>,
93 pub exact: bool,
96 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 #[must_use]
119 pub fn rerank(mut self, rerank: Option<usize>) -> Self {
120 self.rerank = rerank;
121 self
122 }
123
124 #[must_use]
126 pub fn nprobe(mut self, nprobe: Option<usize>) -> Self {
127 self.nprobe = nprobe;
128 self
129 }
130
131 #[must_use]
133 pub fn exact(mut self, exact: bool) -> Self {
134 self.exact = exact;
135 self
136 }
137
138 #[must_use]
140 pub fn filter(mut self, filter: Option<Predicate>) -> Self {
141 self.filter = filter;
142 self
143 }
144
145 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
157pub(crate) trait Registry: Sync {
162 fn algorithm(&self, kind: &str) -> Option<&dyn Algorithm>;
163}
164
165pub(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
174fn 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
185pub(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 pub(crate) decoded: Option<&'a DecodedRef>,
200 pub(crate) attrs: &'a AttrSchema,
202}
203
204impl Query<'_> {
205 fn filter(&self) -> Option<&Predicate> {
207 self.options.filter.as_ref()
208 }
209
210 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
220enum Step<'a> {
222 Indexed {
224 id: &'a str,
225 generation: u32,
226 algorithm: &'a dyn Algorithm,
227 attr_generation: Option<u32>,
229 },
230 Flat(&'a [String]),
232}
233
234enum Source<'a> {
236 Indexed(Box<Indexed<'a>>),
237 Columnar(Run),
239 Flat(Arc<Layer>),
242}
243
244struct Run {
246 views: Vec<Arc<SegmentView>>,
247}
248
249impl Run {
250 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 attr_candidates: Option<Vec<u32>>,
265}
266
267enum Attrs {
270 Have(Option<serde_json::Value>),
271 Row(u32),
272 InView {
274 view: usize,
275 row: usize,
276 },
277}
278
279struct Scored {
281 distance: f32,
282 id: String,
283 source: usize,
284 attrs: Attrs,
285}
286
287fn plan<'a>(q: &Query<'a>, manifest: &'a Manifest) -> Vec<Step<'a>> {
291 let live = &manifest.live_segments;
292 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
329pub(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 let bound = crate::bound::Bound::new(q.top_k);
350 let steps = plan(q, manifest);
351 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 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
390async 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
447async 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
461async 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
537async 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 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 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 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
618fn 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 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 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 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
707const SPAN: usize = cpu::FLAT_CHUNK;
710
711pub(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 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
775async 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 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 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
844pub(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
858fn 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
882async fn unshadowed(sources: &[Source<'_>], at: usize, ids: &[String]) -> Result<Vec<bool>> {
885 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 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
914async 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#[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 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 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 #[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 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 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 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, 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 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 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 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 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 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 }, Candidate {
1393 row: 0,
1394 distance: 1.0,
1395 },
1396 Candidate {
1397 row: 2,
1398 distance: 9.0,
1399 }, ]);
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 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 #[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; async move {
1474 Ok(index::Batch {
1475 candidates: vec![Candidate {
1476 row: 0, 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 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; 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}