Skip to main content

itzma_core/
indexer.rs

1//! Building the index of one segment and publishing it:
2//! [`Namespace::index`](crate::Namespace::index) indexes each live segment in
3//! turn.
4//!
5//! An index is derived data. It is written with put-if-absent under a name that
6//! carries its generation, so a build never overwrites an object a reader may
7//! be using, and it becomes part of the namespace when one manifest
8//! compare-and-swap lists it. Until then it is an orphan, and a crash between
9//! the two costs nothing: the next run finds the object, checks it fits the
10//! segment, and publishes it. Nothing byte-compares two builds, since any valid
11//! index is correct (unlike a segment).
12
13use bytes::Bytes;
14use object_store::path::Path;
15use object_store::{ObjectStore, ObjectStoreExt, PutMode, PutOptions};
16use serde::{Deserialize, Serialize};
17
18use crate::budget::ReadBudget;
19use crate::cpu::{self, Cost, Lane};
20use crate::document::Metric;
21use crate::error::{ItzmaError, Result};
22use crate::fetch::FetchPolicy;
23use crate::index::{self, Kind, hnsw, sq8};
24use crate::manifest::{self, IndexEntry};
25use crate::segment;
26
27/// The default for [`IndexOptions::min_rows`].
28pub const DEFAULT_MIN_ROWS: usize = 4096;
29
30/// The segment format level `index` needs: an index is built for version 2.
31pub(crate) const MIN_SEGMENT_FORMAT: u32 = 2;
32
33/// Settings for [`Namespace::index`](crate::Namespace::index).
34///
35/// New fields will be added, so build one from `default()` and the setters.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(default)]
38#[non_exhaustive]
39pub struct IndexOptions {
40    /// A segment with fewer documents than this is not indexed and is read
41    /// whole, since a flat read of a small segment costs about what the index
42    /// head does. Zero indexes everything, an empty segment included.
43    pub min_rows: usize,
44    /// Build a new generation for a segment that already has an index, instead
45    /// of leaving it alone. The old object stays until
46    /// [`gc`](crate::Namespace::gc) collects it.
47    pub rebuild: bool,
48    /// Which algorithm to build. Different segments may use
49    /// different kinds; rebuilding a segment to a different kind replaces its
50    /// entry like any other rebuild. Defaults to [`IndexKind::Hnsw`].
51    pub kind: IndexKind,
52    /// How many partitions an SQ8 index has. `None` chooses from the
53    /// segment's row count: one partition for a small segment and more for a big
54    /// one. A query then reads only the few partitions nearest to it. `Some(0)` is
55    /// [`ItzmaError::InvalidQuery`], and a number
56    /// above the segment's rows is cut to it.
57    pub nlist: Option<usize>,
58}
59
60impl Default for IndexOptions {
61    fn default() -> Self {
62        Self {
63            min_rows: DEFAULT_MIN_ROWS,
64            rebuild: false,
65            kind: IndexKind::default(),
66            nlist: None,
67        }
68    }
69}
70
71impl IndexOptions {
72    /// Set [`min_rows`](Self::min_rows).
73    #[must_use]
74    pub fn min_rows(mut self, min_rows: usize) -> Self {
75        self.min_rows = min_rows;
76        self
77    }
78
79    /// Set [`rebuild`](Self::rebuild).
80    #[must_use]
81    pub fn rebuild(mut self, rebuild: bool) -> Self {
82        self.rebuild = rebuild;
83        self
84    }
85
86    /// Set [`nlist`](Self::nlist).
87    #[must_use]
88    pub fn nlist(mut self, nlist: Option<usize>) -> Self {
89        self.nlist = nlist;
90        self
91    }
92
93    /// Refuse options that cannot be run, before any storage call.
94    pub(crate) fn validate(&self) -> Result<()> {
95        if self.nlist == Some(0) {
96            return Err(ItzmaError::InvalidQuery("nlist must be at least 1"));
97        }
98        Ok(())
99    }
100
101    /// Set [`kind`](Self::kind).
102    #[must_use]
103    pub fn kind(mut self, kind: IndexKind) -> Self {
104        self.kind = kind;
105        self
106    }
107}
108
109/// The number of partitions [`IndexOptions::nlist`] chooses when it is left at
110/// `None`: one below a threshold and about the square root of the rows above
111/// it. A caller building a namespace's own report of what an
112/// automatic build chose can call this before or after `index` runs; `index`
113/// itself uses the same rule.
114#[must_use]
115pub fn default_nlist(rows: usize) -> usize {
116    sq8::default_nlist(rows)
117}
118
119/// The number of partitions a query probes when
120/// [`QueryOptions::nprobe`](crate::QueryOptions::nprobe) is left at `None`, for
121/// an SQ8 index with `nlist` partitions.
122#[must_use]
123pub fn default_nprobe(nlist: usize) -> usize {
124    sq8::default_nprobe(nlist)
125}
126
127/// Which algorithm builds a segment's index. New variants may be
128/// added, so match on this non-exhaustively.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
130#[serde(rename_all = "snake_case")]
131#[non_exhaustive]
132pub enum IndexKind {
133    /// Scalar quantization to 8 bits per dimension. Near-zero build
134    /// cost, the same cost every query pays whether the segment is warm or
135    /// cold.
136    Sq8,
137    /// Segmented HNSW, the default. Costlier to build and to query cold,
138    /// cheaper to query once the segment's index object is warm in cache.
139    #[default]
140    Hnsw,
141}
142
143impl IndexKind {
144    fn as_kind(self) -> Kind {
145        match self {
146            IndexKind::Sq8 => Kind::Sq8,
147            IndexKind::Hnsw => Kind::Hnsw,
148        }
149    }
150}
151
152/// What a call to [`Namespace::index`](crate::Namespace::index) did, one count
153/// per live segment it looked at. Every segment lands in exactly one.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
155#[serde(default)]
156#[non_exhaustive]
157pub struct IndexReport {
158    /// Segments this run published an index for.
159    pub indexed: usize,
160    /// Segments left alone because they hold fewer than
161    /// [`IndexOptions::min_rows`] documents.
162    pub skipped_small: usize,
163    /// Segments that already had an index (and `rebuild` was not set), or that
164    /// another indexer published while this run built its own.
165    pub already_indexed: usize,
166    /// Segments a compaction retired while this run was working on them. Their
167    /// index object, if it was written, is left for [`gc`](crate::Namespace::gc).
168    pub superseded: usize,
169}
170
171/// What became of one segment.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub(crate) enum Outcome {
174    Indexed,
175    SkippedSmall,
176    AlreadyIndexed,
177    Superseded,
178}
179
180impl IndexReport {
181    pub(crate) fn record(&mut self, outcome: Outcome) {
182        let count = match outcome {
183            Outcome::Indexed => &mut self.indexed,
184            Outcome::SkippedSmall => &mut self.skipped_small,
185            Outcome::AlreadyIndexed => &mut self.already_indexed,
186            Outcome::Superseded => &mut self.superseded,
187        };
188        *count += 1;
189    }
190}
191
192/// Index the live segment `id`, whose current entry in the manifest is `have`.
193///
194/// Reads 20 bytes to decide whether the segment is worth it, and only then the
195/// whole data object, one segment at a time and under a budget of its own, so a
196/// namespace of many segments is not bounded by their sum. A segment bigger than
197/// `read_budget` cannot be indexed.
198///
199/// # Errors
200///
201/// Whatever reading the segment gives (a missing object is
202/// [`segment::is_missing`], which the caller turns into `Superseded` when the
203/// manifest has moved), [`ItzmaError::CorruptIndex`] if an object already at the
204/// new key does not fit the segment, and the errors of a manifest update.
205#[allow(clippy::too_many_arguments)] // the metric joined dim as a per-segment parameter
206pub(crate) async fn index_segment(
207    store: &dyn ObjectStore,
208    namespace: &str,
209    dim: usize,
210    metric: Metric,
211    id: &str,
212    have: Option<&IndexEntry>,
213    options: &IndexOptions,
214    read_budget: u64,
215    policy: &FetchPolicy,
216) -> Result<Outcome> {
217    if have.is_some() && !options.rebuild {
218        return Ok(Outcome::AlreadyIndexed);
219    }
220    let budget = ReadBudget::new(read_budget);
221    let data_path = segment::segment_path(namespace, id);
222
223    let head = segment::peek(store, &data_path, &budget).await?;
224    if usize::try_from(head.doc_count).is_ok_and(|rows| rows < options.min_rows) {
225        return Ok(Outcome::SkippedSmall);
226    }
227
228    let bytes = segment::fetch_bytes(store, &data_path, &budget, policy).await?;
229    let data_size = bytes.len() as u64;
230    let layer = segment::decode_on(Lane::Maintenance, data_path.clone(), bytes, dim).await?;
231    let docs = layer.sorted_docs();
232    let matrix: Vec<f32> = docs.iter().flat_map(|d| d.vector.iter().copied()).collect();
233    let rows = docs.len();
234
235    let names = segment::object_names(store, namespace, id).await?;
236    let floor = segment::generation_floor(
237        have.map(|entry| entry.generation),
238        &names,
239        index::generation_of,
240    );
241    let generation = segment::claim_generation(store, namespace, id, floor).await?;
242    let path = index::index_path(namespace, id, generation);
243    let kind = options.kind.as_kind();
244    let nlist = options.nlist.unwrap_or_else(|| sq8::default_nlist(rows));
245    let cost = build_cost(kind, rows, nlist, dim);
246    let built = cpu::run(Lane::Maintenance, cost, move || match kind {
247        Kind::Sq8 => sq8::build(&matrix, dim, rows, data_size, nlist, metric),
248        Kind::Hnsw => hnsw::build(&matrix, dim, rows, data_size, metric),
249    })
250    .await?;
251    put_or_reuse(store, &path, built, kind, dim, rows as u64, data_size).await?;
252
253    publish(store, namespace, id, have, generation, kind).await
254}
255
256/// How much work a build is, for the compute pool's hand-off: SQ8
257/// compares every row with every centroid, HNSW with about
258/// `EF_CONSTRUCTION` candidates while it inserts it.
259fn build_cost(kind: Kind, rows: usize, nlist: usize, dim: usize) -> Cost {
260    let per_row = match kind {
261        Kind::Sq8 => nlist.max(1),
262        Kind::Hnsw => hnsw::EF_CONSTRUCTION,
263    };
264    Cost::Distances {
265        rows: rows.saturating_mul(per_row),
266        dim,
267    }
268}
269
270/// Write the index with put-if-absent. An object already at the key is an
271/// orphan of an earlier run or the winner of a race, and it is used if it is a
272/// valid index of this segment, whoever built it and however it was built.
273async fn put_or_reuse(
274    store: &dyn ObjectStore,
275    path: &Path,
276    built: Bytes,
277    kind: Kind,
278    dim: usize,
279    rows: u64,
280    data_size: u64,
281) -> Result<()> {
282    match store
283        .put_opts(path, built.into(), PutOptions::from(PutMode::Create))
284        .await
285    {
286        Ok(_) => Ok(()),
287        Err(object_store::Error::AlreadyExists { .. }) => {
288            let existing = store.get(path).await?.bytes().await?;
289            let checked = match kind {
290                Kind::Sq8 => {
291                    sq8::Index::decode(path.as_ref(), &existing, dim, rows, data_size).map(|_| ())
292                }
293                Kind::Hnsw => {
294                    hnsw::Index::decode(path.as_ref(), &existing, dim, rows, data_size).map(|_| ())
295                }
296            };
297            checked.map_err(|err| match err {
298                ItzmaError::CorruptIndex { path, reason } => ItzmaError::CorruptIndex {
299                    path,
300                    reason: format!(
301                        "{reason}; an object already at this key does not fit the segment, \
302                         delete it and rerun"
303                    ),
304                },
305                other => other,
306            })
307        }
308        Err(e) => Err(e.into()),
309    }
310}
311
312/// List the index in the manifest, if the manifest still looks the way it did
313/// when the run planned: the segment live and its entry unchanged.
314async fn publish(
315    store: &dyn ObjectStore,
316    namespace: &str,
317    id: &str,
318    have: Option<&IndexEntry>,
319    generation: u32,
320    kind: Kind,
321) -> Result<Outcome> {
322    let mut lost = Outcome::AlreadyIndexed;
323    let published = manifest::update_if(store, namespace, |m| {
324        if !m.live_segments.iter().any(|live| live == id) {
325            lost = Outcome::Superseded;
326            return false;
327        }
328        if m.indexes.get(id) != have {
329            lost = Outcome::AlreadyIndexed;
330            return false;
331        }
332        m.indexes.insert(
333            id.to_string(),
334            IndexEntry {
335                generation,
336                kind: kind.name().to_string(),
337            },
338        );
339        true
340    })
341    .await?;
342    Ok(published.map_or(lost, |_| Outcome::Indexed))
343}
344
345#[cfg(test)]
346mod tests {
347
348    #[test]
349    fn every_build_worth_indexing_leaves_the_tokio_worker() {
350        use crate::cpu::INLINE_BELOW;
351        // HNSW: the smallest segment `index` builds by default, at small
352        // dimensions, is still hundreds of distances per row.
353        for dim in [4, 25, 128] {
354            let cost = build_cost(Kind::Hnsw, DEFAULT_MIN_ROWS, 1, dim);
355            assert!(cost.units() >= INLINE_BELOW, "hnsw at dim {dim}");
356        }
357        // SQ8 with clustering: every row against every centroid, five times.
358        let cost = build_cost(Kind::Sq8, 100_000, 316, 25);
359        assert!(cost.units() >= INLINE_BELOW);
360    }
361
362    use super::*;
363
364    #[test]
365    fn options_default_to_hnsw_and_the_setter_changes_it() {
366        assert_eq!(IndexOptions::default().kind, IndexKind::Hnsw);
367        let opts = IndexOptions::default().kind(IndexKind::Sq8);
368        assert_eq!(opts.kind, IndexKind::Sq8);
369    }
370}