itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
Documentation
//! Where rounding block reads out to `align` costs bytes, counted at the
//! object store.
//!
//! ```text
//! cargo run --release --example align -- <dir> [--out <file>]
//! ```
//!
//! `<dir>` is the `align-behind-cache` synthetic dataset (`make synthetic
//! ONLY=align-behind-cache SIZE=full`): `schema.json`, `rows.jsonl` and
//! `predicate.json`, the filter with the count the generator worked out. The
//! same selective filter runs four ways over one compacted segment: with and
//! without a cache under the handle, at the default fetch policy and with
//! `align` 1. Behind no cache the two policies read the same bytes, since
//! nothing would share a widened window. Behind a cache the default rounds
//! each read out to its grid, so it fetches more from the origin than the
//! unaligned read; the extra is what later reads share. The bytes and
//! requests go to `--out` (default `<dir>/demo-results.json`) for the charts.
//! The exit code is 1 when a check fails.

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::{
    AttrSchema, CacheOptions, CacheStore, CompactionOptions, Document, FetchPolicy, FilterOptions,
    ItzmaError, Metric, Namespace, Predicate, Schema,
};
use object_store::ObjectStore;
use serde_json::{Value, json};

#[path = "common/counting.rs"]
mod counting;
use counting::CountingStore;

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

/// What one way of reading cost.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cost {
    pub name: &'static str,
    pub cached: bool,
    pub align: u64,
    pub rows: usize,
    pub requests: usize,
    pub bytes: u64,
}

/// Everything one run found.
#[derive(Debug, Default)]
pub struct Findings {
    pub expected: usize,
    pub costs: Vec<Cost>,
}

impl Findings {
    fn bytes(&self, name: &str) -> u64 {
        self.costs
            .iter()
            .find(|c| c.name == name)
            .map_or(0, |c| c.bytes)
    }

    /// Every read returned the expected count; behind no cache the policies
    /// read the same bytes; behind a cache the default read more.
    pub fn passed(&self) -> bool {
        self.costs.len() == 4
            && self.costs.iter().all(|c| c.rows == self.expected)
            && self.bytes("uncached-default") == self.bytes("uncached-align-1")
            && self.bytes("cached-default") > self.bytes("cached-align-1")
    }

    /// The charts' data: what ran, on what, and what each read fetched.
    pub fn results(&self, size: &str, rows: usize) -> Value {
        json!({
            "functionality": "align-behind-cache",
            "version": env!("CARGO_PKG_VERSION"),
            "dataset": "align-behind-cache",
            "size": size,
            "rows": rows,
            "expected": self.expected,
            "results": self.costs.iter().map(|c| json!({
                "name": c.name,
                "cached": c.cached,
                "align": c.align,
                "rows": c.rows,
                "requests": c.requests,
                "bytes": c.bytes,
            })).collect::<Vec<_>>(),
        })
    }
}

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()
}

/// One filter through a fresh handle, with a cache under it or not.
async fn read(
    store: &Arc<CountingStore>,
    predicate: &Predicate,
    name: &'static str,
    cached: bool,
    policy: FetchPolicy,
) -> Result<Cost, ItzmaError> {
    let align = policy.align;
    let origin: Arc<dyn ObjectStore> = store.clone();
    let mut ns = Namespace::open(origin.clone(), "docs")
        .await?
        .with_fetch_policy(policy);
    if cached {
        let cache = CacheStore::new(origin, CacheOptions::default())?;
        ns = ns.with_cache(Arc::new(cache));
    }
    store.reset();
    let page = ns
        .filter(predicate, &FilterOptions::default().limit(MAX_FILTER_LIMIT))
        .await?;
    Ok(Cost {
        name,
        cached,
        align,
        rows: page.rows.len(),
        requests: store.requests(),
        bytes: store.bytes(),
    })
}

/// Build the segment once and read it the four ways.
pub async fn run(
    schema: &Value,
    rows: &str,
    filter: &Value,
) -> Result<Findings, Box<dyn std::error::Error>> {
    let attrs: AttrSchema = serde_json::from_value(schema.clone())?;
    let predicate: Predicate = serde_json::from_value(filter["predicate"].clone())?;
    let store = Arc::new(CountingStore::default());
    let origin: Arc<dyn ObjectStore> = store.clone();
    let ns = Namespace::create(
        origin,
        "docs",
        Schema::new(DIM, Metric::L2).with_attrs(attrs),
    )
    .await?;
    ns.upgrade_segment_format(3).await?;
    for chunk in documents(rows)?.chunks(BATCH) {
        ns.upsert(chunk.to_vec()).await?;
    }
    ns.compact(&COMPACT).await?;

    let mut found = Findings {
        expected: filter["expected"].as_u64().unwrap_or_default() as usize,
        costs: Vec::new(),
    };
    for (name, cached, policy) in [
        ("uncached-default", false, FetchPolicy::default()),
        ("uncached-align-1", false, FetchPolicy::default().align(1)),
        ("cached-default", true, FetchPolicy::default()),
        ("cached-align-1", true, FetchPolicy::default().align(1)),
    ] {
        found
            .costs
            .push(read(&store, &predicate, name, cached, policy).await?);
    }
    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, out) = match args.as_slice() {
        [dir] => (Path::new(dir), Path::new(dir).join("demo-results.json")),
        [dir, flag, out] if flag == "--out" => (Path::new(dir), Path::new(out).to_path_buf()),
        _ => {
            eprintln!("usage: align <dir> [--out <file>]");
            return ExitCode::from(2);
        }
    };
    let load = || -> Result<(Value, String, Value, Value), Box<dyn std::error::Error>> {
        Ok((
            read_json(&dir.join("schema.json"))?,
            std::fs::read_to_string(dir.join("rows.jsonl"))?,
            read_json(&dir.join("predicate.json"))?,
            read_json(&dir.join("meta.json"))?,
        ))
    };
    let (schema, rows, filter, meta) = match load() {
        Ok(data) => data,
        Err(error) => {
            eprintln!(
                "{}: {error}; run: make synthetic ONLY=align-behind-cache SIZE=full",
                dir.display()
            );
            return ExitCode::from(2);
        }
    };
    match run(&schema, &rows, &filter).await {
        Ok(found) => {
            for c in &found.costs {
                println!(
                    "{:<17} {:>5} requests {:>10} bytes ({} rows)",
                    c.name, c.requests, c.bytes, c.rows
                );
            }
            let size = meta["size"].as_str().unwrap_or_default();
            let count = meta["rows"].as_u64().unwrap_or_default() as usize;
            let text =
                serde_json::to_string_pretty(&found.results(size, count)).unwrap_or_default();
            if let Err(error) = std::fs::write(&out, text + "\n") {
                eprintln!("{}: {error}", out.display());
                return ExitCode::from(1);
            }
            if found.passed() {
                ExitCode::SUCCESS
            } else {
                ExitCode::from(1)
            }
        }
        Err(error) => {
            eprintln!("align: {error}");
            ExitCode::from(1)
        }
    }
}

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

    fn rows(count: usize) -> String {
        (0..count)
            .map(|n| {
                json!({
                    "id": format!("item-{n:08}"),
                    "vector": [n as f64, 0.0, 1.0, 0.5],
                    "attrs": {"price": n as f64},
                })
                .to_string()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[tokio::test]
    async fn alignment_costs_bytes_only_behind_a_cache() {
        let filter = json!({
            "predicate": {"Number": {"field": "price", "op": "Lt", "value": 20.0}},
            "expected": 20,
        });
        let found = run(&json!({"price": "number"}), &rows(5_000), &filter)
            .await
            .unwrap();
        assert!(found.passed(), "{found:#?}");
        let results = found.results("small", 5_000);
        assert_eq!(results["functionality"], "align-behind-cache");
        assert_eq!(results["results"].as_array().map(Vec::len), Some(4));
    }
}