troupekit_index/lib.rs
1//! Vector index contract for Troupekit: exact brute force and HNSW.
2//! Sync and pure: no I/O, no async. A store persists the vectors and the
3//! opaque pages an index emits, and hands both back on open.
4
5#![doc(
6 html_logo_url = "https://raw.githubusercontent.com/ChaoticQubit/troupekit/main/assets/brand/logo-mark.svg",
7 html_favicon_url = "https://raw.githubusercontent.com/ChaoticQubit/troupekit/main/assets/brand/favicon.svg"
8)]
9
10mod brute;
11mod hnsw;
12mod page;
13mod quant;
14mod rng;
15
16use std::fmt;
17
18pub use brute::BruteForce;
19pub use hnsw::Hnsw;
20
21/// Largest vector dimension an index accepts.
22/// Larger values are refused by `new_index` and by inserts.
23/// Bounds memory per vector and the cost of one score.
24pub const MAX_DIMS: usize = 65_536;
25
26/// Largest `k` a search accepts.
27/// Larger values are refused with `IndexError::Invalid`.
28/// Bounds the result heap and the HNSW beam width.
29pub const MAX_K: usize = 1_000;
30
31/// One search result: an id and its cosine similarity to the query.
32/// Higher scores are closer. Results come sorted by score descending,
33/// ties broken by the lower id.
34#[non_exhaustive]
35#[derive(Debug, Clone, Copy, PartialEq)]
36pub struct Neighbor {
37 pub id: u64,
38 pub score: f32,
39}
40
41impl Neighbor {
42 /// Builds a result entry from an id and its cosine score.
43 /// Input: any id and score. Output: the neighbour.
44 /// Callers outside the crate use this, since the struct may grow.
45 pub fn new(id: u64, score: f32) -> Self {
46 Self { id, score }
47 }
48}
49
50/// Key of one persisted page.
51/// `Header` holds graph-wide state, `Node` the links of one id.
52/// Brute force emits no pages.
53#[non_exhaustive]
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
55pub enum PageKey {
56 Header,
57 Node(u64),
58}
59
60/// One page change since the last `take_changes` call.
61/// `Put` writes or replaces the bytes of a key, `Delete` removes it.
62/// The bytes are opaque to the store and untrusted on restore.
63#[non_exhaustive]
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub enum PageChange {
66 Put(PageKey, Vec<u8>),
67 Delete(PageKey),
68}
69
70/// In-memory format of stored vectors. Queries stay f32.
71/// `F32` is exact, `F16` halves memory, `I8` quarters it with one
72/// f32 scale per vector. Default `F32`.
73#[non_exhaustive]
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
75pub enum Quantization {
76 #[default]
77 F32,
78 F16,
79 I8,
80}
81
82/// Build and search settings of an HNSW index.
83/// Fields are private; start from `Default` and use the `with_*` setters.
84/// `new_index` validates the values.
85#[non_exhaustive]
86#[derive(Debug, Clone, PartialEq)]
87pub struct HnswParams {
88 m: usize,
89 ef_construction: usize,
90 ef_search: usize,
91 seed: u64,
92 max_deleted_fraction: f32,
93}
94
95impl Default for HnswParams {
96 fn default() -> Self {
97 Self { m: 16, ef_construction: 200, ef_search: 64, seed: 0x5452_4B54, max_deleted_fraction: 0.25 }
98 }
99}
100
101impl HnswParams {
102 /// Sets the link count per node on upper layers; layer 0 keeps `2*m`.
103 /// Input: `m`, valid in `2..=128`. Output: the updated params.
104 /// Checked by `new_index`.
105 pub fn with_m(mut self, m: usize) -> Self {
106 self.m = m;
107 self
108 }
109
110 /// Sets the beam width used while inserting.
111 /// Input: `ef`, valid in `1..=MAX_K * 4`. Output: the updated params.
112 /// Checked by `new_index`.
113 pub fn with_ef_construction(mut self, ef: usize) -> Self {
114 self.ef_construction = ef;
115 self
116 }
117
118 /// Sets the beam width used while searching; raised to `k` per query.
119 /// Input: `ef`, valid in `1..=MAX_K * 4`. Output: the updated params.
120 /// Checked by `new_index`.
121 pub fn with_ef_search(mut self, ef: usize) -> Self {
122 self.ef_search = ef;
123 self
124 }
125
126 /// Sets the seed of the level generator, so builds are reproducible.
127 /// Input: any `u64`. Output: the updated params.
128 /// A zero seed is replaced by a fixed non-zero one internally.
129 pub fn with_seed(mut self, seed: u64) -> Self {
130 self.seed = seed;
131 self
132 }
133
134 /// Sets the share of removals since the last build that triggers a
135 /// rebuild, as a fraction of the node count. Input: `(0.0, 1.0]`.
136 /// Output: the updated params. Checked by `new_index`.
137 pub fn with_max_deleted_fraction(mut self, fraction: f32) -> Self {
138 self.max_deleted_fraction = fraction;
139 self
140 }
141
142 /// Returns the link count per node on upper layers.
143 /// Layer 0 allows twice this many.
144 /// Default 16.
145 pub fn m(&self) -> usize {
146 self.m
147 }
148
149 /// Returns the beam width used while inserting.
150 /// Higher builds a better graph more slowly.
151 /// Default 200.
152 pub fn ef_construction(&self) -> usize {
153 self.ef_construction
154 }
155
156 /// Returns the beam width used while searching.
157 /// A query with a larger `k` widens it to `k`.
158 /// Default 64.
159 pub fn ef_search(&self) -> usize {
160 self.ef_search
161 }
162
163 /// Returns the seed of the level generator.
164 /// The same seed and insert order give the same graph.
165 /// Default `0x5452_4B54`.
166 pub fn seed(&self) -> u64 {
167 self.seed
168 }
169
170 /// Returns the share of removals since the last build that triggers
171 /// a rebuild. Each removal repairs links locally; a rebuild restores
172 /// full graph quality. Default 0.25.
173 pub fn max_deleted_fraction(&self) -> f32 {
174 self.max_deleted_fraction
175 }
176}
177
178/// Which index to build. Default `BruteForce`, which is exact.
179/// `Hnsw` is approximate and faster on large sets.
180/// Passed to `new_index`.
181#[non_exhaustive]
182#[derive(Debug, Clone, PartialEq, Default)]
183pub enum IndexKind {
184 #[default]
185 BruteForce,
186 Hnsw(HnswParams),
187}
188
189/// Failure of an index call. Caller input gets an error, never a panic.
190/// `CorruptPage` means persisted pages were refused; the store then
191/// rebuilds from vectors.
192#[non_exhaustive]
193#[derive(Debug, Clone, PartialEq, thiserror::Error)]
194pub enum IndexError {
195 #[error("dimension mismatch: expected {expected}, got {actual}")]
196 DimensionMismatch { expected: usize, actual: usize },
197 #[error("invalid input: {0}")]
198 Invalid(String),
199 #[error("corrupt page: {0}")]
200 CorruptPage(String),
201 #[error("unsupported: {0}")]
202 Unsupported(&'static str),
203}
204
205/// A vector index over `u64` ids with one fixed dimension.
206/// Search uses cosine similarity, higher is closer, ties by lower id,
207/// at most `k` results, only ids where `allow` returns true.
208pub trait VectorIndex: Send + Sync {
209 /// Returns the fixed dimension of every vector and query.
210 /// Set once by `new_index` and never changed.
211 /// Inserts and searches of another length are refused.
212 fn dims(&self) -> usize;
213
214 /// Returns the number of stored ids.
215 /// A replaced id counts once.
216 /// A removed id is gone at once and not counted.
217 fn len(&self) -> usize;
218
219 /// Returns true when no id is stored.
220 /// Same as `len() == 0`.
221 /// An index whose ids were all removed is empty.
222 fn is_empty(&self) -> bool {
223 self.len() == 0
224 }
225
226 /// Returns the bytes held by stored vectors and graph links.
227 /// Vectors count in their in-memory format: `4*dims`, `2*dims` or
228 /// `dims + 4` bytes each for f32, f16 and i8.
229 fn heap_bytes(&self) -> usize;
230
231 /// Inserts a vector under `id`, replacing any vector already there.
232 /// Input: an id and a vector of `dims` finite values.
233 /// Errors on a wrong dimension or a non-finite component.
234 fn insert(&mut self, id: u64, vector: &[f32]) -> Result<(), IndexError>;
235
236 /// Removes `id` and its vector from the index at once.
237 /// Input: any id. Output: true when the id was stored; an unknown or
238 /// already removed id returns false. Its page is deleted on the next drain.
239 fn remove(&mut self, id: u64) -> bool;
240
241 /// Returns at most `k` nearest live ids allowed by `allow`.
242 /// Sorted by score descending, ties by lower id.
243 /// Errors on a wrong dimension, a non-finite query or `k > MAX_K`.
244 fn search(&self, query: &[f32], k: usize, allow: Option<&dyn Fn(u64) -> bool>) -> Result<Vec<Neighbor>, IndexError>;
245
246 /// Drains the page changes made since the last call.
247 /// The store writes them in the same transaction as the vectors.
248 /// Pages hold links only, never a vector; brute force emits none.
249 fn take_changes(&mut self) -> Vec<PageChange>;
250
251 /// Loads vectors and persisted pages into an empty index.
252 /// Pages are untrusted: any inconsistency is `CorruptPage` and
253 /// leaves the index empty, so the store rebuilds from vectors.
254 fn restore(&mut self, vectors: &mut dyn Iterator<Item = (u64, Vec<f32>)>, pages: &mut dyn Iterator<Item = (PageKey, Vec<u8>)>) -> Result<(), IndexError>;
255}
256
257impl fmt::Debug for dyn VectorIndex {
258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259 f.debug_struct("VectorIndex").field("dims", &self.dims()).field("len", &self.len()).finish()
260 }
261}
262
263/// Builds an empty index of the given kind, dimension and format.
264/// Input: `dims` in `1..=MAX_DIMS` and, for HNSW, params in range.
265/// Output: the boxed index, or `Invalid` naming the bad setting.
266pub fn new_index(kind: &IndexKind, dims: usize, quant: Quantization) -> Result<Box<dyn VectorIndex>, IndexError> {
267 if dims == 0 || dims > MAX_DIMS {
268 return Err(IndexError::Invalid(format!("dims must be in 1..={MAX_DIMS}, got {dims}")));
269 }
270 match kind {
271 IndexKind::BruteForce => Ok(Box::new(BruteForce::new(dims, quant))),
272 IndexKind::Hnsw(params) => {
273 hnsw::validate_params(params)?;
274 Ok(Box::new(Hnsw::new(dims, quant, params.clone())))
275 }
276 }
277}
278
279/// Checks a vector or query against the index dimension.
280/// Input: the index `dims` and the caller's slice. Output: `Ok`, or
281/// `DimensionMismatch` for a wrong length and `Invalid` for NaN or inf.
282pub(crate) fn check_vector(dims: usize, v: &[f32]) -> Result<(), IndexError> {
283 if v.len() != dims {
284 return Err(IndexError::DimensionMismatch { expected: dims, actual: v.len() });
285 }
286 if let Some(i) = v.iter().position(|x| !x.is_finite()) {
287 return Err(IndexError::Invalid(format!("component {i} is not finite")));
288 }
289 Ok(())
290}
291
292/// Checks a search `k` against `MAX_K`.
293/// Input: the caller's `k`. Output: `Ok`, or `Invalid` above the bound.
294/// A `k` of zero is valid and returns no results.
295pub(crate) fn check_k(k: usize) -> Result<(), IndexError> {
296 if k > MAX_K {
297 return Err(IndexError::Invalid(format!("k must be at most {MAX_K}, got {k}")));
298 }
299 Ok(())
300}
301