weavatrix-search-vector 0.2.0

Persistent, mutable, bounded vector candidate search for Rust and Weavatrix
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use crate::metadata::{Metadata, MetadataFilter, MetadataIndex};
use crate::simd::DistanceKernel;
use crate::vector::inverse_norm;
use crate::{IndexConfig, SearchError, SearchHit, VectorIndex};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::sync::{Arc, RwLock};

/// Owned vector plus optional filter metadata.
#[derive(Debug, Clone, PartialEq)]
pub struct VectorRecord {
    pub key: u64,
    pub vector: Vec<f32>,
    pub metadata: Metadata,
}

impl VectorRecord {
    #[must_use]
    pub fn new(key: u64, vector: Vec<f32>) -> Self {
        Self {
            key,
            vector,
            metadata: Metadata::new(),
        }
    }
}

/// Result of an upsert operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MutationOutcome {
    Inserted,
    Updated,
}

/// Thread-safe mutable overlay over an immutable HNSW base.
///
/// Inserts and updates are searched exactly from a bounded delta. Deletions
/// are tombstones. [`Self::compact`] deterministically folds both into a new
/// immutable base without making readers observe a partial rebuild.
#[derive(Debug)]
pub struct MutableVectorIndex {
    config: IndexConfig,
    state: RwLock<MutableState>,
    distance_kernel: DistanceKernel,
}

#[derive(Debug)]
struct MutableState {
    base: Arc<VectorIndex>,
    pending: BTreeMap<u64, Vec<f32>>,
    deleted: BTreeSet<u64>,
    metadata: MetadataIndex,
    generation: u64,
}

impl MutableVectorIndex {
    /// Builds a mutable index and preserves supplied metadata.
    ///
    /// # Errors
    ///
    /// Returns typed config, vector, allocation, capacity, or duplicate-key
    /// errors.
    pub fn build(config: IndexConfig, records: &[VectorRecord]) -> Result<Self, SearchError> {
        let vectors = records
            .iter()
            .map(|record| (record.key, record.vector.as_slice()))
            .collect::<Vec<_>>();
        let base = Arc::new(VectorIndex::build(config.clone(), &vectors)?);
        let mut metadata = MetadataIndex::new();
        for record in records {
            if !record.metadata.is_empty() {
                metadata.insert(record.key, record.metadata.clone());
            }
        }
        Ok(Self {
            config,
            state: RwLock::new(MutableState {
                base,
                pending: BTreeMap::new(),
                deleted: BTreeSet::new(),
                metadata,
                generation: 0,
            }),
            distance_kernel: DistanceKernel::detect(),
        })
    }

    /// Wraps an existing immutable index with an empty mutable delta.
    #[must_use]
    pub fn from_index(index: VectorIndex) -> Self {
        let config = index.config().clone();
        Self {
            config,
            state: RwLock::new(MutableState {
                base: Arc::new(index),
                pending: BTreeMap::new(),
                deleted: BTreeSet::new(),
                metadata: MetadataIndex::new(),
                generation: 0,
            }),
            distance_kernel: DistanceKernel::detect(),
        }
    }

    /// Loads an immutable snapshot and opens an empty mutable delta.
    ///
    /// # Errors
    ///
    /// Returns typed snapshot or storage errors.
    pub fn load(path: impl AsRef<Path>) -> Result<Self, SearchError> {
        Ok(Self::from_index(VectorIndex::load(path)?))
    }

    #[must_use]
    pub const fn config(&self) -> &IndexConfig {
        &self.config
    }

    #[must_use]
    pub fn len(&self) -> usize {
        let state = self
            .state
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        current_len(&state)
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    #[must_use]
    pub fn delta_len(&self) -> usize {
        let state = self
            .state
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.pending.len().saturating_add(state.deleted.len())
    }

    #[must_use]
    pub fn should_compact(&self, maximum_delta: usize) -> bool {
        self.delta_len() >= maximum_delta
    }

    /// Inserts a new key.
    ///
    /// # Errors
    ///
    /// Returns [`SearchError::DuplicateKey`] when the live key already exists,
    /// or a typed vector validation error.
    pub fn insert(&self, key: u64, vector: &[f32], metadata: Metadata) -> Result<(), SearchError> {
        let normalized = normalize(self.config.dimensions, vector)?;
        let mut state = self
            .state
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if key_exists(&state, key) {
            return Err(SearchError::DuplicateKey(key));
        }
        state.deleted.remove(&key);
        state.pending.insert(key, normalized);
        if metadata.is_empty() {
            state.metadata.remove(key);
        } else {
            state.metadata.insert(key, metadata);
        }
        state.generation = state.generation.wrapping_add(1);
        Ok(())
    }

    /// Inserts or replaces one key without rebuilding the immutable base.
    ///
    /// # Errors
    ///
    /// Returns a typed vector validation error.
    pub fn upsert(
        &self,
        key: u64,
        vector: &[f32],
        metadata: Metadata,
    ) -> Result<MutationOutcome, SearchError> {
        let normalized = normalize(self.config.dimensions, vector)?;
        let mut state = self
            .state
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let outcome = if key_exists(&state, key) {
            MutationOutcome::Updated
        } else {
            MutationOutcome::Inserted
        };
        state.deleted.remove(&key);
        state.pending.insert(key, normalized);
        if metadata.is_empty() {
            state.metadata.remove(key);
        } else {
            state.metadata.insert(key, metadata);
        }
        state.generation = state.generation.wrapping_add(1);
        Ok(outcome)
    }

    /// Tombstones a live key. Returns whether a vector was removed.
    pub fn delete(&self, key: u64) -> bool {
        let mut state = self
            .state
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if !key_exists(&state, key) {
            return false;
        }
        state.pending.remove(&key);
        if state.base.vector(key).is_some() {
            state.deleted.insert(key);
        }
        state.metadata.remove(key);
        state.generation = state.generation.wrapping_add(1);
        true
    }

    /// Replaces metadata without changing the vector.
    ///
    /// # Errors
    ///
    /// Returns [`SearchError::MissingKey`] when `key` is not live.
    pub fn set_metadata(&self, key: u64, metadata: Metadata) -> Result<(), SearchError> {
        let mut state = self
            .state
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if !key_exists(&state, key) {
            return Err(SearchError::MissingKey(key));
        }
        if metadata.is_empty() {
            state.metadata.remove(key);
        } else {
            state.metadata.insert(key, metadata);
        }
        state.generation = state.generation.wrapping_add(1);
        Ok(())
    }

    #[must_use]
    pub fn metadata(&self, key: u64) -> Option<Metadata> {
        let state = self
            .state
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.metadata.get(key).cloned()
    }

    /// Searches the immutable base and exact delta, then deterministically
    /// merges equal keys.
    ///
    /// # Errors
    ///
    /// Returns a typed query or allocation error.
    pub fn search(&self, query: &[f32], count: usize) -> Result<Vec<SearchHit>, SearchError> {
        self.search_where(query, count, |_| true)
    }

    /// Searches only records matching `filter`.
    ///
    /// # Errors
    ///
    /// Returns a typed query or allocation error.
    pub fn search_filtered(
        &self,
        query: &[f32],
        count: usize,
        filter: &MetadataFilter,
    ) -> Result<Vec<SearchHit>, SearchError> {
        let state = self
            .state
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        self.search_locked(&state, query, count, |key| {
            state.metadata.matches(key, filter)
        })
    }

    /// Deterministically rebuilds the immutable base. Concurrent mutations are
    /// detected and retried without losing updates.
    ///
    /// # Errors
    ///
    /// Returns a build error or [`SearchError::MutationConflict`] after three
    /// conflicting rebuilds.
    pub fn compact(&self) -> Result<(), SearchError> {
        for _ in 0..3 {
            let (generation, base, pending, deleted) = {
                let state = self
                    .state
                    .read()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                (
                    state.generation,
                    Arc::clone(&state.base),
                    state.pending.clone(),
                    state.deleted.clone(),
                )
            };
            let mut owned = Vec::new();
            owned
                .try_reserve_exact(
                    base.len()
                        .saturating_sub(deleted.len())
                        .saturating_add(pending.len()),
                )
                .map_err(|_| SearchError::AllocationFailed)?;
            for key in base.keys() {
                if deleted.contains(&key) || pending.contains_key(&key) {
                    continue;
                }
                let vector = base.vector(key).ok_or(SearchError::MissingKey(key))?;
                owned.push((key, vector.to_vec()));
            }
            owned.extend(pending.iter().map(|(key, vector)| (*key, vector.clone())));
            owned.sort_unstable_by_key(|record| record.0);
            let borrowed = owned
                .iter()
                .map(|(key, vector)| (*key, vector.as_slice()))
                .collect::<Vec<_>>();
            let rebuilt = Arc::new(VectorIndex::build(self.config.clone(), &borrowed)?);
            let mut state = self
                .state
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if state.generation != generation {
                continue;
            }
            state.base = rebuilt;
            state.pending.clear();
            state.deleted.clear();
            return Ok(());
        }
        Err(SearchError::MutationConflict)
    }

    /// Compacts and saves a complete immutable snapshot.
    ///
    /// # Errors
    ///
    /// Returns a compaction or storage error.
    pub fn save(&self, path: impl AsRef<Path>) -> Result<(), SearchError> {
        self.compact()?;
        let state = self
            .state
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.base.save(path)
    }

    fn search_where<F>(
        &self,
        query: &[f32],
        count: usize,
        accepts: F,
    ) -> Result<Vec<SearchHit>, SearchError>
    where
        F: Fn(u64) -> bool,
    {
        let state = self
            .state
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        self.search_locked(&state, query, count, accepts)
    }

    fn search_locked<F>(
        &self,
        state: &MutableState,
        query: &[f32],
        count: usize,
        accepts: F,
    ) -> Result<Vec<SearchHit>, SearchError>
    where
        F: Fn(u64) -> bool,
    {
        if query.len() != self.config.dimensions {
            return Err(SearchError::DimensionMismatch {
                expected: self.config.dimensions,
                actual: query.len(),
                vector: None,
            });
        }
        let query_inverse_norm = inverse_norm(query, None)?;
        let live_count = current_len(state);
        let limit = count.min(live_count);
        if limit == 0 {
            return Ok(Vec::new());
        }
        let mut hits = state.base.search_filtered(query, limit, |key| {
            !state.deleted.contains(&key) && !state.pending.contains_key(&key) && accepts(key)
        })?;
        hits.try_reserve(state.pending.len())
            .map_err(|_| SearchError::AllocationFailed)?;
        hits.extend(
            state
                .pending
                .iter()
                .filter(|(key, _)| accepts(**key))
                .map(|(key, vector)| SearchHit {
                    key: *key,
                    distance: self.distance_kernel.cosine_distance(
                        vector,
                        query,
                        query_inverse_norm,
                    ),
                }),
        );
        hits.sort_unstable_by(|left, right| {
            left.distance
                .total_cmp(&right.distance)
                .then_with(|| left.key.cmp(&right.key))
        });
        hits.dedup_by_key(|hit| hit.key);
        hits.truncate(limit);
        Ok(hits)
    }
}

fn normalize(dimensions: usize, vector: &[f32]) -> Result<Vec<f32>, SearchError> {
    if vector.len() != dimensions {
        return Err(SearchError::DimensionMismatch {
            expected: dimensions,
            actual: vector.len(),
            vector: Some(0),
        });
    }
    let inverse = inverse_norm(vector, Some(0))?;
    let mut normalized = Vec::new();
    normalized
        .try_reserve_exact(dimensions)
        .map_err(|_| SearchError::AllocationFailed)?;
    normalized.extend(vector.iter().map(|value| value * inverse));
    Ok(normalized)
}

fn key_exists(state: &MutableState, key: u64) -> bool {
    state.pending.contains_key(&key)
        || (!state.deleted.contains(&key) && state.base.vector(key).is_some())
}

fn current_len(state: &MutableState) -> usize {
    let retained_base = state
        .base
        .len()
        .saturating_sub(state.deleted.len())
        .saturating_sub(
            state
                .pending
                .keys()
                .filter(|key| state.base.vector(**key).is_some())
                .count(),
        );
    retained_base.saturating_add(state.pending.len())
}