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    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    // Resolve ids and check shadowing down the ranking, in growing chunks, and
331    // stop once `top_k` live rows that match are in hand and the next row
332    // scores strictly less than the last of them. A row tied with it can still
333    // win on id, so ties are all kept. With no newer source and no filter
334    // nothing is dropped, and this reads the ids of about `top_k` rows, not of
335    // every row a term names. A filter can drop most rows, so it reads further
336    // down the ranking.
337    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        // The attributes are fetched once per chunk for the live rows only, and
355        // stay on the hit so `finish` does not fetch them again.
356        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
387/// Sum `weight * doc_weight` per row over every term's postings, in the
388/// order given, and rank the rows: highest score first, row order among
389/// equals so a run is repeatable.
390///
391/// # Errors
392///
393/// [`ItzmaError::CorruptSparseIndex`] for a row at or past `rows_in_segment`.
394fn 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
418/// The negated score of every document of `layer` against the query's
419/// `weights`, in `layer.docs()` order: `None` where `filter` drops the
420/// document or it shares no term with the query. Chunked so a pool thread
421/// splits it across cores, with the same result either way.
422fn 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
455/// The same for a layer held in memory: score each live document against its
456/// own `sparse` field, which `sparse::read_all_with_sparse` (or the WAL)
457/// already filled in. A document sharing no term with the query is not a
458/// candidate.
459async 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    // One lookup per stored term: the work is the layer's total term count.
467    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    // `Layer::docs` keeps its order while the layer is unchanged (its
482    // contract), so this second pass lines up with the one on the pool.
483    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
504/// For each of `ids`, proposed by source `at`: whether it is still the live
505/// version, that is, no newer source holds the id as a document or a
506/// tombstone.
507async fn unshadowed(sources: &[Source<'_>], at: usize, ids: &[String]) -> Result<Vec<bool>> {
508    // Owned ids: a closure over `&String` is inferred as higher-ranked, which
509    // makes the stream not provably `Send` (see `segment::read_all`).
510    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    // Layers in memory first: they cost no request.
520    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
536/// Fetch the attributes the final hits still lack, one request per block, and
537/// build the hits.
538async 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        // 20,000 documents of 100 terms: past the inline threshold.
588        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}