itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
Documentation
//! Typed columns and zone maps (segment format 3) against the plain format 2:
//! the same filters must return the same rows, whatever the format and
//! whatever order the rows were written in.
//!
//! ```text
//! cargo run --example segment_format -- <dir>
//! ```
//!
//! `<dir>` is the `segment-format-3` synthetic dataset (`make synthetic
//! ONLY=segment-format-3 SIZE=full`): `schema.json`, `docs-sorted.jsonl`,
//! `docs-shuffled.jsonl` and `predicates.json`, each predicate with the count
//! the generator worked out without the filter. Runs on an in-memory store.
//! The exit code is 1 when a count or an answer differs.

use std::collections::BTreeSet;
use std::path::Path;
use std::process::ExitCode;
use std::sync::Arc;

use itzma_core::compaction::DEFAULT_MAX_SEGMENT_BYTES;
use itzma_core::filter::MAX_FILTER_LIMIT;
use itzma_core::inspect;
use itzma_core::{
    AttrSchema, CompactionOptions, Document, FilterOptions, ItzmaError, Metric, Namespace,
    Predicate, Schema,
};
use object_store::ObjectStore;
use object_store::memory::InMemory;
use serde_json::Value;

const DIM: usize = 4;
const BATCH: usize = 200;
const COMPACT: CompactionOptions = CompactionOptions {
    max_segments: 8,
    max_segment_bytes: DEFAULT_MAX_SEGMENT_BYTES,
};

/// One filter's answer under one format and order.
#[derive(Debug, PartialEq, Eq)]
pub struct Answer {
    pub name: String,
    pub ids: BTreeSet<String>,
}

/// Everything one run found.
#[derive(Debug, Default)]
pub struct Findings {
    /// `(order, format)` for every namespace built, with the segment format the manifest ended at.
    pub namespaces: Vec<(String, u32, u32)>,
    pub counts_match: bool,
    pub answers_agree: bool,
    pub format_3_reached: bool,
}

impl Findings {
    pub fn passed(&self) -> bool {
        self.counts_match && self.answers_agree && self.format_3_reached
    }
}

fn documents(text: &str) -> Result<Vec<Document>, serde_json::Error> {
    text.lines()
        .map(|line| {
            let row: Value = serde_json::from_str(line)?;
            let vector = row["vector"]
                .as_array()
                .into_iter()
                .flatten()
                .map(|x| x.as_f64().unwrap_or_default() as f32)
                .collect();
            Ok(Document {
                id: row["id"].as_str().unwrap_or_default().to_string(),
                vector,
                attrs: Some(row["attrs"].clone()),
                sparse: None,
            })
        })
        .collect()
}

async fn build(
    docs: &[Document],
    attrs: &AttrSchema,
    name: &str,
    level: u32,
) -> Result<(Namespace, Arc<dyn ObjectStore>), ItzmaError> {
    let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
    let schema = Schema::new(DIM, Metric::L2).with_attrs(attrs.clone());
    let ns = Namespace::create(store.clone(), name, schema).await?;
    if level >= 3 {
        ns.upgrade_segment_format(level).await?;
    }
    for chunk in docs.chunks(BATCH) {
        ns.upsert(chunk.to_vec()).await?;
    }
    ns.compact(&COMPACT).await?;
    Ok((ns, store))
}

async fn answer(ns: &Namespace, name: &str, predicate: &Predicate) -> Result<Answer, ItzmaError> {
    let mut ids = BTreeSet::new();
    let mut after = None;
    loop {
        let mut options = FilterOptions::default();
        options.limit = MAX_FILTER_LIMIT;
        options.after = after;
        let page = ns.filter(predicate, &options).await?;
        ids.extend(page.rows.into_iter().map(|row| row.id));
        match page.next {
            Some(next) => after = Some(next),
            None => break,
        }
    }
    Ok(Answer {
        name: name.to_string(),
        ids,
    })
}

/// Build each order at format 2 and 3, run every predicate, compare.
pub async fn run(
    schema: &Value,
    sorted: &str,
    shuffled: &str,
    predicates: &Value,
) -> Result<Findings, Box<dyn std::error::Error>> {
    let attrs: AttrSchema = serde_json::from_value(schema.clone())?;
    let wanted: Vec<(String, Predicate, usize)> = predicates
        .as_array()
        .into_iter()
        .flatten()
        .map(|entry| {
            Ok((
                entry["name"].as_str().unwrap_or_default().to_string(),
                serde_json::from_value::<Predicate>(entry["predicate"].clone())?,
                entry["expected"].as_u64().unwrap_or_default() as usize,
            ))
        })
        .collect::<Result<_, serde_json::Error>>()?;

    let mut found = Findings {
        counts_match: true,
        answers_agree: true,
        format_3_reached: true,
        ..Findings::default()
    };
    let mut first: Option<Vec<Answer>> = None;
    for (order, text) in [("sorted", sorted), ("shuffled", shuffled)] {
        let docs = documents(text)?;
        for level in [2, 3] {
            let (ns, store) =
                build(&docs, &attrs, &format!("format-{order}-{level}"), level).await?;
            let manifest = inspect::report(&*store, &format!("format-{order}-{level}"))
                .await?
                .manifest;
            let reached = manifest.map_or(0, |m| m.segment_format);
            found.format_3_reached &= reached == level.max(2);
            found.namespaces.push((order.to_string(), level, reached));
            let mut answers = Vec::new();
            for (name, predicate, expected) in &wanted {
                let got = answer(&ns, name, predicate).await?;
                found.counts_match &= got.ids.len() == *expected;
                answers.push(got);
            }
            match &first {
                None => first = Some(answers),
                Some(reference) => found.answers_agree &= *reference == answers,
            }
        }
    }
    Ok(found)
}

fn read_json(path: &Path) -> Result<Value, Box<dyn std::error::Error>> {
    Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?)
}

#[tokio::main]
async fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let [dir] = args.as_slice() else {
        eprintln!("usage: segment_format <dir>");
        return ExitCode::from(2);
    };
    let dir = Path::new(dir);
    let read = || -> Result<(Value, String, String, Value), Box<dyn std::error::Error>> {
        Ok((
            read_json(&dir.join("schema.json"))?,
            std::fs::read_to_string(dir.join("docs-sorted.jsonl"))?,
            std::fs::read_to_string(dir.join("docs-shuffled.jsonl"))?,
            read_json(&dir.join("predicates.json"))?,
        ))
    };
    let (schema, sorted, shuffled, predicates) = match read() {
        Ok(data) => data,
        Err(error) => {
            eprintln!(
                "{}: {error}; run: make synthetic ONLY=segment-format-3 SIZE=full",
                dir.display()
            );
            return ExitCode::from(2);
        }
    };
    match run(&schema, &sorted, &shuffled, &predicates).await {
        Ok(found) => {
            println!("{found:#?}");
            if found.passed() {
                ExitCode::SUCCESS
            } else {
                ExitCode::from(1)
            }
        }
        Err(error) => {
            eprintln!("segment_format: {error}");
            ExitCode::from(1)
        }
    }
}

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

    fn rows(order: &[usize]) -> String {
        order
            .iter()
            .map(|n| {
                json!({
                    "id": format!("item-{n:03}"),
                    "vector": [*n as f64, 0.0, 1.0, 0.5],
                    "attrs": {"price": *n as f64, "tag": if n % 2 == 0 { "even" } else { "odd" }},
                })
                .to_string()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[tokio::test]
    async fn the_two_formats_and_orders_answer_alike() {
        let ascending: Vec<usize> = (0..300).collect();
        let descending: Vec<usize> = (0..300).rev().collect();
        let schema = json!({"price": "number", "tag": "string"});
        let predicates = json!([
            {"name": "cheap", "expected": 50,
             "predicate": {"Number": {"field": "price", "op": "Lt", "value": 50.0}}},
            {"name": "even", "expected": 150,
             "predicate": {"Text": {"field": "tag", "op": "Eq", "value": "even"}}},
        ]);
        let found = run(&schema, &rows(&ascending), &rows(&descending), &predicates)
            .await
            .unwrap();
        assert!(found.passed(), "{found:#?}");
        assert_eq!(found.namespaces.len(), 4);
    }
}