itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! What one scan saves over paging `filter`, counted at the object store.
//!
//! ```text
//! cargo run --release --example scan -- <dir> [--out <file>]
//! ```
//!
//! `<dir>` is the `public-scan` synthetic dataset (`make synthetic
//! ONLY=public-scan SIZE=full`): `schema.json`, `rows.jsonl` and
//! `queries.json`, each query with the count the generator worked out without
//! reading anything. Each query is read twice from the same compacted
//! namespace: once by paging `filter` (the default page of 100 rows) and once
//! by one `scan`. The ids must be the same, in the same order, and equal the
//! expected count. Then the namespace is cut with `scan_splits` into four
//! ranges, each scanned on its own, and together they must return every row
//! once. The requests and bytes read go to `--out` (default
//! `<dir>/demo-results.json`) for the charts. The exit code is 1 when a check
//! fails.

use std::fmt;
use std::path::Path;
use std::process::ExitCode;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

use async_trait::async_trait;
use futures::TryStreamExt;
use futures::stream::BoxStream;
use itzma_core::compaction::DEFAULT_MAX_SEGMENT_BYTES;
use itzma_core::scan::{Columns, ScanOptions};
use itzma_core::{
    AttrSchema, CompactionOptions, Document, FetchPolicy, FilterOptions, ItzmaError, Metric,
    Namespace, Predicate, Schema,
};
use object_store::memory::InMemory;
use object_store::path::Path as StorePath;
use object_store::{
    CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore,
    PutMultipartOptions, PutOptions, PutPayload, PutResult,
};
use serde_json::{Value, json};

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

/// An `InMemory` store that counts every `get` and the bytes it returns.
#[derive(Debug, Default)]
struct CountingStore {
    inner: InMemory,
    requests: AtomicUsize,
    bytes: AtomicU64,
}

impl CountingStore {
    fn reset(&self) {
        self.requests.store(0, Ordering::SeqCst);
        self.bytes.store(0, Ordering::SeqCst);
    }

    fn requests(&self) -> usize {
        self.requests.load(Ordering::SeqCst)
    }

    fn bytes(&self) -> u64 {
        self.bytes.load(Ordering::SeqCst)
    }
}

impl fmt::Display for CountingStore {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "CountingStore")
    }
}

#[async_trait]
impl ObjectStore for CountingStore {
    async fn put_opts(
        &self,
        location: &StorePath,
        payload: PutPayload,
        opts: PutOptions,
    ) -> object_store::Result<PutResult> {
        self.inner.put_opts(location, payload, opts).await
    }

    async fn put_multipart_opts(
        &self,
        location: &StorePath,
        opts: PutMultipartOptions,
    ) -> object_store::Result<Box<dyn MultipartUpload>> {
        self.inner.put_multipart_opts(location, opts).await
    }

    async fn get_opts(
        &self,
        location: &StorePath,
        options: GetOptions,
    ) -> object_store::Result<GetResult> {
        let got = self.inner.get_opts(location, options).await?;
        self.requests.fetch_add(1, Ordering::SeqCst);
        self.bytes
            .fetch_add(got.range.end - got.range.start, Ordering::SeqCst);
        Ok(got)
    }

    fn delete_stream(
        &self,
        locations: BoxStream<'static, object_store::Result<StorePath>>,
    ) -> BoxStream<'static, object_store::Result<StorePath>> {
        self.inner.delete_stream(locations)
    }

    fn list(
        &self,
        prefix: Option<&StorePath>,
    ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {
        self.inner.list(prefix)
    }

    async fn list_with_delimiter(
        &self,
        prefix: Option<&StorePath>,
    ) -> object_store::Result<ListResult> {
        self.inner.list_with_delimiter(prefix).await
    }

    async fn copy_opts(
        &self,
        from: &StorePath,
        to: &StorePath,
        options: CopyOptions,
    ) -> object_store::Result<()> {
        self.inner.copy_opts(from, to, options).await
    }
}

/// What one read cost, paged and scanned.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cost {
    pub name: String,
    pub expected: usize,
    pub pages: usize,
    pub requests_paged: usize,
    pub bytes_paged: u64,
    pub requests_scanned: usize,
    pub bytes_scanned: u64,
}

/// Everything one run found.
#[derive(Debug, Default)]
pub struct Findings {
    pub costs: Vec<Cost>,
    /// Every read returned the expected count, paged and scanned.
    pub counts_match: bool,
    /// The paged and the scanned read returned the same ids in the same order.
    pub answers_agree: bool,
    /// The ranges from `scan_splits` returned every row once between them.
    pub ranges_cover: bool,
    pub ranges: usize,
}

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

    /// The charts' data: what ran, on what, and what each read cost.
    pub fn results(&self, size: &str, rows: usize) -> Value {
        json!({
            "functionality": "public-scan",
            "version": env!("CARGO_PKG_VERSION"),
            "dataset": "public-scan",
            "size": size,
            "rows": rows,
            "filter_limit": FilterOptions::default().limit,
            "ranges": self.ranges,
            "results": self.costs.iter().map(|c| json!({
                "name": c.name,
                "expected": c.expected,
                "pages": c.pages,
                "paged": {"requests": c.requests_paged, "bytes": c.bytes_paged},
                "scanned": {"requests": c.requests_scanned, "bytes": c.bytes_scanned},
            })).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()
}

/// A compacted namespace over a counting store.
async fn build(
    docs: &[Document],
    attrs: &AttrSchema,
) -> Result<(Namespace, Arc<CountingStore>), ItzmaError> {
    let store = Arc::new(CountingStore::default());
    let schema = Schema::new(DIM, Metric::L2).with_attrs(attrs.clone());
    let ns = Namespace::create(store.clone() as Arc<dyn ObjectStore>, "scan-demo", schema)
        .await?
        .with_fetch_policy(FetchPolicy::local());
    for chunk in docs.chunks(BATCH) {
        ns.upsert(chunk.to_vec()).await?;
    }
    ns.compact(&COMPACT).await?;
    Ok((ns, store))
}

/// Every id the filter matches, in id order, the pages it took and what
/// reading them cost.
async fn paged(
    ns: &Namespace,
    store: &CountingStore,
    predicate: &Predicate,
) -> Result<(Vec<String>, usize, usize, u64), ItzmaError> {
    store.reset();
    let mut ids = Vec::new();
    let mut pages = 0;
    let mut after = None;
    loop {
        let mut options = FilterOptions::default();
        options.after = after;
        let page = ns.filter(predicate, &options).await?;
        pages += 1;
        ids.extend(page.rows.into_iter().map(|row| row.id));
        match page.next {
            Some(next) => after = Some(next),
            None => break,
        }
    }
    Ok((ids, pages, store.requests(), store.bytes()))
}

/// The ids and attributes a scan hands out, like a filter's rows: no vectors.
fn columns() -> Columns {
    Columns::default().vectors(false).sparse(false)
}

/// Every id one scan returns, in order, and what reading them cost.
async fn scanned(
    ns: &Namespace,
    store: &CountingStore,
    predicate: &Predicate,
) -> Result<(Vec<String>, usize, u64), ItzmaError> {
    store.reset();
    let options = ScanOptions::default()
        .filter(predicate.clone())
        .columns(columns());
    let batches: Vec<_> = ns.scan(options)?.try_collect().await?;
    let ids = batches.into_iter().flat_map(|batch| batch.ids).collect();
    Ok((ids, store.requests(), store.bytes()))
}

/// The ids of every range from `scan_splits`, scanned one after the other and
/// joined, and how many ranges there were.
async fn by_ranges(ns: &Namespace) -> Result<(Vec<String>, usize), ItzmaError> {
    let ranges = ns.scan_splits(SPLITS).await?;
    let mut ids = Vec::new();
    for range in &ranges {
        let options = ScanOptions::default()
            .range(range)
            .columns(Columns::ids_only());
        let batches: Vec<_> = ns.scan(options)?.try_collect().await?;
        ids.extend(batches.into_iter().flat_map(|batch| batch.ids));
    }
    Ok((ids, ranges.len()))
}

/// Build the rows once and run every query both ways.
pub async fn run(
    schema: &Value,
    rows: &str,
    queries: &Value,
) -> Result<Findings, Box<dyn std::error::Error>> {
    let attrs: AttrSchema = serde_json::from_value(schema.clone())?;
    let docs = documents(rows)?;
    let (ns, store) = build(&docs, &attrs).await?;
    let mut found = Findings {
        counts_match: true,
        answers_agree: true,
        ..Findings::default()
    };
    for entry in queries.as_array().into_iter().flatten() {
        let predicate: Predicate = serde_json::from_value(entry["predicate"].clone())?;
        let expected = entry["expected"].as_u64().unwrap_or_default() as usize;
        let (by_page, pages, requests_paged, bytes_paged) = paged(&ns, &store, &predicate).await?;
        let (by_scan, requests_scanned, bytes_scanned) = scanned(&ns, &store, &predicate).await?;
        found.counts_match &= by_page.len() == expected && by_scan.len() == expected;
        found.answers_agree &= by_page == by_scan;
        found.costs.push(Cost {
            name: entry["name"].as_str().unwrap_or_default().to_string(),
            expected,
            pages,
            requests_paged,
            bytes_paged,
            requests_scanned,
            bytes_scanned,
        });
    }
    let (joined, ranges) = by_ranges(&ns).await?;
    let mut everything: Vec<String> = docs.iter().map(|d| d.id.clone()).collect();
    everything.sort();
    found.ranges = ranges;
    found.ranges_cover = joined == everything;
    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: scan <dir> [--out <file>]");
            return ExitCode::from(2);
        }
    };
    let read = || -> 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("queries.json"))?,
            read_json(&dir.join("meta.json"))?,
        ))
    };
    let (schema, rows, queries, meta) = match read() {
        Ok(data) => data,
        Err(error) => {
            eprintln!(
                "{}: {error}; run: make synthetic ONLY=public-scan SIZE=full",
                dir.display()
            );
            return ExitCode::from(2);
        }
    };
    match run(&schema, &rows, &queries).await {
        Ok(found) => {
            for c in &found.costs {
                println!(
                    "{:<10} paged: {:>5} requests {:>10} bytes in {:>4} pages   scanned: {:>5} requests {:>10} bytes",
                    c.name,
                    c.requests_paged,
                    c.bytes_paged,
                    c.pages,
                    c.requests_scanned,
                    c.bytes_scanned
                );
            }
            println!("counts_match: {}", found.counts_match);
            println!("answers_agree: {}", found.answers_agree);
            println!(
                "ranges_cover: {} ({} ranges)",
                found.ranges_cover, found.ranges
            );
            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!("scan: {error}");
            ExitCode::from(1)
        }
    }
}

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

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

    #[tokio::test]
    async fn a_scan_returns_what_paging_returns_in_fewer_requests() {
        let schema = json!({"n": "number", "group": "string"});
        let queries = json!([{
            "name": "all", "expected": 1500,
            "predicate": {"Number": {"field": "n", "op": "Ge", "value": 0}},
        }]);
        let found = run(&schema, &rows(1500), &queries).await.unwrap();
        assert!(found.passed(), "{found:#?}");
        let cost = &found.costs[0];
        // A full last page still hands back a cursor, so there can be one more.
        assert!((15..=16).contains(&cost.pages), "{cost:?}");
        assert!(cost.requests_scanned < cost.requests_paged, "{cost:?}");
        let results = found.results("small", 1500);
        assert_eq!(results["functionality"], "public-scan");
        assert_eq!(
            results["results"][0]["paged"]["requests"],
            cost.requests_paged
        );
    }
}