Skip to main content

itzma_core/
sparse_query.rs

1//! The sparse query engine behind
2//! [`Namespace::query_sparse`](crate::Namespace::query_sparse).
3//!
4//! The namespace is a list of *sources*, oldest to newest, planned the way the
5//! dense engine plans them (`query.rs`) but grouped by the manifest's
6//! `sparse_indexes` instead of `indexes`. A live segment with a sparse index is
7//! an indexed source: its term directory is fetched once, and only the
8//! postings of the query's own terms after that. Every run of segments without
9//! one is folded into one in-memory layer and scored directly, and so is the
10//! WAL tail, kept folded by the handle between queries and always
11//! its own, newest source. Each source proposes every document that shares a term with the
12//! query, and the engine drops any proposal a newer source holds as a document
13//! or a tombstone, merges the sources and keeps the closest `top_k`.
14//!
15//! An indexed source reuses [`RangedSegment`], built for `data.bin`, for the
16//! three things it needs a segment for: row to id, the shadow check, and the
17//! attributes of the final hits. A sparse index only adds the term lookup.
18//!
19//! There is no rerank and no re-reading of postings. A sparse dot product over
20//! stored weights is exact, and the full postings scan of every query term
21//! returns every row that shares one, so shadowing can only shrink the set of
22//! real matches. The one loop is local: an indexed source ranks its rows by
23//! score and resolves ids and the shadow check down that ranking only until
24//! `top_k` live rows are in hand, so an unshadowed query reads about `top_k`
25//! ids, not one per matching row.
26
27use 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
52/// Requests in flight at once when a step fans out over segments or ids.
53const FETCH_CONCURRENCY: usize = 16;
54
55/// Settings for [`Namespace::query_sparse`](crate::Namespace::query_sparse).
56///
57/// A sparse dot product is exact, so there is no rerank or exactness knob the
58/// way [`QueryOptions`](crate::QueryOptions) needs. The only field is a filter.
59/// Build one from `default()` and the setter.
60#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
61#[serde(default)]
62#[non_exhaustive]
63pub struct SparseQueryOptions {
64    /// Keep only documents whose attributes match this predicate, as
65    /// [`QueryOptions::filter`](crate::QueryOptions::filter) does.
66    pub filter: Option<Predicate>,
67}
68
69impl SparseQueryOptions {
70    /// Set [`filter`](Self::filter).
71    #[must_use]
72    pub fn filter(mut self, filter: Option<Predicate>) -> Self {
73        self.filter = filter;
74        self
75    }
76}
77
78/// Refuse a query that cannot be run, before any storage call.
79///
80/// # Errors
81///
82/// [`ItzmaError::InvalidQuery`] for a `top_k` of zero, an empty query vector,
83/// or a non-finite weight in it.
84pub(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
101/// The query's weight for each distinct term. A term repeated in the query
102/// counts as the sum of its weights, which is what the dot product with the
103/// summed vector is.
104fn 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
112/// One sparse query against one manifest.
113pub(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    /// Parsed structures kept between queries, if the handle has a
123    /// decoded cache.
124    pub(crate) decoded: Option<&'a DecodedRef>,
125    /// The namespace's attribute schema, to know which fields are indexed.
126    pub(crate) attrs: &'a AttrSchema,
127}
128
129impl Query<'_> {
130    /// The filter, but only when an attribute index could narrow it, decided
131    /// from field names alone with no I/O.
132    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
139/// What the manifest's live segments turn into.
140enum Step<'a> {
141    /// A segment with a sparse index.
142    Indexed {
143        id: &'a str,
144        generation: u32,
145        /// The generation of the segment's attribute index, if it has one.
146        attr_generation: Option<u32>,
147    },
148    /// A run of consecutive segments without one.
149    Flat(&'a [String]),
150}
151
152/// A place a document can come from, newest last.
153enum Source<'a> {
154    Indexed(Box<Indexed<'a>>),
155    /// A run of unindexed segments overlaid into one layer, or the WAL tail;
156    /// either way its documents carry their sparse vectors.
157    Flat(Arc<Layer>),
158}
159
160struct Indexed<'a> {
161    segment: RangedSegment<'a>,
162    index_path: Path,
163    dir: Arc<TermDirectory>,
164    /// The predicate's superset of matching rows in this segment, resolved
165    /// once when the source opens. `None` when there is no filter, no
166    /// attribute index for this segment, or the predicate did not resolve.
167    attr_candidates: Option<Vec<u32>>,
168}
169
170/// Where a hit's attributes are: already in memory, or in the data object.
171enum Attrs {
172    Have(Option<serde_json::Value>),
173    Row(u32),
174}
175
176/// A live candidate with its score, negated so lower is closer like every
177/// other distance in the crate.
178struct Scored {
179    distance: f32,
180    id: String,
181    source: usize,
182    attrs: Attrs,
183}
184
185/// Group the live segments into steps, oldest first. Consecutive segments
186/// without a sparse index stay together, since overlaying them gives their
187/// net effect and nothing between them needs a separate shadow check.
188fn 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
211/// Run the query over `manifest`.
212///
213/// # Errors
214///
215/// The errors of reading segments, sparse sidecars, sparse indexes and the
216/// tail (a missing segment or index, or a fenced WAL object, is what the
217/// caller reloads the manifest for), [`ItzmaError::CorruptSparseIndex`] for a
218/// damaged index or a row it made up, and [`ItzmaError::ReadBudgetExceeded`].
219pub(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    // The tail is read alongside the segments and is its own, newest source,
226    // shared through the handle's view, as in the dense engine.
227    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    // Indexed by position, not mapped over the owned `Step` values: a closure
252    // whose parameter itself borrows `'a` is inferred as higher-ranked, which
253    // then fails to prove the stream `Send` (see `query::open_sources`).
254    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
337/// Score every row the postings of the query's terms name, then keep the best
338/// live ones: at least `top_k`, plus any that tie with the last. One ranged read
339/// per matched term, and ids are resolved only as far down the ranking as needed.
340async 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    // Ascending term id, not the map's order: a row's score is summed in the
348    // order its terms' postings come, float addition is not associative, and
349    // a `HashMap`'s order changes from run to run. Ascending is the order of
350    // a document whose terms are ascending, so such a row scores the same
351    // bits here as on the flat path.
352    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    // Resolve ids and check shadowing down the ranking, in growing chunks, and
376    // stop once `top_k` live rows that match are in hand and the next row
377    // scores strictly less than the last of them. A row tied with it can still
378    // win on id, so ties are all kept. With no newer source and no filter
379    // nothing is dropped, and this reads the ids of about `top_k` rows, not of
380    // every row a term names. A filter can drop most rows, so it reads further
381    // down the ranking.
382    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        // An attribute index's superset drops rows that cannot match before
400        // any attribute is read.
401        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        // The attributes are fetched once per chunk for the live rows only, and
412        // stay on the hit so `finish` does not fetch them again.
413        let rows: Vec<u32> = survivors.iter().map(|(row, _, _)| *row).collect();
414        // A version 3 segment decides from its zone maps and the predicate's
415        // columns, and the attributes of the rows that pass wait for `finish`.
416        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
453/// Sum `weight * doc_weight` per row over every term's postings, in the
454/// order given, and rank the rows: highest score first, row order among
455/// equals so a run is repeatable.
456///
457/// # Errors
458///
459/// [`ItzmaError::CorruptSparseIndex`] for a row at or past `rows_in_segment`.
460fn 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
484/// The negated score of every document of `layer` against the query's
485/// `weights`, in `layer.docs()` order: `None` where `filter` drops the
486/// document or it shares no term with the query. Chunked so a pool thread
487/// splits it across cores, with the same result either way.
488fn 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
521/// The same for a layer held in memory: score each live document against its
522/// own `sparse` field, which `sparse::read_all_with_sparse` (or the WAL)
523/// already filled in. A document sharing no term with the query is not a
524/// candidate.
525async 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    // One lookup per stored term: the work is the layer's total term count.
533    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    // `Layer::docs` keeps its order while the layer is unchanged (its
548    // contract), so this second pass lines up with the one on the pool.
549    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
570/// For each of `ids`, proposed by source `at`: whether it is still the live
571/// version, that is, no newer source holds the id as a document or a
572/// tombstone.
573async fn unshadowed(sources: &[Source<'_>], at: usize, ids: &[String]) -> Result<Vec<bool>> {
574    // Owned ids: a closure over `&String` is inferred as higher-ranked, which
575    // makes the stream not provably `Send` (see `segment::read_all`).
576    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    // Layers in memory first: they cost no request.
586    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
602/// Fetch the attributes the final hits still lack, one request per block, and
603/// build the hits.
604async 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        // 20,000 documents of 100 terms: past the inline threshold.
654        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}