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 postings: Vec<(f32, Vec<(u32, f32)>)> = Vec::new();
310 for (&term, &weight) in weights {
311 let Some(entry) = source.dir.find(term) else {
312 continue;
313 };
314 let found =
315 sparse_index::postings_of(q.store, q.budget, &source.index_path, &source.dir, entry)
316 .await?;
317 postings.push((weight, found));
318 }
319 let rows_in_segment = source.segment.doc_count();
320 let path = source.index_path.to_string();
321 let cost = Cost::Distances {
322 rows: postings.iter().map(|(_, p)| p.len()).sum(),
323 dim: 1,
324 };
325 let ranked = cpu::run(Lane::Query, cost, move || {
326 score_postings(postings, rows_in_segment, &path)
327 })
328 .await?;
329
330 let mut kept: Vec<Scored> = Vec::new();
338 let mut next = 0;
339 let mut chunk = q.top_k;
340 while next < ranked.len() {
341 if kept.len() >= q.top_k && ranked[next].1 < -kept[q.top_k - 1].distance {
342 break;
343 }
344 let end = (next + chunk).min(ranked.len());
345 let rows: Vec<u32> = ranked[next..end].iter().map(|(row, _)| *row).collect();
346 let ids = source.segment.ids_of(&rows).await?;
347 let live = unshadowed(sources, at, &ids).await?;
348 let survivors: Vec<(u32, f32, String)> = ranked[next..end]
349 .iter()
350 .zip(ids)
351 .zip(live)
352 .filter_map(|(((row, score), id), live)| live.then_some((*row, *score, id)))
353 .collect();
354 let fetched = match q.filter {
357 None => None,
358 Some(_) => {
359 let rows: Vec<u32> = survivors.iter().map(|(row, _, _)| *row).collect();
360 Some(source.segment.attrs_of(&rows).await?)
361 }
362 };
363 for (n, (row, score, id)) in survivors.into_iter().enumerate() {
364 let attrs = match (&fetched, q.filter) {
365 (Some(fetched), Some(predicate)) => {
366 let value = fetched[n].clone();
367 if !predicate.matches(value.as_ref()) {
368 continue;
369 }
370 Attrs::Have(value)
371 }
372 _ => Attrs::Row(row),
373 };
374 kept.push(Scored {
375 distance: -score,
376 id,
377 source: at,
378 attrs,
379 });
380 }
381 next = end;
382 chunk = chunk.saturating_mul(2);
383 }
384 Ok(kept)
385}
386
387fn score_postings(
395 postings: Vec<(f32, Vec<(u32, f32)>)>,
396 rows_in_segment: u64,
397 path: &str,
398) -> Result<Vec<(u32, f32)>> {
399 let mut scores: HashMap<u32, f32> = HashMap::new();
400 for (weight, found) in postings {
401 for (row, doc_weight) in found {
402 if u64::from(row) >= rows_in_segment {
403 return Err(ItzmaError::CorruptSparseIndex {
404 path: path.to_string(),
405 reason: format!(
406 "the index named row {row}, the segment has {rows_in_segment} rows"
407 ),
408 });
409 }
410 *scores.entry(row).or_insert(0.0) += weight * doc_weight;
411 }
412 }
413 let mut ranked: Vec<(u32, f32)> = scores.into_iter().collect();
414 ranked.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
415 Ok(ranked)
416}
417
418fn flat_scores(
423 layer: &Layer,
424 weights: &HashMap<u32, f32>,
425 filter: Option<&Predicate>,
426) -> Vec<Option<f32>> {
427 let docs: Vec<&crate::document::Document> = layer.docs().collect();
428 let chunks = cpu::chunked(&docs, cpu::FLAT_CHUNK, |chunk| {
429 chunk
430 .iter()
431 .map(|doc| {
432 if !filter.is_none_or(|p| p.matches(doc.attrs.as_ref())) {
433 return None;
434 }
435 let terms = doc.sparse.as_ref()?;
436 let mut shared = false;
437 let mut score = 0.0f32;
438 for (term, doc_weight) in terms {
439 if let Some(weight) = weights.get(term) {
440 shared = true;
441 score += weight * doc_weight;
442 }
443 }
444 shared.then_some(-score)
445 })
446 .collect::<Vec<_>>()
447 });
448 let mut out = Vec::with_capacity(docs.len());
449 for chunk in chunks {
450 out.extend(chunk);
451 }
452 out
453}
454
455async fn evaluate_flat(
460 q: &Query<'_>,
461 sources: &[Source<'_>],
462 at: usize,
463 layer: &Arc<Layer>,
464 weights: &HashMap<u32, f32>,
465) -> Result<Vec<Scored>> {
466 let terms: usize = layer
468 .docs()
469 .map(|doc| doc.sparse.as_ref().map_or(0, Vec::len))
470 .sum();
471 let (owned, weights, filter) = (layer.clone(), weights.clone(), q.filter.cloned());
472 let scores = cpu::run(
473 Lane::Query,
474 Cost::Distances {
475 rows: terms,
476 dim: 1,
477 },
478 move || flat_scores(&owned, &weights, filter.as_ref()),
479 )
480 .await;
481 debug_assert_eq!(scores.len(), layer.doc_count());
484 let scored: Vec<(f32, &crate::document::Document)> = layer
485 .docs()
486 .zip(scores)
487 .filter_map(|(doc, score)| score.map(|s| (s, doc)))
488 .collect();
489 let ids: Vec<String> = scored.iter().map(|(_, doc)| doc.id.clone()).collect();
490 let live = unshadowed(sources, at, &ids).await?;
491 Ok(scored
492 .into_iter()
493 .zip(live)
494 .filter(|(_, live)| *live)
495 .map(|((distance, doc), _)| Scored {
496 distance,
497 id: doc.id.clone(),
498 source: at,
499 attrs: Attrs::Have(doc.attrs.clone()),
500 })
501 .collect())
502}
503
504async fn unshadowed(sources: &[Source<'_>], at: usize, ids: &[String]) -> Result<Vec<bool>> {
508 stream::iter(ids.iter().cloned())
511 .map(|id| async move { is_live(sources, at, &id).await })
512 .buffered(FETCH_CONCURRENCY)
513 .try_collect()
514 .await
515}
516
517async fn is_live(sources: &[Source<'_>], at: usize, id: &str) -> Result<bool> {
518 let newer = &sources[at + 1..];
519 if newer
521 .iter()
522 .any(|source| matches!(source, Source::Flat(layer) if layer.holds(id)))
523 {
524 return Ok(false);
525 }
526 for source in newer {
527 if let Source::Indexed(newer) = source {
528 if newer.segment.holds(id).await? != Held::No {
529 return Ok(false);
530 }
531 }
532 }
533 Ok(true)
534}
535
536async fn finish(sources: &[Source<'_>], live: Vec<Scored>) -> Result<Vec<Hit>> {
539 let mut wanted: HashMap<usize, Vec<u32>> = HashMap::new();
540 for hit in &live {
541 if let Attrs::Row(row) = hit.attrs {
542 wanted.entry(hit.source).or_default().push(row);
543 }
544 }
545 let fetched = try_join_all(
546 wanted
547 .into_iter()
548 .map(|(at, rows)| fetch_attrs(sources, at, rows)),
549 )
550 .await?;
551 let mut attrs: HashMap<(usize, u32), Option<serde_json::Value>> = HashMap::new();
552 for (at, rows, values) in fetched {
553 attrs.extend(rows.into_iter().zip(values).map(|(row, v)| ((at, row), v)));
554 }
555 Ok(live
556 .into_iter()
557 .map(|hit| Hit {
558 attrs: match hit.attrs {
559 Attrs::Have(value) => value,
560 Attrs::Row(row) => attrs.remove(&(hit.source, row)).flatten(),
561 },
562 id: hit.id,
563 distance: hit.distance,
564 })
565 .collect())
566}
567
568async fn fetch_attrs(
569 sources: &[Source<'_>],
570 at: usize,
571 rows: Vec<u32>,
572) -> Result<(usize, Vec<u32>, Vec<Option<serde_json::Value>>)> {
573 let Source::Indexed(source) = &sources[at] else {
574 return Ok((at, rows, Vec::new()));
575 };
576 let values = source.segment.attrs_of(&rows).await?;
577 Ok((at, rows, values))
578}
579
580#[cfg(test)]
581mod tests {
582 use super::*;
583 use crate::document::{Document, WalOp};
584
585 #[tokio::test]
586 async fn sparse_flat_scores_on_the_pool_equal_the_inline_ones() {
587 let mut layer = Layer::new();
589 for i in 0..20_000u32 {
590 layer.apply(WalOp::Upsert(Document {
591 id: format!("d{i:06}"),
592 vector: vec![0.0],
593 attrs: Some(serde_json::json!({ "active": i % 3 == 0 })),
594 sparse: Some(
595 (0..100)
596 .map(|t| ((i + t * 7) % 500, 1.0 + (t % 5) as f32))
597 .collect(),
598 ),
599 }));
600 }
601 let layer = Arc::new(layer);
602 let weights: HashMap<u32, f32> = [(3, 1.0), (10, 0.5), (499, 2.0)].into();
603 for filter in [None, Some(Predicate::is_true("active"))] {
604 let inline = flat_scores(&layer, &weights, filter.as_ref());
605 assert_eq!(inline.len(), 20_000);
606 assert!(inline.iter().any(Option::is_some) && inline.iter().any(Option::is_none));
607 let (l, w, f) = (layer.clone(), weights.clone(), filter.clone());
608 let pooled = cpu::run(
609 Lane::Query,
610 Cost::Distances {
611 rows: 2_000_000,
612 dim: 1,
613 },
614 move || flat_scores(&l, &w, f.as_ref()),
615 )
616 .await;
617 assert_eq!(pooled, inline);
618 }
619 }
620
621 #[tokio::test]
622 async fn scored_postings_on_the_pool_equal_the_inline_ones() {
623 let postings: Vec<(f32, Vec<(u32, f32)>)> = (0..30u32)
624 .map(|t| {
625 (
626 1.0 + t as f32 / 10.0,
627 (0..50_000)
628 .step_by(1 + t as usize)
629 .map(|r| (r, 0.5))
630 .collect(),
631 )
632 })
633 .collect();
634 let inline = score_postings(postings.clone(), 50_000, "p").expect("score");
635 let p = postings.clone();
636 let pooled = cpu::run(
637 Lane::Query,
638 Cost::Distances {
639 rows: 2_000_000,
640 dim: 1,
641 },
642 move || score_postings(p, 50_000, "p"),
643 )
644 .await
645 .expect("score");
646 assert_eq!(pooled, inline);
647 assert!(
648 inline
649 .windows(2)
650 .all(|w| w[0].1 > w[1].1 || (w[0].1 == w[1].1 && w[0].0 < w[1].0))
651 );
652 let err = score_postings(postings, 10, "p").expect_err("row past the segment");
653 assert!(matches!(err, ItzmaError::CorruptSparseIndex { .. }));
654 }
655
656 #[test]
657 fn validate_refuses_what_cannot_run() {
658 let ok: SparseVector = vec![(1, 1.0)];
659 assert!(validate(&ok, 1).is_ok());
660 for (query, top_k) in [
661 (ok.clone(), 0),
662 (Vec::new(), 1),
663 (vec![(1, f32::NAN)], 1),
664 (vec![(1, f32::INFINITY)], 1),
665 ] {
666 assert!(
667 matches!(validate(&query, top_k), Err(ItzmaError::InvalidQuery(_))),
668 "{query:?} / {top_k}"
669 );
670 }
671 }
672
673 #[test]
674 fn a_repeated_query_term_counts_as_the_sum_of_its_weights() {
675 let weights = weights_of(&vec![(3, 1.0), (5, 2.0), (3, 0.5)]);
676 assert_eq!(weights.len(), 2);
677 assert_eq!(weights[&3], 1.5);
678 assert_eq!(weights[&5], 2.0);
679 }
680}