1use std::collections::{BTreeSet, HashMap};
28use std::sync::Arc;
29
30use futures::future::try_join_all;
31use futures::stream::{self, StreamExt, TryStreamExt};
32use object_store::ObjectStore;
33use object_store::path::Path;
34use serde::{Deserialize, Serialize};
35
36use crate::attr_index;
37use crate::attrs::AttrSchema;
38use crate::budget::ReadBudget;
39use crate::cpu::{self, Cost, Lane};
40use crate::decoded::{DecodedRef, What};
41use crate::document::SparseVector;
42use crate::error::{ItzmaError, Result};
43use crate::fetch::FetchPolicy;
44use crate::layer::Layer;
45use crate::manifest::Manifest;
46use crate::predicate::Predicate;
47use crate::search::Hit;
48use crate::segment::{Held, RangedSegment};
49use crate::sparse;
50use crate::sparse_index::{self, TermDirectory};
51
52const FETCH_CONCURRENCY: usize = 16;
54
55#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
61#[serde(default)]
62#[non_exhaustive]
63pub struct SparseQueryOptions {
64 pub filter: Option<Predicate>,
67}
68
69impl SparseQueryOptions {
70 #[must_use]
72 pub fn filter(mut self, filter: Option<Predicate>) -> Self {
73 self.filter = filter;
74 self
75 }
76}
77
78pub(crate) fn validate(query: &SparseVector, top_k: usize) -> Result<()> {
85 if top_k == 0 {
86 return Err(ItzmaError::InvalidQuery("top_k must be at least 1"));
87 }
88 if query.is_empty() {
89 return Err(ItzmaError::InvalidQuery(
90 "the sparse query vector must not be empty",
91 ));
92 }
93 if query.iter().any(|(_, weight)| !weight.is_finite()) {
94 return Err(ItzmaError::InvalidQuery(
95 "the sparse query vector has a non-finite weight",
96 ));
97 }
98 Ok(())
99}
100
101fn weights_of(query: &SparseVector) -> HashMap<u32, f32> {
105 let mut weights: HashMap<u32, f32> = HashMap::with_capacity(query.len());
106 for &(term, weight) in query {
107 *weights.entry(term).or_insert(0.0) += weight;
108 }
109 weights
110}
111
112pub(crate) struct Query<'a> {
114 pub(crate) store: &'a dyn ObjectStore,
115 pub(crate) namespace: &'a str,
116 pub(crate) dim: usize,
117 pub(crate) query: &'a SparseVector,
118 pub(crate) top_k: usize,
119 pub(crate) filter: Option<&'a Predicate>,
120 pub(crate) budget: &'a ReadBudget,
121 pub(crate) policy: &'a FetchPolicy,
122 pub(crate) decoded: Option<&'a DecodedRef>,
125 pub(crate) attrs: &'a AttrSchema,
127}
128
129impl Query<'_> {
130 fn resolvable_filter(&self) -> Option<&Predicate> {
133 let predicate = self.filter?;
134 let indexed: BTreeSet<&str> = self.attrs.indexed_field_names().collect();
135 attr_index::could_resolve(predicate, &indexed).then_some(predicate)
136 }
137}
138
139enum Step<'a> {
141 Indexed {
143 id: &'a str,
144 generation: u32,
145 attr_generation: Option<u32>,
147 },
148 Flat(&'a [String]),
150}
151
152enum Source<'a> {
154 Indexed(Box<Indexed<'a>>),
155 Flat(Arc<Layer>),
158}
159
160struct Indexed<'a> {
161 segment: RangedSegment<'a>,
162 index_path: Path,
163 dir: Arc<TermDirectory>,
164 attr_candidates: Option<Vec<u32>>,
168}
169
170enum Attrs {
172 Have(Option<serde_json::Value>),
173 Row(u32),
174}
175
176struct Scored {
179 distance: f32,
180 id: String,
181 source: usize,
182 attrs: Attrs,
183}
184
185fn plan<'a>(manifest: &'a Manifest) -> Vec<Step<'a>> {
189 let live = &manifest.live_segments;
190 let mut steps = Vec::new();
191 let mut run_start = 0;
192 for (at, id) in live.iter().enumerate() {
193 if let Some(entry) = manifest.sparse_indexes.get(id) {
194 if run_start < at {
195 steps.push(Step::Flat(&live[run_start..at]));
196 }
197 steps.push(Step::Indexed {
198 id,
199 generation: entry.generation,
200 attr_generation: manifest.attr_indexes.get(id).map(|e| e.generation),
201 });
202 run_start = at + 1;
203 }
204 }
205 if run_start < live.len() {
206 steps.push(Step::Flat(&live[run_start..]));
207 }
208 steps
209}
210
211pub(crate) async fn run<'a>(
220 q: &Query<'a>,
221 manifest: &'a Manifest,
222 tail: impl Future<Output = Result<Arc<Layer>>>,
223) -> Result<Vec<Hit>> {
224 let steps = plan(manifest);
225 let (mut sources, tail) = futures::try_join!(open_sources(q, steps), tail)?;
228 if !tail.is_empty() {
229 sources.push(Source::Flat(tail));
230 }
231
232 let weights = weights_of(q.query);
233 let sources = &sources;
234 let weights = &weights;
235 let mut live: Vec<Scored> =
236 try_join_all((0..sources.len()).map(|at| search_source(q, sources, at, weights)))
237 .await?
238 .into_iter()
239 .flatten()
240 .collect();
241 live.sort_by(|a, b| {
242 a.distance
243 .total_cmp(&b.distance)
244 .then_with(|| a.id.cmp(&b.id))
245 });
246 live.truncate(q.top_k);
247 finish(sources, live).await
248}
249
250async fn open_sources<'a>(q: &Query<'a>, steps: Vec<Step<'a>>) -> Result<Vec<Source<'a>>> {
251 stream::iter(0..steps.len())
255 .map(|at| open_source(q, &steps[at]))
256 .buffered(FETCH_CONCURRENCY)
257 .try_collect()
258 .await
259}
260
261async fn open_source<'a>(q: &Query<'a>, step: &Step<'a>) -> Result<Source<'a>> {
262 match *step {
263 Step::Indexed {
264 id,
265 generation,
266 attr_generation,
267 } => {
268 let segment = RangedSegment::open(
269 q.store,
270 q.namespace,
271 id,
272 q.dim,
273 q.budget,
274 q.policy,
275 q.decoded,
276 )
277 .await?;
278 let index_path = sparse_index::sparse_index_path(q.namespace, id, generation);
279 let rows = segment.doc_count();
280 let load = || async {
281 let (_prefix, dir) =
282 sparse_index::open(q.store, q.budget, &index_path, rows).await?;
283 let weight = dir.weight();
284 Ok((dir, weight))
285 };
286 let dir = match q.decoded {
287 Some(decoded) => {
288 decoded
289 .get_or_load(&index_path, What::SparseDirectory, load)
290 .await?
291 }
292 None => Arc::new(load().await?.0),
293 };
294 let attr_candidates = match (attr_generation, q.resolvable_filter()) {
295 (Some(attr_gen), Some(predicate)) => {
296 let path = attr_index::attr_index_path(q.namespace, id, attr_gen);
297 let idx =
298 attr_index::open(q.store, q.budget, &path, segment.doc_count()).await?;
299 attr_index::index_candidates(predicate, &idx)
300 }
301 _ => None,
302 };
303 Ok(Source::Indexed(Box::new(Indexed {
304 segment,
305 index_path,
306 dir,
307 attr_candidates,
308 })))
309 }
310 Step::Flat(ids) => Ok(Source::Flat(Arc::new(
311 sparse::read_all_with_sparse(
312 q.store,
313 q.namespace,
314 ids,
315 q.dim,
316 q.budget,
317 q.policy,
318 Lane::Query,
319 )
320 .await?,
321 ))),
322 }
323}
324
325async fn search_source(
326 q: &Query<'_>,
327 sources: &[Source<'_>],
328 at: usize,
329 weights: &HashMap<u32, f32>,
330) -> Result<Vec<Scored>> {
331 match &sources[at] {
332 Source::Indexed(source) => evaluate_indexed(q, sources, at, source, weights).await,
333 Source::Flat(layer) => evaluate_flat(q, sources, at, layer, weights).await,
334 }
335}
336
337async fn evaluate_indexed(
341 q: &Query<'_>,
342 sources: &[Source<'_>],
343 at: usize,
344 source: &Indexed<'_>,
345 weights: &HashMap<u32, f32>,
346) -> Result<Vec<Scored>> {
347 let mut ordered: Vec<(u32, f32)> = weights.iter().map(|(&t, &w)| (t, w)).collect();
353 ordered.sort_unstable_by_key(|&(term, _)| term);
354 let mut postings: Vec<(f32, Vec<(u32, f32)>)> = Vec::new();
355 for (term, weight) in ordered {
356 let Some(entry) = source.dir.find(term) else {
357 continue;
358 };
359 let found =
360 sparse_index::postings_of(q.store, q.budget, &source.index_path, &source.dir, entry)
361 .await?;
362 postings.push((weight, found));
363 }
364 let rows_in_segment = source.segment.doc_count();
365 let path = source.index_path.to_string();
366 let cost = Cost::Distances {
367 rows: postings.iter().map(|(_, p)| p.len()).sum(),
368 dim: 1,
369 };
370 let ranked = cpu::run(Lane::Query, cost, move || {
371 score_postings(postings, rows_in_segment, &path)
372 })
373 .await?;
374
375 let mut kept: Vec<Scored> = Vec::new();
383 let mut next = 0;
384 let mut chunk = q.top_k;
385 while next < ranked.len() {
386 if kept.len() >= q.top_k && ranked[next].1 < -kept[q.top_k - 1].distance {
387 break;
388 }
389 let end = (next + chunk).min(ranked.len());
390 let rows: Vec<u32> = ranked[next..end].iter().map(|(row, _)| *row).collect();
391 let ids = source.segment.ids_of(&rows).await?;
392 let live = unshadowed(sources, at, &ids).await?;
393 let survivors: Vec<(u32, f32, String)> = ranked[next..end]
394 .iter()
395 .zip(ids)
396 .zip(live)
397 .filter_map(|(((row, score), id), live)| live.then_some((*row, *score, id)))
398 .collect();
399 let survivors: Vec<(u32, f32, String)> = match &source.attr_candidates {
402 Some(candidates) => {
403 let allowed: std::collections::HashSet<u32> = candidates.iter().copied().collect();
404 survivors
405 .into_iter()
406 .filter(|(row, _, _)| allowed.contains(row))
407 .collect()
408 }
409 None => survivors,
410 };
411 let rows: Vec<u32> = survivors.iter().map(|(row, _, _)| *row).collect();
414 let decided = match q.filter {
417 Some(predicate) => source.segment.eligible_of(predicate, &rows).await?,
418 None => None,
419 };
420 let fetched = match (q.filter, &decided) {
421 (Some(_), None) => Some(source.segment.attrs_of(&rows).await?),
422 _ => None,
423 };
424 for (n, (row, score, id)) in survivors.into_iter().enumerate() {
425 let attrs = match (&fetched, q.filter) {
426 (Some(fetched), Some(predicate)) => {
427 let value = fetched[n].clone();
428 if !predicate.matches(value.as_ref()) {
429 continue;
430 }
431 Attrs::Have(value)
432 }
433 _ => {
434 if decided.as_ref().is_some_and(|decided| !decided[n]) {
435 continue;
436 }
437 Attrs::Row(row)
438 }
439 };
440 kept.push(Scored {
441 distance: -score,
442 id,
443 source: at,
444 attrs,
445 });
446 }
447 next = end;
448 chunk = chunk.saturating_mul(2);
449 }
450 Ok(kept)
451}
452
453fn score_postings(
461 postings: Vec<(f32, Vec<(u32, f32)>)>,
462 rows_in_segment: u64,
463 path: &str,
464) -> Result<Vec<(u32, f32)>> {
465 let mut scores: HashMap<u32, f32> = HashMap::new();
466 for (weight, found) in postings {
467 for (row, doc_weight) in found {
468 if u64::from(row) >= rows_in_segment {
469 return Err(ItzmaError::CorruptSparseIndex {
470 path: path.to_string(),
471 reason: format!(
472 "the index named row {row}, the segment has {rows_in_segment} rows"
473 ),
474 });
475 }
476 *scores.entry(row).or_insert(0.0) += weight * doc_weight;
477 }
478 }
479 let mut ranked: Vec<(u32, f32)> = scores.into_iter().collect();
480 ranked.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
481 Ok(ranked)
482}
483
484fn flat_scores(
489 layer: &Layer,
490 weights: &HashMap<u32, f32>,
491 filter: Option<&Predicate>,
492) -> Vec<Option<f32>> {
493 let docs: Vec<&crate::document::Document> = layer.docs().collect();
494 let chunks = cpu::chunked(&docs, cpu::FLAT_CHUNK, |chunk| {
495 chunk
496 .iter()
497 .map(|doc| {
498 if !filter.is_none_or(|p| p.matches(doc.attrs.as_ref())) {
499 return None;
500 }
501 let terms = doc.sparse.as_ref()?;
502 let mut shared = false;
503 let mut score = 0.0f32;
504 for (term, doc_weight) in terms {
505 if let Some(weight) = weights.get(term) {
506 shared = true;
507 score += weight * doc_weight;
508 }
509 }
510 shared.then_some(-score)
511 })
512 .collect::<Vec<_>>()
513 });
514 let mut out = Vec::with_capacity(docs.len());
515 for chunk in chunks {
516 out.extend(chunk);
517 }
518 out
519}
520
521async fn evaluate_flat(
526 q: &Query<'_>,
527 sources: &[Source<'_>],
528 at: usize,
529 layer: &Arc<Layer>,
530 weights: &HashMap<u32, f32>,
531) -> Result<Vec<Scored>> {
532 let terms: usize = layer
534 .docs()
535 .map(|doc| doc.sparse.as_ref().map_or(0, Vec::len))
536 .sum();
537 let (owned, weights, filter) = (layer.clone(), weights.clone(), q.filter.cloned());
538 let scores = cpu::run(
539 Lane::Query,
540 Cost::Distances {
541 rows: terms,
542 dim: 1,
543 },
544 move || flat_scores(&owned, &weights, filter.as_ref()),
545 )
546 .await;
547 debug_assert_eq!(scores.len(), layer.doc_count());
550 let scored: Vec<(f32, &crate::document::Document)> = layer
551 .docs()
552 .zip(scores)
553 .filter_map(|(doc, score)| score.map(|s| (s, doc)))
554 .collect();
555 let ids: Vec<String> = scored.iter().map(|(_, doc)| doc.id.clone()).collect();
556 let live = unshadowed(sources, at, &ids).await?;
557 Ok(scored
558 .into_iter()
559 .zip(live)
560 .filter(|(_, live)| *live)
561 .map(|((distance, doc), _)| Scored {
562 distance,
563 id: doc.id.clone(),
564 source: at,
565 attrs: Attrs::Have(doc.attrs.clone()),
566 })
567 .collect())
568}
569
570async fn unshadowed(sources: &[Source<'_>], at: usize, ids: &[String]) -> Result<Vec<bool>> {
574 stream::iter(ids.iter().cloned())
577 .map(|id| async move { is_live(sources, at, &id).await })
578 .buffered(FETCH_CONCURRENCY)
579 .try_collect()
580 .await
581}
582
583async fn is_live(sources: &[Source<'_>], at: usize, id: &str) -> Result<bool> {
584 let newer = &sources[at + 1..];
585 if newer
587 .iter()
588 .any(|source| matches!(source, Source::Flat(layer) if layer.holds(id)))
589 {
590 return Ok(false);
591 }
592 for source in newer {
593 if let Source::Indexed(newer) = source {
594 if newer.segment.holds(id).await? != Held::No {
595 return Ok(false);
596 }
597 }
598 }
599 Ok(true)
600}
601
602async fn finish(sources: &[Source<'_>], live: Vec<Scored>) -> Result<Vec<Hit>> {
605 let mut wanted: HashMap<usize, Vec<u32>> = HashMap::new();
606 for hit in &live {
607 if let Attrs::Row(row) = hit.attrs {
608 wanted.entry(hit.source).or_default().push(row);
609 }
610 }
611 let fetched = try_join_all(
612 wanted
613 .into_iter()
614 .map(|(at, rows)| fetch_attrs(sources, at, rows)),
615 )
616 .await?;
617 let mut attrs: HashMap<(usize, u32), Option<serde_json::Value>> = HashMap::new();
618 for (at, rows, values) in fetched {
619 attrs.extend(rows.into_iter().zip(values).map(|(row, v)| ((at, row), v)));
620 }
621 Ok(live
622 .into_iter()
623 .map(|hit| Hit {
624 attrs: match hit.attrs {
625 Attrs::Have(value) => value,
626 Attrs::Row(row) => attrs.remove(&(hit.source, row)).flatten(),
627 },
628 id: hit.id,
629 distance: hit.distance,
630 })
631 .collect())
632}
633
634async fn fetch_attrs(
635 sources: &[Source<'_>],
636 at: usize,
637 rows: Vec<u32>,
638) -> Result<(usize, Vec<u32>, Vec<Option<serde_json::Value>>)> {
639 let Source::Indexed(source) = &sources[at] else {
640 return Ok((at, rows, Vec::new()));
641 };
642 let values = source.segment.attrs_of(&rows).await?;
643 Ok((at, rows, values))
644}
645
646#[cfg(test)]
647mod tests {
648 use super::*;
649 use crate::document::{Document, WalOp};
650
651 #[tokio::test]
652 async fn sparse_flat_scores_on_the_pool_equal_the_inline_ones() {
653 let mut layer = Layer::new();
655 for i in 0..20_000u32 {
656 layer.apply(WalOp::Upsert(Document {
657 id: format!("d{i:06}"),
658 vector: vec![0.0],
659 attrs: Some(serde_json::json!({ "active": i % 3 == 0 })),
660 sparse: Some(
661 (0..100)
662 .map(|t| ((i + t * 7) % 500, 1.0 + (t % 5) as f32))
663 .collect(),
664 ),
665 }));
666 }
667 let layer = Arc::new(layer);
668 let weights: HashMap<u32, f32> = [(3, 1.0), (10, 0.5), (499, 2.0)].into();
669 for filter in [None, Some(Predicate::is_true("active"))] {
670 let inline = flat_scores(&layer, &weights, filter.as_ref());
671 assert_eq!(inline.len(), 20_000);
672 assert!(inline.iter().any(Option::is_some) && inline.iter().any(Option::is_none));
673 let (l, w, f) = (layer.clone(), weights.clone(), filter.clone());
674 let pooled = cpu::run(
675 Lane::Query,
676 Cost::Distances {
677 rows: 2_000_000,
678 dim: 1,
679 },
680 move || flat_scores(&l, &w, f.as_ref()),
681 )
682 .await;
683 assert_eq!(pooled, inline);
684 }
685 }
686
687 #[tokio::test]
688 async fn scored_postings_on_the_pool_equal_the_inline_ones() {
689 let postings: Vec<(f32, Vec<(u32, f32)>)> = (0..30u32)
690 .map(|t| {
691 (
692 1.0 + t as f32 / 10.0,
693 (0..50_000)
694 .step_by(1 + t as usize)
695 .map(|r| (r, 0.5))
696 .collect(),
697 )
698 })
699 .collect();
700 let inline = score_postings(postings.clone(), 50_000, "p").expect("score");
701 let p = postings.clone();
702 let pooled = cpu::run(
703 Lane::Query,
704 Cost::Distances {
705 rows: 2_000_000,
706 dim: 1,
707 },
708 move || score_postings(p, 50_000, "p"),
709 )
710 .await
711 .expect("score");
712 assert_eq!(pooled, inline);
713 assert!(
714 inline
715 .windows(2)
716 .all(|w| w[0].1 > w[1].1 || (w[0].1 == w[1].1 && w[0].0 < w[1].0))
717 );
718 let err = score_postings(postings, 10, "p").expect_err("row past the segment");
719 assert!(matches!(err, ItzmaError::CorruptSparseIndex { .. }));
720 }
721
722 #[test]
723 fn validate_refuses_what_cannot_run() {
724 let ok: SparseVector = vec![(1, 1.0)];
725 assert!(validate(&ok, 1).is_ok());
726 for (query, top_k) in [
727 (ok.clone(), 0),
728 (Vec::new(), 1),
729 (vec![(1, f32::NAN)], 1),
730 (vec![(1, f32::INFINITY)], 1),
731 ] {
732 assert!(
733 matches!(validate(&query, top_k), Err(ItzmaError::InvalidQuery(_))),
734 "{query:?} / {top_k}"
735 );
736 }
737 }
738
739 #[test]
740 fn a_repeated_query_term_counts_as_the_sum_of_its_weights() {
741 let weights = weights_of(&vec![(3, 1.0), (5, 2.0), (3, 0.5)]);
742 assert_eq!(weights.len(), 2);
743 assert_eq!(weights[&3], 1.5);
744 assert_eq!(weights[&5], 2.0);
745 }
746}