itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
Documentation
//! What a cache directory's owner prevents: one store's bytes served as
//! another's.
//!
//! ```text
//! cargo run --release --example cache_owner -- <dir> [--out <file>]
//! ```
//!
//! `<dir>` is the `cache-owner` synthetic dataset (`make synthetic
//! ONLY=cache-owner SIZE=full`): `schema.json` and the rows of two stores,
//! `rows.jsonl` (ids `a-...`) and `rows-b.jsonl` (ids `b-...`), the same
//! length so their segments have the same layout. Both stores hold a
//! namespace of one name, so their objects have the same paths, which is all
//! a cache entry is named by. Store A is queried through a cache directory,
//! then store B through the same directory. With no owner set B is answered
//! from A's entries. With owners set the directory refuses B. The count of A's
//! ids in B's answer goes 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::{
    AttrSchema, CacheOptions, CacheStore, CompactionOptions, Document, ItzmaError, Metric,
    Namespace, NvmeOptions, Schema,
};
use object_store::ObjectStore;
use object_store::memory::InMemory;
use serde_json::{Value, json};

const DIM: usize = 4;
const BATCH: usize = 500;
const TOP_K: usize = 10;
const ID: &str = "owner-demo";
const COMPACT: CompactionOptions = CompactionOptions {
    max_segments: 8,
    max_segment_bytes: DEFAULT_MAX_SEGMENT_BYTES,
};

/// Everything one run found.
#[derive(Debug, Default)]
pub struct Findings {
    /// Store A's ids in store B's answer when the directory had no owner.
    pub foreign_without_owner: usize,
    /// Store A's ids in store B's answer when the directory had owners (none:
    /// B was refused).
    pub foreign_with_owner: usize,
    /// The directory refused store B when it had owners.
    pub refused: bool,
    /// Store A, back after a restart, was let in.
    pub same_owner_welcome: bool,
}

impl Findings {
    pub fn passed(&self) -> bool {
        self.foreign_without_owner > 0
            && self.foreign_with_owner == 0
            && self.refused
            && self.same_owner_welcome
    }

    /// The charts' data: what ran, on what, and how many wrong ids each way.
    pub fn results(&self, size: &str, rows: usize) -> Value {
        json!({
            "functionality": "cache-owner",
            "version": env!("CARGO_PKG_VERSION"),
            "dataset": "cache-owner",
            "size": size,
            "rows": rows,
            "top_k": TOP_K,
            "results": [
                {"name": "no-owner", "foreign_ids": self.foreign_without_owner, "refused": false},
                {"name": "owner", "foreign_ids": self.foreign_with_owner, "refused": self.refused},
            ],
        })
    }
}

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

/// A compacted store holding `docs`.
async fn store_with(
    docs: &[Document],
    attrs: &AttrSchema,
) -> Result<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(), ID, schema).await?;
    for chunk in docs.chunks(BATCH) {
        ns.upsert(chunk.to_vec()).await?;
    }
    ns.compact(&COMPACT).await?;
    Ok(store)
}

/// The cache over `store` with its NVMe tier in `dir`, or the refusal.
fn cached(
    store: &Arc<dyn ObjectStore>,
    dir: &Path,
    owner: Option<&str>,
) -> Result<Arc<CacheStore>, ItzmaError> {
    let mut nvme = NvmeOptions::new(dir, 64 << 20);
    if let Some(owner) = owner {
        nvme = nvme.owner(owner);
    }
    let mut options = CacheOptions::default();
    options.nvme = Some(nvme);
    Ok(Arc::new(CacheStore::new(store.clone(), options)?))
}

/// The ids nearest `vector` through `cache`, a new handle and RAM tier each
/// call so only the directory is shared.
async fn nearest(
    store: &Arc<dyn ObjectStore>,
    cache: Arc<CacheStore>,
    vector: &[f32],
) -> Result<Vec<String>, ItzmaError> {
    let ns = Namespace::open(store.clone(), ID).await?.with_cache(cache);
    Ok(ns
        .query(vector, TOP_K)
        .await?
        .into_iter()
        .map(|hit| hit.id)
        .collect())
}

/// Run store A and then store B through one directory, `owners` naming them
/// or not. B's answer, or `None` when the directory refused it.
async fn through_one_directory(
    stores: [&Arc<dyn ObjectStore>; 2],
    dir: &Path,
    owners: [Option<&str>; 2],
    vector: &[f32],
) -> Result<Option<Vec<String>>, ItzmaError> {
    nearest(stores[0], cached(stores[0], dir, owners[0])?, vector).await?;
    match cached(stores[1], dir, owners[1]) {
        Ok(cache) => Ok(Some(nearest(stores[1], cache, vector).await?)),
        Err(_) => Ok(None),
    }
}

fn foreign(answer: &[String]) -> usize {
    answer.iter().filter(|id| id.starts_with("a-")).count()
}

/// Build the two stores once and run the directory both ways.
pub async fn run(
    schema: &Value,
    rows_a: &str,
    rows_b: &str,
) -> Result<Findings, Box<dyn std::error::Error>> {
    let attrs: AttrSchema = serde_json::from_value(schema.clone())?;
    let (docs_a, docs_b) = (documents(rows_a)?, documents(rows_b)?);
    let vector = docs_a.first().map(|d| d.vector.clone()).unwrap_or_default();
    let (a, b) = (
        store_with(&docs_a, &attrs).await?,
        store_with(&docs_b, &attrs).await?,
    );
    let mut found = Findings::default();

    let open = tempfile::tempdir()?;
    let answer = through_one_directory([&a, &b], open.path(), [None, None], &vector).await?;
    found.foreign_without_owner = answer.as_deref().map_or(0, foreign);

    let owned = tempfile::tempdir()?;
    let owners = [Some("store-a"), Some("store-b")];
    let answer = through_one_directory([&a, &b], owned.path(), owners, &vector).await?;
    found.refused = answer.is_none();
    found.foreign_with_owner = answer.as_deref().map_or(0, foreign);
    found.same_owner_welcome = cached(&a, owned.path(), Some("store-a")).is_ok();
    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: cache_owner <dir> [--out <file>]");
            return ExitCode::from(2);
        }
    };
    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("rows.jsonl"))?,
            std::fs::read_to_string(dir.join("rows-b.jsonl"))?,
            read_json(&dir.join("meta.json"))?,
        ))
    };
    let (schema, rows_a, rows_b, meta) = match read() {
        Ok(data) => data,
        Err(error) => {
            eprintln!(
                "{}: {error}; run: make synthetic ONLY=cache-owner SIZE=full",
                dir.display()
            );
            return ExitCode::from(2);
        }
    };
    match run(&schema, &rows_a, &rows_b).await {
        Ok(found) => {
            println!(
                "no owner:   {} of store A's ids in store B's top {TOP_K}",
                found.foreign_without_owner
            );
            println!(
                "with owner: {} of store A's ids in store B's top {TOP_K}",
                found.foreign_with_owner
            );
            println!("refused: {}", found.refused);
            println!("same_owner_welcome: {}", found.same_owner_welcome);
            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!("cache_owner: {error}");
            ExitCode::from(1)
        }
    }
}

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

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

    #[tokio::test]
    async fn an_owner_keeps_one_store_from_being_served_the_others_bytes() {
        let schema = json!({"n": "number"});
        let found = run(&schema, &rows("a", 300), &rows("b", 300))
            .await
            .unwrap();
        assert!(found.passed(), "{found:#?}");
        let results = found.results("small", 300);
        assert_eq!(results["functionality"], "cache-owner");
        assert_eq!(results["results"][1]["refused"], true);
    }
}