airust 0.6.7

Rust-native knowledge and memory engine for AI agents and local LLM applications: lexical search, optional semantic retrieval, versioned memory, source-bound evidence and MCP
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
#![doc = include_str!("../docs/SEMANTIC.md")]

use crate::{
    index::validate_entry,
    ranking::{Ranked, TopK},
    Context, Engine, IndexError, KnowledgeEntry,
};
use std::{
    collections::{BTreeMap, BTreeSet},
    sync::{Arc, OnceLock},
};
use thiserror::Error;

#[cfg(feature = "local-embeddings")]
pub mod local;

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum EmbeddingError {
    #[cfg(feature = "execution")]
    #[error(transparent)]
    Execution(#[from] crate::execution::ExecutionError),
    #[error("embedding space requires a nonempty model recipe ID and positive dimension")]
    InvalidSpace,
    #[error("expected {expected} vector components, received {actual}")]
    Dimension { expected: usize, actual: usize },
    #[error("vector component {0} is not finite")]
    NonFinite(usize),
    #[error("embedding vector must have a nonzero norm")]
    ZeroVector,
    #[error("embedding spaces do not match: expected {expected:?}, received {actual:?}")]
    SpaceMismatch { expected: String, actual: String },
    #[error("embedding input must not be empty or whitespace-only")]
    EmptyInput,
    #[error("embedding batch size must be positive")]
    BatchSize,
    #[error("provider returned {actual} vectors for {expected} inputs")]
    BatchCount { expected: usize, actual: usize },
    #[error("minimum cosine score must be finite and between -1 and 1")]
    InvalidThreshold,
    #[error("embedding provider failed: {0}")]
    Provider(String),
    #[error(transparent)]
    Index(#[from] IndexError),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmbeddingSpace {
    model: String,
    dimensions: usize,
}

impl EmbeddingSpace {
    pub fn new(model: impl Into<String>, dimensions: usize) -> Result<Self, EmbeddingError> {
        let model = model.into();
        if model.trim().is_empty() || dimensions == 0 {
            return Err(EmbeddingError::InvalidSpace);
        }
        Ok(Self { model, dimensions })
    }

    pub fn model(&self) -> &str {
        &self.model
    }

    pub fn dimensions(&self) -> usize {
        self.dimensions
    }

    pub(crate) fn require(&self, other: &Self) -> Result<(), EmbeddingError> {
        if self == other {
            Ok(())
        } else {
            Err(EmbeddingError::SpaceMismatch {
                expected: format!("{}:{}", self.model, self.dimensions),
                actual: format!("{}:{}", other.model, other.dimensions),
            })
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Embedding {
    space: EmbeddingSpace,
    values: Vec<f32>,
}

impl Embedding {
    pub fn new(space: EmbeddingSpace, mut values: Vec<f32>) -> Result<Self, EmbeddingError> {
        let norm = vector_norm(&values, space.dimensions)?;
        for value in &mut values {
            *value = (f64::from(*value) / norm) as f32;
        }
        Ok(Self { space, values })
    }

    pub fn space(&self) -> &EmbeddingSpace {
        &self.space
    }

    pub fn values(&self) -> &[f32] {
        &self.values
    }

    pub fn cosine(&self, other: &Self) -> Result<f64, EmbeddingError> {
        self.space.require(&other.space)?;
        cosine_similarity(&self.values, &other.values)
    }
}

pub(crate) fn vector_norm(values: &[f32], dimensions: usize) -> Result<f64, EmbeddingError> {
    if values.len() != dimensions || dimensions == 0 {
        return Err(EmbeddingError::Dimension {
            expected: dimensions,
            actual: values.len(),
        });
    }
    let mut squared = 0.0;
    for (index, &value) in values.iter().enumerate() {
        if !value.is_finite() {
            return Err(EmbeddingError::NonFinite(index));
        }
        squared += f64::from(value) * f64::from(value);
    }
    if squared == 0.0 {
        return Err(EmbeddingError::ZeroVector);
    }
    Ok(squared.sqrt())
}

pub fn cosine_similarity(left: &[f32], right: &[f32]) -> Result<f64, EmbeddingError> {
    let left_norm = vector_norm(left, left.len())?;
    let right_norm = vector_norm(right, left.len())?;
    Ok(cosine_with_norms(left, left_norm, right, right_norm))
}

pub(crate) fn cosine_with_norms(
    left: &[f32],
    left_norm: f64,
    right: &[f32],
    right_norm: f64,
) -> f64 {
    let dot: f64 = left
        .iter()
        .zip(right)
        .map(|(&a, &b)| f64::from(a) * f64::from(b))
        .sum();
    (dot / left_norm / right_norm).clamp(-1.0, 1.0)
}

#[derive(Debug, Clone)]
struct StoredVector {
    values: Arc<Vec<f32>>,
    norm: OnceLock<f64>,
}

impl StoredVector {
    fn validated(values: Vec<f32>) -> Self {
        Self {
            values: Arc::new(values),
            norm: OnceLock::new(),
        }
    }

    #[cfg(feature = "cache")]
    fn with_norm(values: Vec<f32>, norm: f64) -> Self {
        Self {
            values: Arc::new(values),
            norm: OnceLock::from(norm),
        }
    }

    fn norm(&self) -> f64 {
        if let Some(norm) = self.norm.get() {
            return *norm;
        }
        let norm =
            vector_norm(&self.values, self.values.len()).expect("stored vectors are validated");
        let _ = self.norm.set(norm);
        norm
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EmbeddingPurpose {
    Query,
    Document,
}

pub trait EmbeddingProvider {
    fn space(&self) -> &EmbeddingSpace;

    fn embed(
        &mut self,
        texts: &[&str],
        purpose: EmbeddingPurpose,
    ) -> Result<Vec<Vec<f32>>, EmbeddingError>;
}

pub fn embed_batch(
    provider: &mut (impl EmbeddingProvider + ?Sized),
    texts: &[&str],
    purpose: EmbeddingPurpose,
) -> Result<Vec<Embedding>, EmbeddingError> {
    if texts.iter().any(|text| text.trim().is_empty()) {
        return Err(EmbeddingError::EmptyInput);
    }
    if texts.is_empty() {
        return Ok(Vec::new());
    }
    let space = provider.space().clone();
    let vectors = provider.embed(texts, purpose)?;
    space.require(provider.space())?;
    if vectors.len() != texts.len() {
        return Err(EmbeddingError::BatchCount {
            expected: texts.len(),
            actual: vectors.len(),
        });
    }
    vectors
        .into_iter()
        .map(|vector| Embedding::new(space.clone(), vector))
        .collect()
}

#[derive(Debug, Clone)]
pub struct SemanticSearchOptions {
    #[cfg(feature = "execution")]
    control: Option<crate::execution::WorkControl>,
    limit: usize,
    min_score: f64,
    context: Option<Context>,
}

impl SemanticSearchOptions {
    #[cfg(feature = "execution")]
    fn progress(&self, phase: crate::execution::WorkPhase, completed: usize, total: Option<usize>) {
        if let Some(control) = self.control() {
            control.progress(phase, completed, total);
        }
    }

    #[cfg(feature = "execution")]
    pub fn with_control(mut self, control: crate::execution::WorkControl) -> Self {
        self.control = Some(control);
        self
    }
    #[cfg(feature = "execution")]
    pub fn control(&self) -> Option<&crate::execution::WorkControl> {
        self.control.as_ref()
    }
    fn checkpoint(&self) -> Result<(), EmbeddingError> {
        #[cfg(feature = "execution")]
        if let Some(control) = &self.control {
            control
                .checkpoint()
                .map_err(crate::semantic::EmbeddingError::from)?;
        }
        Ok(())
    }

    pub fn new(limit: usize) -> Self {
        Self {
            limit,
            ..Self::default()
        }
    }

    pub fn with_min_score(mut self, min_score: f64) -> Result<Self, EmbeddingError> {
        if !min_score.is_finite() || !(-1.0..=1.0).contains(&min_score) {
            return Err(EmbeddingError::InvalidThreshold);
        }
        self.min_score = min_score;
        Ok(self)
    }

    pub fn with_context(mut self, context: Context) -> Self {
        self.context = Some(context);
        self
    }

    pub fn limit(&self) -> usize {
        self.limit
    }

    pub fn min_score(&self) -> f64 {
        self.min_score
    }

    pub fn context(&self) -> Option<&Context> {
        self.context.as_ref()
    }
}

impl Default for SemanticSearchOptions {
    fn default() -> Self {
        Self {
            #[cfg(feature = "execution")]
            control: None,
            limit: 10,
            min_score: -1.0,
            context: None,
        }
    }
}

#[derive(Debug, Clone, serde::Serialize)]
#[non_exhaustive]
pub struct SemanticResult<'a> {
    pub entry: &'a KnowledgeEntry,
    pub score: f64,
}

impl Ranked for SemanticResult<'_> {
    fn score(&self) -> f64 {
        self.score
    }
    fn id(&self) -> &str {
        &self.entry.id
    }
}

#[derive(Debug, Clone)]
pub struct SemanticIndex {
    lexical: Engine,
    space: EmbeddingSpace,
    vectors: BTreeMap<String, StoredVector>,
}

impl SemanticIndex {
    #[cfg(feature = "cache")]
    pub(crate) fn from_cached_parts(
        lexical: Engine,
        space: EmbeddingSpace,
        vectors: BTreeMap<String, (Vec<f32>, f64)>,
    ) -> Self {
        Self {
            lexical,
            space,
            vectors: vectors
                .into_iter()
                .map(|(id, (vector, norm))| (id, StoredVector::with_norm(vector, norm)))
                .collect(),
        }
    }
    pub fn new(space: EmbeddingSpace) -> Self {
        Self {
            lexical: Engine::new(),
            space,
            vectors: BTreeMap::new(),
        }
    }

    pub fn from_index(
        lexical: Engine,
        provider: &mut (impl EmbeddingProvider + ?Sized),
        batch_size: usize,
    ) -> Result<Self, EmbeddingError> {
        if batch_size == 0 {
            return Err(EmbeddingError::BatchSize);
        }
        let space = provider.space().clone();
        let mut vectors = BTreeMap::new();
        let mut entries = lexical.entries();
        loop {
            let batch: Vec<_> = entries.by_ref().take(batch_size).collect();
            if batch.is_empty() {
                break;
            }
            space.require(provider.space())?;
            let texts: Vec<_> = batch.iter().map(|entry| entry.text.as_str()).collect();
            let embedded = embed_batch(provider, &texts, EmbeddingPurpose::Document)?;
            space.require(provider.space())?;
            for (entry, embedding) in batch.into_iter().zip(embedded) {
                vectors.insert(entry.id.clone(), StoredVector::validated(embedding.values));
            }
        }
        drop(entries);
        Ok(Self {
            lexical,
            space,
            vectors,
        })
    }

    #[cfg(feature = "hnsw")]
    pub(crate) fn shared_embeddings(&self) -> impl Iterator<Item = (&str, Arc<Vec<f32>>)> {
        self.vectors
            .iter()
            .map(|(id, vector)| (id.as_str(), Arc::clone(&vector.values)))
    }

    pub fn space(&self) -> &EmbeddingSpace {
        &self.space
    }
    pub fn lexical(&self) -> &Engine {
        &self.lexical
    }

    pub fn into_lexical(self) -> Engine {
        self.lexical
    }
    pub fn len(&self) -> usize {
        self.lexical.len()
    }
    pub fn is_empty(&self) -> bool {
        self.lexical.is_empty()
    }
    pub fn embedding(&self, id: &str) -> Option<&[f32]> {
        self.vectors.get(id).map(|vector| vector.values.as_slice())
    }
    #[cfg(feature = "hnsw")]
    pub(crate) fn stored_embedding(&self, id: &str) -> Option<(&[f32], f64)> {
        self.vectors
            .get(id)
            .map(|vector| (vector.values.as_slice(), vector.norm()))
    }
    #[cfg(feature = "snapshots")]
    pub(crate) fn replace_unchanged_text(
        &mut self,
        entry: KnowledgeEntry,
    ) -> Result<Option<KnowledgeEntry>, EmbeddingError> {
        if self
            .lexical
            .get(&entry.id)
            .is_none_or(|old| old.text != entry.text)
        {
            return Ok(None);
        }
        Ok(self.lexical.upsert(entry)?)
    }

    pub fn upsert_embedded(
        &mut self,
        entry: KnowledgeEntry,
        embedding: Embedding,
    ) -> Result<Option<KnowledgeEntry>, EmbeddingError> {
        self.space.require(embedding.space())?;
        let normalized = validate_entry(&entry)?;
        self.vectors
            .insert(entry.id.clone(), StoredVector::validated(embedding.values));
        Ok(self.lexical.insert_validated(entry, normalized))
    }

    pub fn upsert(
        &mut self,
        entry: KnowledgeEntry,
        provider: &mut (impl EmbeddingProvider + ?Sized),
    ) -> Result<Option<KnowledgeEntry>, EmbeddingError> {
        let normalized = validate_entry(&entry)?;
        self.space.require(provider.space())?;
        let mut embedded = embed_batch(provider, &[&entry.text], EmbeddingPurpose::Document)?;
        self.space.require(provider.space())?;
        let embedding = embedded.pop().expect("validated single embedding");
        self.vectors
            .insert(entry.id.clone(), StoredVector::validated(embedding.values));
        Ok(self.lexical.insert_validated(entry, normalized))
    }

    pub fn upsert_batch(
        &mut self,
        entries: Vec<KnowledgeEntry>,
        provider: &mut (impl EmbeddingProvider + ?Sized),
        batch_size: usize,
    ) -> Result<usize, EmbeddingError> {
        if batch_size == 0 {
            return Err(EmbeddingError::BatchSize);
        }
        self.space.require(provider.space())?;
        let mut ids = BTreeSet::new();
        let mut prepared = Vec::with_capacity(entries.len());
        for entry in entries {
            if !ids.insert(entry.id.clone()) {
                return Err(IndexError::DuplicateId(entry.id).into());
            }
            let normalized = validate_entry(&entry)?;
            prepared.push((entry, normalized));
        }
        let mut embeddings = Vec::with_capacity(prepared.len());
        for batch in prepared.chunks(batch_size) {
            self.space.require(provider.space())?;
            let texts: Vec<_> = batch.iter().map(|(entry, _)| entry.text.as_str()).collect();
            embeddings.extend(embed_batch(provider, &texts, EmbeddingPurpose::Document)?);
            self.space.require(provider.space())?;
        }
        let count = prepared.len();
        for ((entry, normalized), embedding) in prepared.into_iter().zip(embeddings) {
            self.vectors
                .insert(entry.id.clone(), StoredVector::validated(embedding.values));
            self.lexical.insert_validated(entry, normalized);
        }
        Ok(count)
    }

    pub fn remove(&mut self, id: &str) -> Option<KnowledgeEntry> {
        self.vectors.remove(id);
        self.lexical.remove(id)
    }

    pub fn clear(&mut self) {
        self.vectors.clear();
        self.lexical.clear();
    }

    pub fn search(
        &self,
        query: &str,
        provider: &mut (impl EmbeddingProvider + ?Sized),
        options: &SemanticSearchOptions,
    ) -> Result<Vec<SemanticResult<'_>>, EmbeddingError> {
        options.checkpoint()?;
        if query.trim().is_empty() {
            return Err(EmbeddingError::EmptyInput);
        }
        self.space.require(provider.space())?;
        if options.limit == 0 || self.is_empty() {
            return Ok(Vec::new());
        }
        #[cfg(feature = "execution")]
        options.progress(crate::execution::WorkPhase::Embedding, 0, Some(1));
        options.checkpoint()?;
        let embeddings = embed_batch(provider, &[query], EmbeddingPurpose::Query);
        options.checkpoint()?;
        let mut embeddings = embeddings?;
        #[cfg(feature = "execution")]
        options.progress(crate::execution::WorkPhase::Embedding, 1, Some(1));
        self.space.require(provider.space())?;
        self.search_embedding(
            &embeddings.pop().expect("validated single embedding"),
            options,
        )
    }

    pub fn search_embedding(
        &self,
        query: &Embedding,
        options: &SemanticSearchOptions,
    ) -> Result<Vec<SemanticResult<'_>>, EmbeddingError> {
        options.checkpoint()?;
        self.space.require(query.space())?;
        let mut results = TopK::new(options.limit);
        if options.limit == 0 {
            return Ok(Vec::new());
        }
        let query_norm = vector_norm(query.values(), query.values().len())?;
        #[cfg(feature = "execution")]
        options.progress(
            crate::execution::WorkPhase::Ranking,
            0,
            Some(self.vectors.len()),
        );
        for (position, (id, vector)) in self.vectors.iter().enumerate() {
            #[cfg(not(feature = "execution"))]
            let _ = position;
            #[cfg(feature = "execution")]
            if position.is_multiple_of(512) {
                options.progress(
                    crate::execution::WorkPhase::Ranking,
                    position,
                    Some(self.vectors.len()),
                );
            }
            options.checkpoint()?;
            let entry = self
                .lexical
                .get(id)
                .expect("semantic and lexical IDs agree");
            if options
                .context
                .as_ref()
                .is_some_and(|context| !context.includes(entry))
            {
                continue;
            }
            let score =
                cosine_with_norms(query.values(), query_norm, &vector.values, vector.norm());
            if score >= options.min_score {
                results.push(SemanticResult { entry, score });
            }
        }
        options.checkpoint()?;
        let results = results.finish();
        #[cfg(feature = "execution")]
        options.progress(
            crate::execution::WorkPhase::Ranking,
            self.vectors.len(),
            Some(self.vectors.len()),
        );
        options.checkpoint()?;
        Ok(results)
    }
}

#[cfg(all(feature = "execution", feature = "snapshots"))]
pub(crate) struct ControlledProvider<'a> {
    pub(crate) provider: &'a mut dyn EmbeddingProvider,
    pub(crate) control: &'a crate::execution::WorkControl,
}
#[cfg(all(feature = "execution", feature = "snapshots"))]
impl EmbeddingProvider for ControlledProvider<'_> {
    fn space(&self) -> &EmbeddingSpace {
        self.provider.space()
    }
    fn embed(
        &mut self,
        texts: &[&str],
        purpose: EmbeddingPurpose,
    ) -> Result<Vec<Vec<f32>>, EmbeddingError> {
        self.control
            .progress(crate::execution::WorkPhase::Embedding, 0, Some(texts.len()));
        self.control.checkpoint()?;
        let result = self.provider.embed(texts, purpose);
        self.control.checkpoint()?;
        if result.is_ok() {
            self.control.progress(
                crate::execution::WorkPhase::Embedding,
                texts.len(),
                Some(texts.len()),
            );
        }
        result
    }
}

#[cfg(test)]
mod stored_norm_tests {
    use super::*;

    #[test]
    fn norms_are_lazy_concurrent_and_bound_to_the_stored_values() {
        let space = EmbeddingSpace::new("stored-norm-lifecycle", 3).unwrap();
        let query = Embedding::new(space.clone(), vec![1.0, 3.0, 4.0]).unwrap();
        let mut index = SemanticIndex::new(space.clone());
        for id in ["a", "b"] {
            let entry = KnowledgeEntry::new(id, id).with_metadata(serde_json::json!({"group": id}));
            index.upsert_embedded(entry, query.clone()).unwrap();
        }
        let cold = index.clone();
        let expected = vector_norm(query.values(), 3).unwrap().to_bits();
        let scoped =
            SemanticSearchOptions::new(2).with_context(Context::new().with_metadata("group", "a"));
        let ready = std::sync::Barrier::new(2);
        assert!(index
            .vectors
            .values()
            .all(|vector| vector.norm.get().is_none()));
        std::thread::scope(|scope| {
            for _ in 0..2 {
                scope.spawn(|| {
                    ready.wait();
                    let hits = index.search_embedding(&query, &scoped).unwrap();
                    assert_eq!(hits.len(), 1);
                    assert_eq!(hits[0].entry.id, "a");
                    assert_eq!(
                        hits[0].score.to_bits(),
                        query.cosine(&query).unwrap().to_bits()
                    );
                });
            }
        });
        let warm = index.clone();
        assert!(cold
            .vectors
            .values()
            .all(|vector| vector.norm.get().is_none()));
        for current in [&index, &warm] {
            assert_eq!(current.vectors["a"].norm.get().unwrap().to_bits(), expected);
            assert!(current.vectors["b"].norm.get().is_none());
        }
        let changed = Embedding::new(space, vec![0.0, -1.0, 0.0]).unwrap();
        index
            .upsert_embedded(KnowledgeEntry::new("a", "replaced"), changed.clone())
            .unwrap();
        assert!(index.vectors["a"].norm.get().is_none());
        let hits = index
            .search_embedding(&changed, &SemanticSearchOptions::new(2))
            .unwrap();
        assert_eq!(
            hits[0].score.to_bits(),
            changed.cosine(&changed).unwrap().to_bits()
        );
        assert_eq!(index.vectors["a"].norm.get(), Some(&1.0));
        assert_eq!(warm.vectors["a"].norm.get().unwrap().to_bits(), expected);
        index.remove("a");
        assert!(!index.vectors.contains_key("a"));
        assert!(warm.vectors.contains_key("a"));
    }

    #[cfg(feature = "cache")]
    #[test]
    fn cache_import_reuses_the_validated_norm_while_export_leaves_it_cold() {
        use crate::cache::{CacheIdentity, IndexCache};
        let directory = tempfile::tempdir().unwrap();
        let cache = IndexCache::new(
            directory.path().join("vectors"),
            CacheIdentity::new("norm-cache").unwrap(),
        );
        let space = EmbeddingSpace::new("restored-norm", 3).unwrap();
        let embedding = Embedding::new(space.clone(), vec![1.0, 2.0, -3.0]).unwrap();
        let norm = vector_norm(embedding.values(), 3).unwrap();
        let entry = KnowledgeEntry::new("v", "document");
        let mut index = SemanticIndex::new(space.clone());
        index.upsert_embedded(entry.clone(), embedding).unwrap();
        cache.save_semantic(&index).unwrap();
        assert!(index.vectors["v"].norm.get().is_none());
        let loaded = cache.load_semantic(&mut vec![entry], &space).unwrap();
        assert_eq!(
            loaded.index().vectors["v"].norm.get().unwrap().to_bits(),
            norm.to_bits()
        );
    }
}