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::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
50/// Requests in flight at once when a step fans out over segments or ids.
51const FETCH_CONCURRENCY: usize = 16;
52
53/// Settings for [`Namespace::query_sparse`](crate::Namespace::query_sparse).
54///
55/// A sparse dot product is exact, so there is no rerank or exactness knob the
56/// way [`QueryOptions`](crate::QueryOptions) needs. The only field is a filter.
57/// Build one from `default()` and the setter.
58#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
59#[serde(default)]
60#[non_exhaustive]
61pub struct SparseQueryOptions {
62    /// Keep only documents whose attributes match this predicate, as
63    /// [`QueryOptions::filter`](crate::QueryOptions::filter) does.
64    pub filter: Option<Predicate>,
65}
66
67impl SparseQueryOptions {
68    /// Set [`filter`](Self::filter).
69    #[must_use]
70    pub fn filter(mut self, filter: Option<Predicate>) -> Self {
71        self.filter = filter;
72        self
73    }
74}
75
76/// Refuse a query that cannot be run, before any storage call.
77///
78/// # Errors
79///
80/// [`ItzmaError::InvalidQuery`] for a `top_k` of zero, an empty query vector,
81/// or a non-finite weight in it.
82pub(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
99/// The query's weight for each distinct term. A term repeated in the query
100/// counts as the sum of its weights, which is what the dot product with the
101/// summed vector is.
102fn 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
110/// One sparse query against one manifest.
111pub(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    /// Parsed structures kept between queries, if the handle has a
121    /// decoded cache.
122    pub(crate) decoded: Option<&'a DecodedRef>,
123}
124
125/// What the manifest's live segments turn into.
126enum Step<'a> {
127    /// A segment with a sparse index.
128    Indexed { id: &'a str, generation: u32 },
129    /// A run of consecutive segments without one.
130    Flat(&'a [String]),
131}
132
133/// A place a document can come from, newest last.
134enum Source<'a> {
135    Indexed(Box<Indexed<'a>>),
136    /// A run of unindexed segments overlaid into one layer, or the WAL tail;
137    /// either way its documents carry their sparse vectors.
138    Flat(Arc<Layer>),
139}
140
141struct Indexed<'a> {
142    segment: RangedSegment<'a>,
143    index_path: Path,
144    dir: Arc<TermDirectory>,
145}
146
147/// Where a hit's attributes are: already in memory, or in the data object.
148enum Attrs {
149    Have(Option<serde_json::Value>),
150    Row(u32),
151}
152
153/// A live candidate with its score, negated so lower is closer like every
154/// other distance in the crate.
155struct Scored {
156    distance: f32,
157    id: String,
158    source: usize,
159    attrs: Attrs,
160}
161
162/// Group the live segments into steps, oldest first. Consecutive segments
163/// without a sparse index stay together, since overlaying them gives their
164/// net effect and nothing between them needs a separate shadow check.
165fn 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
187/// Run the query over `manifest`.
188///
189/// # Errors
190///
191/// The errors of reading segments, sparse sidecars, sparse indexes and the
192/// tail (a missing segment or index, or a fenced WAL object, is what the
193/// caller reloads the manifest for), [`ItzmaError::CorruptSparseIndex`] for a
194/// damaged index or a row it made up, and [`ItzmaError::ReadBudgetExceeded`].
195pub(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    // The tail is read alongside the segments and is its own, newest source,
202    // shared through the handle's view, as in the dense engine.
203    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    // Indexed by position, not mapped over the owned `Step` values: a closure
228    // whose parameter itself borrows `'a` is inferred as higher-ranked, which
229    // then fails to prove the stream `Send` (see `query::open_sources`).
230    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
299/// Score every row the postings of the query's terms name, then keep the best
300/// live ones: at least `top_k`, plus any that tie with the last. One ranged read
301/// per matched term, and ids are resolved only as far down the ranking as needed.
302async 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    // Ascending term id, not the map's order: a row's score is summed in the
310    // order its terms' postings come, float addition is not associative, and
311    // a `HashMap`'s order changes from run to run. Ascending is the order of
312    // a document whose terms are ascending, so such a row scores the same
313    // bits here as on the flat path.
314    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    // Resolve ids and check shadowing down the ranking, in growing chunks, and
338    // stop once `top_k` live rows that match are in hand and the next row
339    // scores strictly less than the last of them. A row tied with it can still
340    // win on id, so ties are all kept. With no newer source and no filter
341    // nothing is dropped, and this reads the ids of about `top_k` rows, not of
342    // every row a term names. A filter can drop most rows, so it reads further
343    // down the ranking.
344    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        // The attributes are fetched once per chunk for the live rows only, and
362        // stay on the hit so `finish` does not fetch them again.
363        let rows: Vec<u32> = survivors.iter().map(|(row, _, _)| *row).collect();
364        // A version 3 segment decides from its zone maps and the predicate's
365        // columns, and the attributes of the rows that pass wait for `finish`.
366        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
403/// Sum `weight * doc_weight` per row over every term's postings, in the
404/// order given, and rank the rows: highest score first, row order among
405/// equals so a run is repeatable.
406///
407/// # Errors
408///
409/// [`ItzmaError::CorruptSparseIndex`] for a row at or past `rows_in_segment`.
410fn 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
434/// The negated score of every document of `layer` against the query's
435/// `weights`, in `layer.docs()` order: `None` where `filter` drops the
436/// document or it shares no term with the query. Chunked so a pool thread
437/// splits it across cores, with the same result either way.
438fn 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
471/// The same for a layer held in memory: score each live document against its
472/// own `sparse` field, which `sparse::read_all_with_sparse` (or the WAL)
473/// already filled in. A document sharing no term with the query is not a
474/// candidate.
475async 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    // One lookup per stored term: the work is the layer's total term count.
483    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    // `Layer::docs` keeps its order while the layer is unchanged (its
498    // contract), so this second pass lines up with the one on the pool.
499    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
520/// For each of `ids`, proposed by source `at`: whether it is still the live
521/// version, that is, no newer source holds the id as a document or a
522/// tombstone.
523async fn unshadowed(sources: &[Source<'_>], at: usize, ids: &[String]) -> Result<Vec<bool>> {
524    // Owned ids: a closure over `&String` is inferred as higher-ranked, which
525    // makes the stream not provably `Send` (see `segment::read_all`).
526    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    // Layers in memory first: they cost no request.
536    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
552/// Fetch the attributes the final hits still lack, one request per block, and
553/// build the hits.
554async 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        // 20,000 documents of 100 terms: past the inline threshold.
604        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}