itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
Documentation
//! What a scan holds: a range holds windows of the
//! segments its range reaches, not of every live segment; a window is held
//! about as compactly as it is stored; a batch's vectors are held once; and a
//! tombstone window is parsed without a buffer per row.
//! A file of its own, and one test: the counting allocator sees every
//! allocation in the binary, so nothing may run beside a measurement.

mod common;

use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use futures::StreamExt;
use itzma_core::scan::{Columns, ScanOptions};
use itzma_core::{AttrSchema, AttrType, CompactionOptions, Document, Metric, Namespace, Schema};
use object_store::ObjectStore;
use object_store::memory::InMemory;

/// Counts the bytes allocated right now and the most ever at once.
struct Counting;

static NOW: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);

unsafe impl GlobalAlloc for Counting {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let p = unsafe { System.alloc(layout) };
        if !p.is_null() {
            let now = NOW.fetch_add(layout.size(), Ordering::Relaxed) + layout.size();
            PEAK.fetch_max(now, Ordering::Relaxed);
        }
        p
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        unsafe { System.dealloc(ptr, layout) };
        NOW.fetch_sub(layout.size(), Ordering::Relaxed);
    }
}

#[global_allocator]
static ALLOCATOR: Counting = Counting;

const DIM: usize = 4;
const SEGMENTS: usize = 8;
const ROWS: usize = 20_000;
const RANGES: usize = 4;
const TOMBSTONES: usize = 40_000;
/// Peak bytes per byte fetched allowed while a tombstone window opens: the
/// fetched bytes themselves (once more while a copying store's pieces are
/// joined) and the column. Parsed through a buffer per row it was 3.9.
const TOMBSTONE_PEAK: f64 = 2.5;

/// Reset the peak to what is allocated now, and return that.
fn reset() -> usize {
    let now = NOW.load(Ordering::SeqCst);
    PEAK.store(now, Ordering::SeqCst);
    now
}

fn now() -> usize {
    NOW.load(Ordering::SeqCst)
}

fn peak() -> usize {
    PEAK.load(Ordering::SeqCst)
}

/// A namespace of `segments` folds of `rows` documents each, disjoint id
/// ranges, every document with a short attribute object when `attrs` is set.
async fn namespace(
    counting: &Arc<common::counting::CountingStore>,
    dim: usize,
    segments: usize,
    rows: usize,
    attrs: bool,
) -> Namespace {
    let store: Arc<dyn ObjectStore> = counting.clone();
    let schema = Schema::new(dim, Metric::L2).with_attrs(
        AttrSchema::new()
            .field("name", AttrType::Text)
            .field("price", AttrType::Number),
    );
    let ns = Namespace::create(store, "docs", schema).await.unwrap();
    for s in 0..segments {
        let docs = (0..rows)
            .map(|i| Document {
                id: format!("d{:07}", s * rows + i),
                vector: vec![i as f32; dim],
                attrs: attrs
                    .then(|| serde_json::json!({ "name": format!("n{}", i % 97), "price": i })),
                sparse: None,
            })
            .collect();
        ns.upsert(docs).await.unwrap();
        ns.compact(&CompactionOptions::default()).await.unwrap();
    }
    ns
}

/// What one whole scan holds once open, against the bytes it fetched to
/// open it (each segment's first window): the decoded factor of a window.
async fn opened_factor(
    ns: &Namespace,
    counting: &common::counting::CountingStore,
    columns: Columns,
) -> (usize, usize) {
    counting.reset();
    let before = reset();
    let mut whole = ns
        .scan(ScanOptions::default().columns(columns).batch_rows(1))
        .unwrap();
    let first = whole.next().await.unwrap().unwrap();
    let held = now() - before;
    let fetched = counting.bytes() as usize;
    drop((first, whole));
    (held, fetched)
}

#[tokio::test]
async fn a_scan_holds_its_windows_compactly_and_its_vectors_once() {
    let mut failures = Vec::new();

    // 1. Decoded bytes per stored byte of a window, for documents with and
    // without attributes. One `String` and one `Bytes` per row held a window
    // at three to six times its stored size.
    for attrs in [false, true] {
        let counting =
            Arc::new(common::counting::CountingStore::wrapping(InMemory::new()).copying());
        let ns = namespace(&counting, DIM, SEGMENTS, ROWS, attrs).await;
        let (held, fetched) = opened_factor(&ns, &counting, Columns::ids_only()).await;
        let factor = held as f64 / fetched as f64;
        eprintln!(
            "whole scan, attributes {attrs}: fetched {fetched} bytes, held {held}: {factor:.2} held per byte fetched"
        );
        if factor > 2.0 {
            failures.push(format!(
                "attributes {attrs}: a window held {factor:.2} bytes per byte fetched"
            ));
        }
    }
    let counting = Arc::new(common::counting::CountingStore::wrapping(InMemory::new()).copying());
    let ns = namespace(&counting, DIM, SEGMENTS, ROWS, false).await;

    // 2. Four range scans, each opened with its first batch in hand (what the
    // bridge's range tasks hold while they wait on their channels), hold
    // about what one whole scan does, not a window of every segment each.
    let ids = ScanOptions::default().columns(Columns::ids_only());
    let before = reset();
    let mut whole = ns.scan(ids.clone()).unwrap();
    let first = whole.next().await.unwrap().unwrap();
    let whole_held = now() - before;
    drop((first, whole));
    let ranges = ns.scan_splits(RANGES).await.unwrap();
    assert_eq!(ranges.len(), RANGES);
    let before = reset();
    let mut streams: Vec<_> = ranges
        .iter()
        .map(|r| ns.scan(ids.clone().range(r)).unwrap())
        .collect();
    let mut batches = Vec::new();
    for stream in &mut streams {
        batches.push(stream.next().await.unwrap().unwrap());
    }
    let ranges_held = now() - before;
    drop((batches, streams));
    eprintln!("whole scan held {whole_held} bytes, {RANGES} range scans {ranges_held}");
    if ranges_held >= whole_held * 3 / 2 {
        failures.push(format!(
            "{RANGES} range scans held {ranges_held} bytes, one whole scan {whole_held}"
        ));
    }
    drop(ns);

    // 3. A batch's vectors are held once: one segment of exactly one batch,
    // read to the end with and without its vectors. Fetched rows decoded
    // into a matrix and then copied into the batch's held them twice.
    let dim = 128;
    let rows = 8_192;
    let counting = Arc::new(common::counting::CountingStore::wrapping(InMemory::new()).copying());
    let ns = namespace(&counting, dim, 1, rows, false).await;
    let vectors = rows * dim * 4;
    let mut grew = [0; 2];
    for (at, with_vectors) in [false, true].into_iter().enumerate() {
        let before = reset();
        let mut scan = ns
            .scan(
                ScanOptions::default()
                    .columns(Columns::ids_only().vectors(with_vectors))
                    .batch_rows(rows),
            )
            .unwrap();
        while let Some(batch) = scan.next().await {
            drop(batch.unwrap());
        }
        drop(scan);
        grew[at] = peak() - before;
    }
    let per_vector_byte = (grew[1] - grew[0]) as f64 / vectors as f64;
    eprintln!(
        "one batch of {rows} rows: peak grew {} without vectors, {} with {vectors} bytes of them: {per_vector_byte:.2} per vector byte",
        grew[0], grew[1]
    );
    if per_vector_byte >= 1.25 {
        failures.push(format!(
            "a batch held {per_vector_byte:.2} bytes per byte of its vectors"
        ));
    }
    drop(ns);

    // 4. A tombstone window is parsed straight into its column: the peak of
    // opening a scan over a segment of tombstones stays near the bytes it
    // fetched. A buffer per row on the way to the column, freed once the
    // column was built, peaked at several times that.
    let counting = Arc::new(common::counting::CountingStore::wrapping(InMemory::new()).copying());
    let store: Arc<dyn ObjectStore> = counting.clone();
    let ns = Namespace::create(store, "docs", Schema::new(DIM, Metric::L2))
        .await
        .unwrap();
    ns.upsert(vec![common::doc("a", &[0.0; DIM])])
        .await
        .unwrap();
    ns.compact(&CompactionOptions::default()).await.unwrap();
    ns.delete((0..TOMBSTONES).map(|n| format!("t{n:07}")).collect())
        .await
        .unwrap();
    ns.compact(&CompactionOptions::default()).await.unwrap();
    counting.reset();
    let before = reset();
    let mut scan = ns
        .scan(
            ScanOptions::default()
                .columns(Columns::ids_only())
                .batch_rows(1),
        )
        .unwrap();
    let first = scan.next().await.unwrap().unwrap();
    let grew = peak() - before;
    let fetched = counting.bytes() as usize;
    drop((first, scan));
    let factor = grew as f64 / fetched as f64;
    eprintln!(
        "tombstone window: fetched {fetched} bytes, peak grew {grew}: {factor:.2} per byte fetched"
    );
    if factor > TOMBSTONE_PEAK {
        failures.push(format!(
            "opening a tombstone window peaked at {factor:.2} bytes per byte fetched"
        ));
    }

    assert!(failures.is_empty(), "{failures:#?}");
}