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