1use std::collections::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::budget::ReadBudget;
37use crate::cpu::{self, Cost, Lane};
38use crate::decoded::{DecodedRef, What};
39use crate::document::SparseVector;
40use crate::error::{ItzmaError, Result};
41use crate::fetch::FetchPolicy;
42use crate::layer::Layer;
43use crate::manifest::Manifest;
44use crate::predicate::Predicate;
45use crate::search::Hit;
46use crate::segment::{Held, RangedSegment};
47use crate::sparse;
48use crate::sparse_index::{self, TermDirectory};
49
50const FETCH_CONCURRENCY: usize = 16;
52
53#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
59#[serde(default)]
60#[non_exhaustive]
61pub struct SparseQueryOptions {
62 pub filter: Option<Predicate>,
65}
66
67impl SparseQueryOptions {
68 #[must_use]
70 pub fn filter(mut self, filter: Option<Predicate>) -> Self {
71 self.filter = filter;
72 self
73 }
74}
75
76pub(crate) fn validate(query: &SparseVector, top_k: usize) -> Result<()> {
83 if top_k == 0 {
84 return Err(ItzmaError::InvalidQuery("top_k must be at least 1"));
85 }
86 if query.is_empty() {
87 return Err(ItzmaError::InvalidQuery(
88 "the sparse query vector must not be empty",
89 ));
90 }
91 if query.iter().any(|(_, weight)| !weight.is_finite()) {
92 return Err(ItzmaError::InvalidQuery(
93 "the sparse query vector has a non-finite weight",
94 ));
95 }
96 Ok(())
97}
98
99fn weights_of(query: &SparseVector) -> HashMap<u32, f32> {
103 let mut weights: HashMap<u32, f32> = HashMap::with_capacity(query.len());
104 for &(term, weight) in query {
105 *weights.entry(term).or_insert(0.0) += weight;
106 }
107 weights
108}
109
110pub(crate) struct Query<'a> {
112 pub(crate) store: &'a dyn ObjectStore,
113 pub(crate) namespace: &'a str,
114 pub(crate) dim: usize,
115 pub(crate) query: &'a SparseVector,
116 pub(crate) top_k: usize,
117 pub(crate) filter: Option<&'a Predicate>,
118 pub(crate) budget: &'a ReadBudget,
119 pub(crate) policy: &'a FetchPolicy,
120 pub(crate) decoded: Option<&'a DecodedRef>,
123}
124
125enum Step<'a> {
127 Indexed { id: &'a str, generation: u32 },
129 Flat(&'a [String]),
131}
132
133enum Source<'a> {
135 Indexed(Box<Indexed<'a>>),
136 Flat(Arc<Layer>),
139}
140
141struct Indexed<'a> {
142 segment: RangedSegment<'a>,
143 index_path: Path,
144 dir: Arc<TermDirectory>,
145}
146
147enum Attrs {
149 Have(Option<serde_json::Value>),
150 Row(u32),
151}
152
153struct Scored {
156 distance: f32,
157 id: String,
158 source: usize,
159 attrs: Attrs,
160}
161
162fn plan<'a>(manifest: &'a Manifest) -> Vec<Step<'a>> {
166 let live = &manifest.live_segments;
167 let mut steps = Vec::new();
168 let mut run_start = 0;
169 for (at, id) in live.iter().enumerate() {
170 if let Some(entry) = manifest.sparse_indexes.get(id) {
171 if run_start < at {
172 steps.push(Step::Flat(&live[run_start..at]));
173 }
174 steps.push(Step::Indexed {
175 id,
176 generation: entry.generation,
177 });
178 run_start = at + 1;
179 }
180 }
181 if run_start < live.len() {
182 steps.push(Step::Flat(&live[run_start..]));
183 }
184 steps
185}
186
187pub(crate) async fn run<'a>(
196 q: &Query<'a>,
197 manifest: &'a Manifest,
198 tail: impl Future<Output = Result<Arc<Layer>>>,
199) -> Result<Vec<Hit>> {
200 let steps = plan(manifest);
201 let (mut sources, tail) = futures::try_join!(open_sources(q, steps), tail)?;
204 if !tail.is_empty() {
205 sources.push(Source::Flat(tail));
206 }
207
208 let weights = weights_of(q.query);
209 let sources = &sources;
210 let weights = &weights;
211 let mut live: Vec<Scored> =
212 try_join_all((0..sources.len()).map(|at| search_source(q, sources, at, weights)))
213 .await?
214 .into_iter()
215 .flatten()
216 .collect();
217 live.sort_by(|a, b| {
218 a.distance
219 .total_cmp(&b.distance)
220 .then_with(|| a.id.cmp(&b.id))
221 });
222 live.truncate(q.top_k);
223 finish(sources, live).await
224}
225
226async fn open_sources<'a>(q: &Query<'a>, steps: Vec<Step<'a>>) -> Result<Vec<Source<'a>>> {
227 stream::iter(0..steps.len())
231 .map(|at| open_source(q, &steps[at]))
232 .buffered(FETCH_CONCURRENCY)
233 .try_collect()
234 .await
235}
236
237async fn open_source<'a>(q: &Query<'a>, step: &Step<'a>) -> Result<Source<'a>> {
238 match *step {
239 Step::Indexed { id, generation } => {
240 let segment = RangedSegment::open(
241 q.store,
242 q.namespace,
243 id,
244 q.dim,
245 q.budget,
246 q.policy,
247 q.decoded,
248 )
249 .await?;
250 let index_path = sparse_index::sparse_index_path(q.namespace, id, generation);
251 let rows = segment.doc_count();
252 let load = || async {
253 let (_prefix, dir) =
254 sparse_index::open(q.store, q.budget, &index_path, rows).await?;
255 let weight = dir.weight();
256 Ok((dir, weight))
257 };
258 let dir = match q.decoded {
259 Some(decoded) => {
260 decoded
261 .get_or_load(&index_path, What::SparseDirectory, load)
262 .await?
263 }
264 None => Arc::new(load().await?.0),
265 };
266 Ok(Source::Indexed(Box::new(Indexed {
267 segment,
268 index_path,
269 dir,
270 })))
271 }
272 Step::Flat(ids) => Ok(Source::Flat(Arc::new(
273 sparse::read_all_with_sparse(
274 q.store,
275 q.namespace,
276 ids,
277 q.dim,
278 q.budget,
279 q.policy,
280 Lane::Query,
281 )
282 .await?,
283 ))),
284 }
285}
286
287async fn search_source(
288 q: &Query<'_>,
289 sources: &[Source<'_>],
290 at: usize,
291 weights: &HashMap<u32, f32>,
292) -> Result<Vec<Scored>> {
293 match &sources[at] {
294 Source::Indexed(source) => evaluate_indexed(q, sources, at, source, weights).await,
295 Source::Flat(layer) => evaluate_flat(q, sources, at, layer, weights).await,
296 }
297}
298
299async fn evaluate_indexed(
303 q: &Query<'_>,
304 sources: &[Source<'_>],
305 at: usize,
306 source: &Indexed<'_>,
307 weights: &HashMap<u32, f32>,
308) -> Result<Vec<Scored>> {
309 let mut ordered: Vec<(u32, f32)> = weights.iter().map(|(&t, &w)| (t, w)).collect();
315 ordered.sort_unstable_by_key(|&(term, _)| term);
316 let mut postings: Vec<(f32, Vec<(u32, f32)>)> = Vec::new();
317 for (term, weight) in ordered {
318 let Some(entry) = source.dir.find(term) else {
319 continue;
320 };
321 let found =
322 sparse_index::postings_of(q.store, q.budget, &source.index_path, &source.dir, entry)
323 .await?;
324 postings.push((weight, found));
325 }
326 let rows_in_segment = source.segment.doc_count();
327 let path = source.index_path.to_string();
328 let cost = Cost::Distances {
329 rows: postings.iter().map(|(_, p)| p.len()).sum(),
330 dim: 1,
331 };
332 let ranked = cpu::run(Lane::Query, cost, move || {
333 score_postings(postings, rows_in_segment, &path)
334 })
335 .await?;
336
337 let mut kept: Vec<Scored> = Vec::new();
345 let mut next = 0;
346 let mut chunk = q.top_k;
347 while next < ranked.len() {
348 if kept.len() >= q.top_k && ranked[next].1 < -kept[q.top_k - 1].distance {
349 break;
350 }
351 let end = (next + chunk).min(ranked.len());
352 let rows: Vec<u32> = ranked[next..end].iter().map(|(row, _)| *row).collect();
353 let ids = source.segment.ids_of(&rows).await?;
354 let live = unshadowed(sources, at, &ids).await?;
355 let survivors: Vec<(u32, f32, String)> = ranked[next..end]
356 .iter()
357 .zip(ids)
358 .zip(live)
359 .filter_map(|(((row, score), id), live)| live.then_some((*row, *score, id)))
360 .collect();
361 let rows: Vec<u32> = survivors.iter().map(|(row, _, _)| *row).collect();
364 let decided = match q.filter {
367 Some(predicate) => source.segment.eligible_of(predicate, &rows).await?,
368 None => None,
369 };
370 let fetched = match (q.filter, &decided) {
371 (Some(_), None) => Some(source.segment.attrs_of(&rows).await?),
372 _ => None,
373 };
374 for (n, (row, score, id)) in survivors.into_iter().enumerate() {
375 let attrs = match (&fetched, q.filter) {
376 (Some(fetched), Some(predicate)) => {
377 let value = fetched[n].clone();
378 if !predicate.matches(value.as_ref()) {
379 continue;
380 }
381 Attrs::Have(value)
382 }
383 _ => {
384 if decided.as_ref().is_some_and(|decided| !decided[n]) {
385 continue;
386 }
387 Attrs::Row(row)
388 }
389 };
390 kept.push(Scored {
391 distance: -score,
392 id,
393 source: at,
394 attrs,
395 });
396 }
397 next = end;
398 chunk = chunk.saturating_mul(2);
399 }
400 Ok(kept)
401}
402
403fn score_postings(
411 postings: Vec<(f32, Vec<(u32, f32)>)>,
412 rows_in_segment: u64,
413 path: &str,
414) -> Result<Vec<(u32, f32)>> {
415 let mut scores: HashMap<u32, f32> = HashMap::new();
416 for (weight, found) in postings {
417 for (row, doc_weight) in found {
418 if u64::from(row) >= rows_in_segment {
419 return Err(ItzmaError::CorruptSparseIndex {
420 path: path.to_string(),
421 reason: format!(
422 "the index named row {row}, the segment has {rows_in_segment} rows"
423 ),
424 });
425 }
426 *scores.entry(row).or_insert(0.0) += weight * doc_weight;
427 }
428 }
429 let mut ranked: Vec<(u32, f32)> = scores.into_iter().collect();
430 ranked.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
431 Ok(ranked)
432}
433
434fn flat_scores(
439 layer: &Layer,
440 weights: &HashMap<u32, f32>,
441 filter: Option<&Predicate>,
442) -> Vec<Option<f32>> {
443 let docs: Vec<&crate::document::Document> = layer.docs().collect();
444 let chunks = cpu::chunked(&docs, cpu::FLAT_CHUNK, |chunk| {
445 chunk
446 .iter()
447 .map(|doc| {
448 if !filter.is_none_or(|p| p.matches(doc.attrs.as_ref())) {
449 return None;
450 }
451 let terms = doc.sparse.as_ref()?;
452 let mut shared = false;
453 let mut score = 0.0f32;
454 for (term, doc_weight) in terms {
455 if let Some(weight) = weights.get(term) {
456 shared = true;
457 score += weight * doc_weight;
458 }
459 }
460 shared.then_some(-score)
461 })
462 .collect::<Vec<_>>()
463 });
464 let mut out = Vec::with_capacity(docs.len());
465 for chunk in chunks {
466 out.extend(chunk);
467 }
468 out
469}
470
471async fn evaluate_flat(
476 q: &Query<'_>,
477 sources: &[Source<'_>],
478 at: usize,
479 layer: &Arc<Layer>,
480 weights: &HashMap<u32, f32>,
481) -> Result<Vec<Scored>> {
482 let terms: usize = layer
484 .docs()
485 .map(|doc| doc.sparse.as_ref().map_or(0, Vec::len))
486 .sum();
487 let (owned, weights, filter) = (layer.clone(), weights.clone(), q.filter.cloned());
488 let scores = cpu::run(
489 Lane::Query,
490 Cost::Distances {
491 rows: terms,
492 dim: 1,
493 },
494 move || flat_scores(&owned, &weights, filter.as_ref()),
495 )
496 .await;
497 debug_assert_eq!(scores.len(), layer.doc_count());
500 let scored: Vec<(f32, &crate::document::Document)> = layer
501 .docs()
502 .zip(scores)
503 .filter_map(|(doc, score)| score.map(|s| (s, doc)))
504 .collect();
505 let ids: Vec<String> = scored.iter().map(|(_, doc)| doc.id.clone()).collect();
506 let live = unshadowed(sources, at, &ids).await?;
507 Ok(scored
508 .into_iter()
509 .zip(live)
510 .filter(|(_, live)| *live)
511 .map(|((distance, doc), _)| Scored {
512 distance,
513 id: doc.id.clone(),
514 source: at,
515 attrs: Attrs::Have(doc.attrs.clone()),
516 })
517 .collect())
518}
519
520async fn unshadowed(sources: &[Source<'_>], at: usize, ids: &[String]) -> Result<Vec<bool>> {
524 stream::iter(ids.iter().cloned())
527 .map(|id| async move { is_live(sources, at, &id).await })
528 .buffered(FETCH_CONCURRENCY)
529 .try_collect()
530 .await
531}
532
533async fn is_live(sources: &[Source<'_>], at: usize, id: &str) -> Result<bool> {
534 let newer = &sources[at + 1..];
535 if newer
537 .iter()
538 .any(|source| matches!(source, Source::Flat(layer) if layer.holds(id)))
539 {
540 return Ok(false);
541 }
542 for source in newer {
543 if let Source::Indexed(newer) = source {
544 if newer.segment.holds(id).await? != Held::No {
545 return Ok(false);
546 }
547 }
548 }
549 Ok(true)
550}
551
552async fn finish(sources: &[Source<'_>], live: Vec<Scored>) -> Result<Vec<Hit>> {
555 let mut wanted: HashMap<usize, Vec<u32>> = HashMap::new();
556 for hit in &live {
557 if let Attrs::Row(row) = hit.attrs {
558 wanted.entry(hit.source).or_default().push(row);
559 }
560 }
561 let fetched = try_join_all(
562 wanted
563 .into_iter()
564 .map(|(at, rows)| fetch_attrs(sources, at, rows)),
565 )
566 .await?;
567 let mut attrs: HashMap<(usize, u32), Option<serde_json::Value>> = HashMap::new();
568 for (at, rows, values) in fetched {
569 attrs.extend(rows.into_iter().zip(values).map(|(row, v)| ((at, row), v)));
570 }
571 Ok(live
572 .into_iter()
573 .map(|hit| Hit {
574 attrs: match hit.attrs {
575 Attrs::Have(value) => value,
576 Attrs::Row(row) => attrs.remove(&(hit.source, row)).flatten(),
577 },
578 id: hit.id,
579 distance: hit.distance,
580 })
581 .collect())
582}
583
584async fn fetch_attrs(
585 sources: &[Source<'_>],
586 at: usize,
587 rows: Vec<u32>,
588) -> Result<(usize, Vec<u32>, Vec<Option<serde_json::Value>>)> {
589 let Source::Indexed(source) = &sources[at] else {
590 return Ok((at, rows, Vec::new()));
591 };
592 let values = source.segment.attrs_of(&rows).await?;
593 Ok((at, rows, values))
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599 use crate::document::{Document, WalOp};
600
601 #[tokio::test]
602 async fn sparse_flat_scores_on_the_pool_equal_the_inline_ones() {
603 let mut layer = Layer::new();
605 for i in 0..20_000u32 {
606 layer.apply(WalOp::Upsert(Document {
607 id: format!("d{i:06}"),
608 vector: vec![0.0],
609 attrs: Some(serde_json::json!({ "active": i % 3 == 0 })),
610 sparse: Some(
611 (0..100)
612 .map(|t| ((i + t * 7) % 500, 1.0 + (t % 5) as f32))
613 .collect(),
614 ),
615 }));
616 }
617 let layer = Arc::new(layer);
618 let weights: HashMap<u32, f32> = [(3, 1.0), (10, 0.5), (499, 2.0)].into();
619 for filter in [None, Some(Predicate::is_true("active"))] {
620 let inline = flat_scores(&layer, &weights, filter.as_ref());
621 assert_eq!(inline.len(), 20_000);
622 assert!(inline.iter().any(Option::is_some) && inline.iter().any(Option::is_none));
623 let (l, w, f) = (layer.clone(), weights.clone(), filter.clone());
624 let pooled = cpu::run(
625 Lane::Query,
626 Cost::Distances {
627 rows: 2_000_000,
628 dim: 1,
629 },
630 move || flat_scores(&l, &w, f.as_ref()),
631 )
632 .await;
633 assert_eq!(pooled, inline);
634 }
635 }
636
637 #[tokio::test]
638 async fn scored_postings_on_the_pool_equal_the_inline_ones() {
639 let postings: Vec<(f32, Vec<(u32, f32)>)> = (0..30u32)
640 .map(|t| {
641 (
642 1.0 + t as f32 / 10.0,
643 (0..50_000)
644 .step_by(1 + t as usize)
645 .map(|r| (r, 0.5))
646 .collect(),
647 )
648 })
649 .collect();
650 let inline = score_postings(postings.clone(), 50_000, "p").expect("score");
651 let p = postings.clone();
652 let pooled = cpu::run(
653 Lane::Query,
654 Cost::Distances {
655 rows: 2_000_000,
656 dim: 1,
657 },
658 move || score_postings(p, 50_000, "p"),
659 )
660 .await
661 .expect("score");
662 assert_eq!(pooled, inline);
663 assert!(
664 inline
665 .windows(2)
666 .all(|w| w[0].1 > w[1].1 || (w[0].1 == w[1].1 && w[0].0 < w[1].0))
667 );
668 let err = score_postings(postings, 10, "p").expect_err("row past the segment");
669 assert!(matches!(err, ItzmaError::CorruptSparseIndex { .. }));
670 }
671
672 #[test]
673 fn validate_refuses_what_cannot_run() {
674 let ok: SparseVector = vec![(1, 1.0)];
675 assert!(validate(&ok, 1).is_ok());
676 for (query, top_k) in [
677 (ok.clone(), 0),
678 (Vec::new(), 1),
679 (vec![(1, f32::NAN)], 1),
680 (vec![(1, f32::INFINITY)], 1),
681 ] {
682 assert!(
683 matches!(validate(&query, top_k), Err(ItzmaError::InvalidQuery(_))),
684 "{query:?} / {top_k}"
685 );
686 }
687 }
688
689 #[test]
690 fn a_repeated_query_term_counts_as_the_sum_of_its_weights() {
691 let weights = weights_of(&vec![(3, 1.0), (5, 2.0), (3, 0.5)]);
692 assert_eq!(weights.len(), 2);
693 assert_eq!(weights[&3], 1.5);
694 assert_eq!(weights[&5], 2.0);
695 }
696}