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;
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;
const TOMBSTONE_PEAK: f64 = 2.5;
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)
}
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
}
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();
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;
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);
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);
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:#?}");
}