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//! | [`attr_indexer`] | [`IndexAttrsOptions`], [`IndexAttrsReport`] and the run behind [`Namespace::index_attrs`] |
57//! | [`sparse_indexer`] | [`IndexSparseOptions`], [`IndexSparseReport`] and the run behind [`Namespace::index_sparse`] |
58//! | [`maintain`] | [`MaintenanceOptions`] and the run behind [`Namespace::maintain`] |
59//! | [`columns`] | [`DocColumns`]: a batch of upserts held as columns, for Arrow input |
60//! | [`lease`] | [`MaintenanceLease`]: which process maintains a namespace |
61//! | [`inspect`] | [`inspect::report`]: a read-only look at what a namespace holds and what looks wrong |
62//! | [`search`] | Distance metrics and the flat top-k scan |
63//! | [`error`] | [`ItzmaError`] and [`Result`] |
64//!
65//! A query or a compaction run reads at most a byte budget, [`DEFAULT_READ_BUDGET`] unless set
66//! with [`Namespace::with_read_budget`], and stops with [`ItzmaError::ReadBudgetExceeded`] past
67//! it.
68//!
69//! `wal`, `manifest`, `layer`, `segment` and `compaction` are public so
70//! integration tests can drive them directly. Application code should stay on
71//! [`Namespace`].
72//!
73//! # On-disk layout
74//!
75//! ```text
76//! <namespace>/
77//!   schema.json                    dimension, metric and attribute types, written once, never changed
78//!   maintenance/lease.json         which process maintains the namespace, written by a loop's lease
79//!   gc/fenced-through              how far the WAL fences reach, a hint for `gc` (only with fence_wal)
80//!   manifest/current.json          schema, live segments, WAL fold point
81//!   wal/00000000000000000001.json  one object per write batch (binary, see below)
82//!   wal/00000000000000000002.json
83//!   segments/<lo>-<hi>/data.bin    compacted data, named by the WAL range it covers
84//!   segments/<lo>-<hi>/index-<n>.bin an index of that segment, generation n, once `index` built one
85//!   segments/<lo>-<hi>/sparse.bin  the segment's sparse vectors, only if a document has one
86//!   segments/<lo>-<hi>/sparse-idx-<n>.bin its sparse inverted index, once `index_sparse` built one
87//! ```
88//!
89//! The manifest is JSON. WAL objects and segments are binary, and a WAL object
90//! is ZSTD-compressed when that makes it smaller. The WAL key keeps
91//! its `.json` suffix on purpose: every writer has to try the same key for the
92//! same sequence number, or put-if-absent stops deciding the race. A write that carries an
93//! idempotency key ([`WriteKey`]) is version 3, the same object with the key in
94//! the header. A batch with a sparse vector is version 4, or 5 with a key.
95//!
96//! Nothing in the layout is ever overwritten but the manifest, and the WAL
97//! objects that [`Namespace::gc`] is asked to fence. GC deletes segments that a
98//! merge or a later fold superseded, and with
99//! [`GcOptions::fence_wal`] replaces folded WAL objects with 8-byte fences that
100//! keep put-if-absent working at their keys. Nothing else is removed. The
101//! schema is kept in the manifest and again in `schema.json`, which is
102//! written once, so losing the manifest does not lose it.
103//! [`Namespace::recover`] then writes a new manifest from the schema object, the
104//! segment names and the WAL listing.
105//! [`Namespace::maintain`] is the call to schedule: it compacts when the WAL tail
106//! is long enough and then collects.
107//!
108//! Every object carries a `format_version` so the encoding can change later. A
109//! reader that meets a version it does not know fails with
110//! [`ItzmaError::UnsupportedFormat`] instead of guessing. The manifest also
111//! records the newest WAL format the namespace may contain, and a build that
112//! reads an older one refuses the namespace with
113//! [`ItzmaError::WalFormatTooNew`] before it touches the WAL.
114//! [`Namespace::upgrade_wal_format`] raises that level, one way. A second level,
115//! `segment_format`, does the same for segments: a build that reads an older
116//! segment format is refused with [`ItzmaError::SegmentFormatTooNew`], and
117//! [`Namespace::upgrade_segment_format`] raises it. Compaction writes
118//! the segment version that level allows.
119#![cfg_attr(not(test), deny(clippy::unwrap_used))]
120#![warn(missing_docs)]
121
122// The crate README, which crates.io shows, runs as a doctest so its example
123// can't drift from the API.
124#[cfg(doctest)]
125#[doc = include_str!("../README.md")]
126pub struct ReadmeDoctest;
127
128// The repository README's Rust examples run too.
129#[cfg(doctest)]
130#[doc = include_str!("../../../README.md")]
131pub struct RootReadmeDoctest;
132
133mod attr_index;
134pub mod attr_indexer;
135pub mod attrs;
136mod bloom;
137mod bound;
138mod budget;
139mod cache;
140mod columnar;
141pub mod columns;
142pub mod compaction;
143mod cpu;
144mod decoded;
145pub mod document;
146pub mod error;
147mod fetch;
148pub mod filter;
149mod gate;
150pub mod gc;
151mod index;
152pub mod indexer;
153pub mod inspect;
154mod kernels;
155pub mod layer;
156pub mod lease;
157pub mod maintain;
158pub mod manifest;
159pub mod namespace;
160pub mod predicate;
161mod put;
162pub mod quant;
163mod query;
164pub mod recover;
165pub mod scan;
166pub mod schema_object;
167pub mod search;
168pub mod segment;
169pub mod sparse;
170mod sparse_index;
171pub mod sparse_indexer;
172mod sparse_query;
173mod stream;
174mod view;
175pub mod wal;
176mod wal_codec;
177
178pub use attr_indexer::{IndexAttrsOptions, IndexAttrsReport};
179pub use attrs::{AttrSchema, AttrType};
180pub use budget::DEFAULT_READ_BUDGET;
181pub use cache::{CacheOptions, CacheStore, DEFAULT_RAM_MAX_BYTES, NvmeOptions};
182pub use columns::{AttrColumn, DocColumns, SparseColumn};
183pub use compaction::{Compaction, CompactionOptions};
184pub use cpu::{CpuThreads, configure_cpu};
185pub use decoded::{DEFAULT_DECODED_MAX_BYTES, DecodedCache, DecodedCacheOptions};
186pub use document::{Document, Metric, Schema, SparseVector, WalOp};
187pub use error::{ItzmaError, Result};
188pub use fetch::FetchPolicy;
189pub use filter::{FilterOptions, FilterPage, Row};
190pub use gate::{DEFAULT_GATE_MAX_BYTES, DEFAULT_GATE_MAX_REQUESTS, GateOptions, GatedStore};
191pub use gc::{GcOptions, GcReport};
192pub use indexer::{IndexKind, IndexOptions, IndexReport};
193pub use lease::{DEFAULT_LEASE_RENEW, DEFAULT_LEASE_TTL, LeaseOptions, MaintenanceLease, Role};
194pub use maintain::{CompactTrigger, MaintenanceOptions, MaintenanceReport};
195pub use manifest::{AttrIndexEntry, IndexEntry, Manifest, SparseIndexEntry};
196pub use namespace::Namespace;
197pub use predicate::{AttrValue, Compare, Predicate, TextCompare};
198pub use put::{
199    DEFAULT_FALLBACK_MAX, DEFAULT_PART_SIZE, DEFAULT_STREAM_ABOVE, DEFAULT_UPLOAD_CONCURRENCY,
200    MIN_PART_SIZE, UploadOptions,
201};
202pub use query::{DEFAULT_RERANK, QueryOptions};
203pub use recover::RecoverReport;
204pub use search::Hit;
205pub use segment::Matrix;
206pub use sparse_indexer::{IndexSparseOptions, IndexSparseReport};
207pub use sparse_query::SparseQueryOptions;
208pub use stream::{
209    DEFAULT_STREAM_DEPTH, DEFAULT_STREAM_TARGET_BYTES, StreamError, StreamOptions, StreamReport,
210};
211pub use wal::WriteKey;