Skip to main content

itzma_core/
sparse_indexer.rs

1//! Building the sparse inverted index of one segment and publishing it
2//!: [`Namespace::index_sparse`](crate::Namespace::index_sparse).
3//! Mirrors `indexer.rs`'s shape for the dense index — put-if-absent, then
4//! one manifest compare-and-swap — with one algorithm, so there is no `kind`.
5
6use std::collections::BTreeMap;
7
8use object_store::path::Path;
9use object_store::{ObjectStore, ObjectStoreExt, PutMode, PutOptions};
10use serde::{Deserialize, Serialize};
11
12use crate::budget::ReadBudget;
13use crate::error::{ItzmaError, Result};
14use crate::fetch::FetchPolicy;
15use crate::manifest::{self, SparseIndexEntry};
16use crate::segment;
17use crate::sparse;
18use crate::sparse_index;
19
20/// Settings for [`Namespace::index_sparse`](crate::Namespace::index_sparse).
21///
22/// New fields will be added, so build one from `default()` and the setters.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
24#[serde(default)]
25#[non_exhaustive]
26pub struct IndexSparseOptions {
27    /// Build a new generation for a segment that already has a sparse
28    /// index, instead of leaving it alone. The old object stays until
29    /// [`gc`](crate::Namespace::gc) collects it.
30    pub rebuild: bool,
31}
32
33impl IndexSparseOptions {
34    /// Set [`rebuild`](Self::rebuild).
35    #[must_use]
36    pub fn rebuild(mut self, rebuild: bool) -> Self {
37        self.rebuild = rebuild;
38        self
39    }
40}
41
42/// What a call to [`Namespace::index_sparse`](crate::Namespace::index_sparse)
43/// did, one count per live segment it looked at. Every segment lands in
44/// exactly one.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
46#[serde(default)]
47#[non_exhaustive]
48pub struct IndexSparseReport {
49    /// Segments this run published a sparse index for.
50    pub indexed: usize,
51    /// Segments left alone because they have no `sparse.bin` (no document in
52    /// them carries a sparse vector).
53    pub skipped_no_sparse: usize,
54    /// Segments that already had a sparse index (and `rebuild` was not set),
55    /// or that another indexer published while this run built its own.
56    pub already_indexed: usize,
57    /// Segments a compaction retired while this run was working on them.
58    pub superseded: usize,
59}
60
61/// What became of one segment.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub(crate) enum Outcome {
64    Indexed,
65    SkippedNoSparse,
66    AlreadyIndexed,
67    Superseded,
68}
69
70impl IndexSparseReport {
71    pub(crate) fn record(&mut self, outcome: Outcome) {
72        let count = match outcome {
73            Outcome::Indexed => &mut self.indexed,
74            Outcome::SkippedNoSparse => &mut self.skipped_no_sparse,
75            Outcome::AlreadyIndexed => &mut self.already_indexed,
76            Outcome::Superseded => &mut self.superseded,
77        };
78        *count += 1;
79    }
80}
81
82/// Index the live segment `id`'s sparse sidecar, whose current entry in the
83/// manifest is `have`.
84///
85/// # Errors
86///
87/// Whatever reading `sparse.bin` gives ([`ItzmaError::CorruptSegment`]; a
88/// missing object is [`sparse::is_missing`], turned into
89/// [`Outcome::SkippedNoSparse`] here, not an error — a segment legitimately
90/// has none), [`ItzmaError::CorruptSparseIndex`] if an object already at the
91/// new key does not fit the segment, and the errors of a manifest update.
92pub(crate) async fn index_segment(
93    store: &dyn ObjectStore,
94    namespace: &str,
95    id: &str,
96    have: Option<&SparseIndexEntry>,
97    options: &IndexSparseOptions,
98    read_budget: u64,
99    policy: &FetchPolicy,
100) -> Result<Outcome> {
101    if have.is_some() && !options.rebuild {
102        return Ok(Outcome::AlreadyIndexed);
103    }
104    let budget = ReadBudget::new(read_budget);
105    let data_path = segment::segment_path(namespace, id);
106    let head = segment::peek(store, &data_path, &budget).await?;
107    let rows = u32::try_from(head.doc_count).map_err(|_| ItzmaError::CorruptSegment {
108        path: data_path.to_string(),
109        reason: "too many rows for a sparse index's u32 row count".into(),
110    })?;
111
112    let sparse_path = sparse::sparse_path(namespace, id);
113    let bytes = match sparse::fetch_bytes(store, &sparse_path, &budget, policy).await {
114        Ok(bytes) => bytes,
115        Err(e) if sparse::is_missing(&e) => return Ok(Outcome::SkippedNoSparse),
116        Err(e) => return Err(e),
117    };
118    let rows_decoded = sparse::decode(sparse_path.as_ref(), &bytes, u64::from(rows))?;
119
120    let mut postings: BTreeMap<u32, Vec<(u32, f32)>> = BTreeMap::new();
121    for (row, terms) in rows_decoded.into_iter().enumerate() {
122        let Some(terms) = terms else { continue };
123        for (term, weight) in terms {
124            postings.entry(term).or_default().push((row as u32, weight));
125        }
126    }
127
128    let names = segment::object_names(store, namespace, id).await?;
129    let floor = segment::generation_floor(
130        have.map(|entry| entry.generation),
131        &names,
132        sparse_index::generation_of,
133    );
134    let generation = segment::claim_generation(store, namespace, id, floor).await?;
135    let path = sparse_index::sparse_index_path(namespace, id, generation);
136    let built = sparse_index::build(rows, &postings);
137    put_or_reuse(store, &path, built, u64::from(rows)).await?;
138
139    publish(store, namespace, id, have, generation).await
140}
141
142/// Write the sparse index with put-if-absent. An object already at the key is
143/// an orphan of an earlier run or the winner of a race, and it is used if it
144/// checks out as a valid sparse index of this segment.
145async fn put_or_reuse(
146    store: &dyn ObjectStore,
147    path: &Path,
148    built: bytes::Bytes,
149    rows: u64,
150) -> Result<()> {
151    match store
152        .put_opts(path, built.into(), PutOptions::from(PutMode::Create))
153        .await
154    {
155        Ok(_) => Ok(()),
156        Err(object_store::Error::AlreadyExists { .. }) => {
157            let existing = store.get(path).await?.bytes().await?;
158            sparse_index::open_bytes_for_check(path.as_ref(), &existing, rows).map_err(|err| {
159                match err {
160                    ItzmaError::CorruptSparseIndex { path, reason } => {
161                        ItzmaError::CorruptSparseIndex {
162                            path,
163                            reason: format!(
164                                "{reason}; an object already at this key does not fit the \
165                                 segment, delete it and rerun"
166                            ),
167                        }
168                    }
169                    other => other,
170                }
171            })
172        }
173        Err(e) => Err(e.into()),
174    }
175}
176
177/// List the sparse index in the manifest, if the manifest still looks the way
178/// it did when the run planned: the segment live and its entry unchanged.
179async fn publish(
180    store: &dyn ObjectStore,
181    namespace: &str,
182    id: &str,
183    have: Option<&SparseIndexEntry>,
184    generation: u32,
185) -> Result<Outcome> {
186    let mut lost = Outcome::AlreadyIndexed;
187    let published = manifest::update_if(store, namespace, |m| {
188        if !m.live_segments.iter().any(|live| live == id) {
189            lost = Outcome::Superseded;
190            return false;
191        }
192        if m.sparse_indexes.get(id) != have {
193            lost = Outcome::AlreadyIndexed;
194            return false;
195        }
196        m.sparse_indexes
197            .insert(id.to_string(), SparseIndexEntry { generation });
198        true
199    })
200    .await?;
201    Ok(published.map_or(lost, |_| Outcome::Indexed))
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn rebuild_setter_changes_the_default() {
210        assert!(!IndexSparseOptions::default().rebuild);
211        assert!(IndexSparseOptions::default().rebuild(true).rebuild);
212    }
213}