itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
Documentation
//! Building the attribute index of one segment and publishing it:
//! [`Namespace::index_attrs`](crate::Namespace::index_attrs)
//! indexes each live segment in turn. Mirrors `sparse_indexer.rs`'s shape —
//! put-if-absent, then one manifest compare-and-swap — but reads the whole
//! segment the way `indexer.rs`'s dense index does (there is no
//! `min_rows` floor: building this index is one pass over attributes
//! already being decoded, not a quantization or graph build).

use std::collections::BTreeMap;

use object_store::path::Path;
use object_store::{ObjectStore, ObjectStoreExt, PutMode, PutOptions};
use serde::{Deserialize, Serialize};

use crate::attr_index::{self, FieldBuild, Kind, Value};
use crate::attrs::AttrSchema;
use crate::budget::ReadBudget;
use crate::cpu::Lane;
use crate::error::{ItzmaError, Result};
use crate::fetch::FetchPolicy;
use crate::manifest::{self, AttrIndexEntry};
use crate::segment;

/// Settings for [`Namespace::index_attrs`](crate::Namespace::index_attrs).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct IndexAttrsOptions {
    /// Build a new generation for a segment that already has an attribute
    /// index, instead of leaving it alone. The old object stays until
    /// [`gc`](crate::Namespace::gc) collects it.
    pub rebuild: bool,
}

impl IndexAttrsOptions {
    /// Set [`rebuild`](Self::rebuild).
    #[must_use]
    pub fn rebuild(mut self, rebuild: bool) -> Self {
        self.rebuild = rebuild;
        self
    }
}

/// What a call to [`Namespace::index_attrs`](crate::Namespace::index_attrs)
/// did, one count per live segment it looked at.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct IndexAttrsReport {
    /// Segments this run published an attribute index for.
    pub indexed: usize,
    /// Segments left alone because the namespace's schema marks no field
    /// indexed.
    pub skipped_no_indexed_fields: usize,
    /// Segments that already had an attribute index (and `rebuild` was not
    /// set), or that another indexer published while this run built its
    /// own.
    pub already_indexed: usize,
    /// Segments a compaction retired while this run was working on them.
    pub superseded: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Outcome {
    Indexed,
    SkippedNoIndexedFields,
    AlreadyIndexed,
    Superseded,
}

impl IndexAttrsReport {
    pub(crate) fn record(&mut self, outcome: Outcome) {
        let count = match outcome {
            Outcome::Indexed => &mut self.indexed,
            Outcome::SkippedNoIndexedFields => &mut self.skipped_no_indexed_fields,
            Outcome::AlreadyIndexed => &mut self.already_indexed,
            Outcome::Superseded => &mut self.superseded,
        };
        *count += 1;
    }
}

/// Index the live segment `id`'s indexed attribute fields, whose current
/// entry in the manifest is `have`. Checks the schema before touching
/// storage: a namespace with no indexed field costs nothing to call this
/// on.
///
/// # Errors
///
/// Whatever reading the segment gives, [`ItzmaError::CorruptAttrIndex`] if
/// an object already at the new key does not fit the segment, and the
/// errors of a manifest update.
#[allow(clippy::too_many_arguments)] // mirrors indexer::index_segment's shape
pub(crate) async fn index_segment(
    store: &dyn ObjectStore,
    namespace: &str,
    dim: usize,
    attrs: &AttrSchema,
    id: &str,
    have: Option<&AttrIndexEntry>,
    options: &IndexAttrsOptions,
    read_budget: u64,
    policy: &FetchPolicy,
) -> Result<Outcome> {
    if have.is_some() && !options.rebuild {
        return Ok(Outcome::AlreadyIndexed);
    }
    let indexed_fields: Vec<(String, crate::attrs::AttrType)> = attrs
        .indexed_field_names()
        .map(|name| (name.to_string(), attrs.get(name).expect("declared")))
        .collect();
    if indexed_fields.is_empty() {
        return Ok(Outcome::SkippedNoIndexedFields);
    }

    let budget = ReadBudget::new(read_budget);
    let data_path = segment::segment_path(namespace, id);
    let bytes = segment::fetch_bytes(store, &data_path, &budget, policy).await?;
    let layer = segment::decode_on(Lane::Maintenance, data_path.clone(), bytes, dim).await?;
    let docs = layer.sorted_docs();
    let rows = docs.len() as u32;

    let mut per_field: BTreeMap<String, Vec<(Value, u32)>> = indexed_fields
        .iter()
        .map(|(name, _)| (name.clone(), Vec::new()))
        .collect();
    for (row, doc) in docs.iter().enumerate() {
        let row = row as u32;
        for (name, ty) in &indexed_fields {
            let pairs = per_field.get_mut(name).expect("seeded above");
            match ty {
                crate::attrs::AttrType::TextSet | crate::attrs::AttrType::NumberSet => {
                    for value in attr_index::field_elements(doc.attrs.as_ref(), name, *ty) {
                        pairs.push((value, row));
                    }
                }
                _ => {
                    if let Some(value) = attr_index::field_value(doc.attrs.as_ref(), name, *ty) {
                        pairs.push((value, row));
                    }
                }
            }
        }
    }
    let fields: BTreeMap<String, FieldBuild> = per_field
        .into_iter()
        .map(|(name, pairs)| {
            let ty = indexed_fields
                .iter()
                .find(|(n, _)| n == &name)
                .expect("seeded above")
                .1;
            let kind = Kind::of(ty);
            let entries = attr_index::group_sorted(pairs);
            (name, FieldBuild { kind, entries })
        })
        .collect();

    let names = segment::object_names(store, namespace, id).await?;
    let floor = segment::generation_floor(
        have.map(|entry| entry.generation),
        &names,
        attr_index::generation_of,
    );
    let generation = segment::claim_generation(store, namespace, id, floor).await?;
    let path = attr_index::attr_index_path(namespace, id, generation);
    let built = attr_index::build(rows, &fields);
    put_or_reuse(store, &path, built, u64::from(rows)).await?;

    publish(store, namespace, id, have, generation).await
}

/// Write the attribute index with put-if-absent. An object already at the
/// key is an orphan of an earlier run or the winner of a race, and it is
/// used if it checks out as a valid attribute index of this segment.
async fn put_or_reuse(
    store: &dyn ObjectStore,
    path: &Path,
    built: bytes::Bytes,
    rows: u64,
) -> Result<()> {
    match store
        .put_opts(path, built.into(), PutOptions::from(PutMode::Create))
        .await
    {
        Ok(_) => Ok(()),
        Err(object_store::Error::AlreadyExists { .. }) => {
            let existing = store.get(path).await?.bytes().await?;
            attr_index::open_bytes_for_check(path.as_ref(), &existing, rows).map_err(
                |err| match err {
                    ItzmaError::CorruptAttrIndex { path, reason } => ItzmaError::CorruptAttrIndex {
                        path,
                        reason: format!(
                            "{reason}; an object already at this key does not fit the \
                                 segment, delete it and rerun"
                        ),
                    },
                    other => other,
                },
            )
        }
        Err(e) => Err(e.into()),
    }
}

/// List the attribute index in the manifest, if it still looks the way it
/// did when the run planned: the segment live and its entry unchanged.
async fn publish(
    store: &dyn ObjectStore,
    namespace: &str,
    id: &str,
    have: Option<&AttrIndexEntry>,
    generation: u32,
) -> Result<Outcome> {
    let mut lost = Outcome::AlreadyIndexed;
    let published = manifest::update_if(store, namespace, |m| {
        if !m.live_segments.iter().any(|live| live == id) {
            lost = Outcome::Superseded;
            return false;
        }
        if m.attr_indexes.get(id) != have {
            lost = Outcome::AlreadyIndexed;
            return false;
        }
        m.attr_indexes
            .insert(id.to_string(), AttrIndexEntry { generation });
        true
    })
    .await?;
    Ok(published.map_or(lost, |_| Outcome::Indexed))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rebuild_setter_changes_the_default() {
        assert!(!IndexAttrsOptions::default().rebuild);
        assert!(IndexAttrsOptions::default().rebuild(true).rebuild);
    }
}