Skip to main content

itzma_core/
lib.rs

1//! Itzma core: object-storage-backed vector retrieval.
2//!
3//! Vectors live as plain objects in a bucket. There is no server in the
4//! middle: any process with access to the bucket can write, and any process
5//! can query. Correctness comes from two primitives the object store already
6//! provides, put-if-absent and conditional update.
7//!
8//! # Where to start
9//!
10//! [`Namespace`] is the public API. Create one, `upsert` documents, `query`
11//! for nearest neighbors:
12//!
13//! ```
14//! # #[tokio::main]
15//! # async fn main() -> itzma_core::Result<()> {
16//! use std::sync::Arc;
17//!
18//! use itzma_core::{Document, Metric, Namespace, Schema};
19//! use object_store::memory::InMemory;
20//!
21//! let store = Arc::new(InMemory::new());
22//! let schema = Schema::new(2, Metric::L2);
23//! let ns = Namespace::create(store, "docs", schema).await?;
24//!
25//! ns.upsert(vec![Document { id: "a".into(), vector: vec![1.0, 0.0], attrs: None, sparse: None }]).await?;
26//! let hits = ns.query(&[0.0, 0.0], 5).await?;
27//! assert_eq!(hits[0].id, "a");
28//! # Ok(())
29//! # }
30//! ```
31//!
32//! Any `Arc<dyn object_store::ObjectStore>` works as the backend: in-memory
33//! for tests, local disk, or S3, GCS and Azure. Note that `LocalFileSystem`
34//! does not implement conditional update, which [`manifest::update`],
35//! [`manifest::update_if`] and so [`Namespace::compact`] and
36//! [`Namespace::upgrade_wal_format`] and [`Namespace::upgrade_segment_format`] need.
37//!
38//! # Modules
39//!
40//! | Module | Job |
41//! |---|---|
42//! | [`namespace`] | The [`Namespace`] handle: create, open, upsert, delete (each also keyed), query, query_sparse, filter, index, index_sparse, compact, gc, maintain, recover |
43//! | [`document`] | [`Document`], [`WalOp`], [`Schema`], [`Metric`] |
44//! | [`attrs`] | [`AttrSchema`], [`AttrType`]: the typed attribute fields a namespace declares |
45//! | [`predicate`] | [`Predicate`]: a typed condition over attributes |
46//! | [`filter`] | [`FilterOptions`], [`FilterPage`], [`Row`] and the run behind [`Namespace::filter`] |
47//! | [`wal`] | Sequenced write-ahead log: [`wal::append`], [`wal::append_keyed`], [`wal::read_log`] |
48//! | [`manifest`] | The namespace manifest and its compare-and-swap update |
49//! | [`schema_object`] | `schema.json`, the schema written once at create |
50//! | [`segment`] | Segment binary codecs (versions 2 and 3), ids, and the manifest invariant check |
51//! | [`layer`] | [`layer::Layer`]: the net effect of applying operations in order |
52//! | [`compaction`] | [`Compaction`], [`CompactionOptions`] and the run behind [`Namespace::compact`] |
53//! | [`gc`] | [`GcOptions`], [`GcReport`] and the run behind [`Namespace::gc`] |
54//! | [`indexer`] | [`IndexOptions`], [`IndexReport`] and the run behind [`Namespace::index`] |
55//! | [`sparse`] | [`SparseVector`] storage beside a segment: `sparse.bin` |
56//! | [`sparse_indexer`] | [`IndexSparseOptions`], [`IndexSparseReport`] and the run behind [`Namespace::index_sparse`] |
57//! | [`maintain`] | [`MaintenanceOptions`] and the run behind [`Namespace::maintain`] |
58//! | [`columns`] | [`DocColumns`]: a batch of upserts held as columns, for Arrow input |
59//! | [`inspect`] | [`inspect::report`]: a read-only look at what a namespace holds and what looks wrong |
60//! | [`search`] | Distance metrics and the flat top-k scan |
61//! | [`error`] | [`ItzmaError`] and [`Result`] |
62//!
63//! A query or a compaction run reads at most a byte budget, [`DEFAULT_READ_BUDGET`] unless set
64//! with [`Namespace::with_read_budget`], and stops with [`ItzmaError::ReadBudgetExceeded`] past
65//! it.
66//!
67//! `wal`, `manifest`, `layer`, `segment` and `compaction` are public so
68//! integration tests can drive them directly. Application code should stay on
69//! [`Namespace`].
70//!
71//! # On-disk layout
72//!
73//! ```text
74//! <namespace>/
75//!   schema.json                    dimension, metric and attribute types, written once, never changed
76//!   gc/fenced-through              how far the WAL fences reach, a hint for `gc` (only with fence_wal)
77//!   manifest/current.json          schema, live segments, WAL fold point
78//!   wal/00000000000000000001.json  one object per write batch (binary, see below)
79//!   wal/00000000000000000002.json
80//!   segments/<lo>-<hi>/data.bin    compacted data, named by the WAL range it covers
81//!   segments/<lo>-<hi>/index-<n>.bin an index of that segment, generation n, once `index` built one
82//!   segments/<lo>-<hi>/sparse.bin  the segment's sparse vectors, only if a document has one
83//!   segments/<lo>-<hi>/sparse-idx-<n>.bin its sparse inverted index, once `index_sparse` built one
84//! ```
85//!
86//! The manifest is JSON. WAL objects and segments are binary, and a WAL object
87//! is ZSTD-compressed when that makes it smaller. The WAL key keeps
88//! its `.json` suffix on purpose: every writer has to try the same key for the
89//! same sequence number, or put-if-absent stops deciding the race. A write that carries an
90//! idempotency key ([`WriteKey`]) is version 3, the same object with the key in
91//! the header. A batch with a sparse vector is version 4, or 5 with a key.
92//!
93//! Nothing in the layout is ever overwritten but the manifest, and the WAL
94//! objects that [`Namespace::gc`] is asked to fence. GC deletes segments that a
95//! merge or a later fold superseded, and with
96//! [`GcOptions::fence_wal`] replaces folded WAL objects with 8-byte fences that
97//! keep put-if-absent working at their keys. Nothing else is removed. The
98//! schema is kept in the manifest and again in `schema.json`, which is
99//! written once, so losing the manifest does not lose it.
100//! [`Namespace::recover`] then writes a new manifest from the schema object, the
101//! segment names and the WAL listing.
102//! [`Namespace::maintain`] is the call to schedule: it compacts when the WAL tail
103//! is long enough and then collects.
104//!
105//! Every object carries a `format_version` so the encoding can change later. A
106//! reader that meets a version it does not know fails with
107//! [`ItzmaError::UnsupportedFormat`] instead of guessing. The manifest also
108//! records the newest WAL format the namespace may contain, and a build that
109//! reads an older one refuses the namespace with
110//! [`ItzmaError::WalFormatTooNew`] before it touches the WAL.
111//! [`Namespace::upgrade_wal_format`] raises that level, one way. A second level,
112//! `segment_format`, does the same for segments: a build that reads an older
113//! segment format is refused with [`ItzmaError::SegmentFormatTooNew`], and
114//! [`Namespace::upgrade_segment_format`] raises it. Compaction writes
115//! the segment version that level allows.
116#![cfg_attr(not(test), deny(clippy::unwrap_used))]
117#![warn(missing_docs)]
118
119// The crate README, which crates.io shows, runs as a doctest so its example
120// can't drift from the API.
121#[cfg(doctest)]
122#[doc = include_str!("../README.md")]
123pub struct ReadmeDoctest;
124
125pub mod attrs;
126mod bloom;
127mod bound;
128mod budget;
129mod cache;
130mod columnar;
131pub mod columns;
132pub mod compaction;
133mod cpu;
134mod decoded;
135pub mod document;
136pub mod error;
137mod fetch;
138pub mod filter;
139pub mod gc;
140mod index;
141pub mod indexer;
142pub mod inspect;
143mod kernels;
144pub mod layer;
145pub mod maintain;
146pub mod manifest;
147pub mod namespace;
148pub mod predicate;
149pub mod quant;
150mod query;
151pub mod recover;
152mod scan;
153pub mod schema_object;
154pub mod search;
155pub mod segment;
156pub mod sparse;
157mod sparse_index;
158pub mod sparse_indexer;
159mod sparse_query;
160mod stream;
161mod view;
162pub mod wal;
163mod wal_codec;
164
165pub use attrs::{AttrSchema, AttrType};
166pub use budget::DEFAULT_READ_BUDGET;
167pub use cache::{CacheOptions, CacheStore, DEFAULT_RAM_MAX_BYTES, NvmeOptions};
168pub use columns::{AttrColumn, DocColumns, SparseColumn};
169pub use compaction::{Compaction, CompactionOptions};
170pub use cpu::{CpuThreads, configure_cpu};
171pub use decoded::{DEFAULT_DECODED_MAX_BYTES, DecodedCache, DecodedCacheOptions};
172pub use document::{Document, Metric, Schema, SparseVector, WalOp};
173pub use error::{ItzmaError, Result};
174pub use fetch::FetchPolicy;
175pub use filter::{FilterOptions, FilterPage, Row};
176pub use gc::{GcOptions, GcReport};
177pub use indexer::{IndexKind, IndexOptions, IndexReport};
178pub use maintain::{CompactTrigger, MaintenanceOptions, MaintenanceReport};
179pub use manifest::{IndexEntry, Manifest, SparseIndexEntry};
180pub use namespace::Namespace;
181pub use predicate::{AttrValue, Compare, Predicate, TextCompare};
182pub use query::{DEFAULT_RERANK, QueryOptions};
183pub use recover::RecoverReport;
184pub use search::Hit;
185pub use sparse_indexer::{IndexSparseOptions, IndexSparseReport};
186pub use sparse_query::SparseQueryOptions;
187pub use stream::{
188    DEFAULT_STREAM_DEPTH, DEFAULT_STREAM_TARGET_BYTES, StreamError, StreamOptions, StreamReport,
189};
190pub use wal::WriteKey;