Skip to main content

weirdnet_semcache/
semantic.rs

1//! Similarity lookup by embedding: [`SemanticCache`].
2//!
3//! The caller embeds the prompt (with whatever embedding model it runs) and asks the cache for
4//! the stored entry whose embedding is closest by cosine similarity. A stored value stands in
5//! only when that similarity reaches the configured threshold, and only within the same scope,
6//! so answers never cross models, revisions or system prompts. See [`scope_key`].
7//!
8//! Embeddings are validated (non-empty, finite, not all zero, the scope's dimension) and
9//! normalized to unit length on the way in, so callers may pass raw or normalized vectors.
10
11use std::collections::HashMap;
12use std::fmt;
13use std::sync::Mutex;
14use std::time::{Duration, Instant};
15
16use serde::de::DeserializeOwned;
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19use weirdnet_agent::remote::{from_cbor, to_cbor};
20
21use crate::CachedAnswer;
22
23/// Similarity a lookup needs to hit when none is configured.
24pub const DEFAULT_THRESHOLD: f32 = 0.95;
25
26/// Two normalized embeddings at least this similar are the same entry: inserting one replaces
27/// the other's value instead of adding a near-duplicate.
28const SAME_ENTRY: f32 = 1.0 - 1e-6;
29
30/// How a [`SemanticCache`] matches and evicts.
31#[derive(Debug, Clone, PartialEq)]
32#[non_exhaustive]
33pub struct SemanticConfig {
34    /// At most this many entries across all scopes (at least 1); the least recently used goes first.
35    pub max_entries: usize,
36    /// Cosine similarity, in `-1.0..=1.0`, a lookup needs to hit.
37    pub threshold: f32,
38    /// Entries older than this never hit and are dropped. `None` keeps them until evicted.
39    pub ttl: Option<Duration>,
40    /// Every embedding must have this many dimensions. `None` fixes each scope's dimension from
41    /// its first entry (until the scope is empty again).
42    pub dimension: Option<usize>,
43}
44
45impl SemanticConfig {
46    /// At most `max_entries`, threshold [`DEFAULT_THRESHOLD`], no TTL, any dimension.
47    pub fn new(max_entries: usize) -> Self {
48        Self { max_entries: max_entries.max(1), threshold: DEFAULT_THRESHOLD, ttl: None, dimension: None }
49    }
50
51    /// Hit at `threshold` or above, clamped to `-1.0..=1.0`. A NaN keeps the current threshold.
52    pub fn with_threshold(mut self, threshold: f32) -> Self {
53        if !threshold.is_nan() {
54            self.threshold = threshold.clamp(-1.0, 1.0);
55        }
56        self
57    }
58
59    /// Entries expire `ttl` after they were stored.
60    pub fn with_ttl(mut self, ttl: Duration) -> Self {
61        self.ttl = Some(ttl);
62        self
63    }
64
65    /// Every embedding must have `dimension` dimensions.
66    pub fn with_dimension(mut self, dimension: usize) -> Self {
67        self.dimension = Some(dimension);
68        self
69    }
70}
71
72impl Default for SemanticConfig {
73    fn default() -> Self {
74        Self::new(256)
75    }
76}
77
78/// Why a [`SemanticCache`] call was refused.
79#[derive(Debug, Clone, PartialEq, Eq)]
80#[non_exhaustive]
81pub enum SemanticError {
82    /// The embedding has no dimensions.
83    Empty,
84    /// The embedding holds a NaN or an infinity.
85    NotFinite,
86    /// The embedding is all zeros (or too small to normalize), so it has no direction.
87    ZeroVector,
88    /// The embedding's dimension isn't the configured one or the scope's.
89    DimensionMismatch { expected: usize, found: usize },
90    /// A snapshot couldn't be written or read.
91    Snapshot(String),
92}
93
94impl fmt::Display for SemanticError {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        match self {
97            Self::Empty => f.write_str("embedding is empty"),
98            Self::NotFinite => f.write_str("embedding holds a NaN or an infinity"),
99            Self::ZeroVector => f.write_str("embedding is a zero vector"),
100            Self::DimensionMismatch { expected, found } => write!(f, "embedding has {found} dimensions, expected {expected}"),
101            Self::Snapshot(e) => write!(f, "snapshot: {e}"),
102        }
103    }
104}
105
106impl std::error::Error for SemanticError {}
107
108/// The result of [`SemanticCache::lookup`].
109#[derive(Debug, Clone, PartialEq)]
110#[non_exhaustive]
111pub enum Lookup<V> {
112    /// The most similar live entry in the scope reached the threshold.
113    Hit {
114        /// A copy of the stored value.
115        value: V,
116        /// Cosine similarity to the query.
117        score: f32,
118        /// The entry, for [`SemanticCache::remove`].
119        id: u64,
120    },
121    /// Nothing reached the threshold.
122    Miss {
123        /// The best similarity found below the threshold, `None` when the scope had no live entries.
124        best: Option<f32>,
125    },
126}
127
128impl<V> Lookup<V> {
129    pub fn is_hit(&self) -> bool {
130        matches!(self, Self::Hit { .. })
131    }
132
133    /// The hit's score, or the best score of a miss.
134    pub fn score(&self) -> Option<f32> {
135        match self {
136            Self::Hit { score, .. } => Some(*score),
137            Self::Miss { best } => *best,
138        }
139    }
140
141    /// The value of a hit.
142    pub fn into_value(self) -> Option<V> {
143        match self {
144            Self::Hit { value, .. } => Some(value),
145            Self::Miss { .. } => None,
146        }
147    }
148}
149
150/// Counters since the cache was made or last [`clear`](SemanticCache::clear)ed.
151#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
152#[non_exhaustive]
153pub struct SemanticStats {
154    /// Live entries now (expired ones not yet dropped included).
155    pub entries: usize,
156    pub hits: u64,
157    pub misses: u64,
158    /// Entries dropped to make room.
159    pub evictions: u64,
160    /// Entries dropped because their TTL ran out.
161    pub expired: u64,
162}
163
164/// A stable scope for [`SemanticCache`]: hex SHA-256 over the length-prefixed `parts`, such as
165/// the model id, its revision and a hash of the system prompt. Different parts (or the same
166/// text split differently) give different scopes.
167pub fn scope_key(parts: &[&str]) -> String {
168    let mut h = Sha256::new();
169    h.update(b"weirdnet-semcache/scope/v1");
170    for p in parts {
171        h.update((p.len() as u64).to_le_bytes());
172        h.update(p.as_bytes());
173    }
174    h.finalize().iter().map(|b| format!("{b:02x}")).collect()
175}
176
177/// `embedding` scaled to unit length, after checking it is non-empty, finite and not zero.
178pub fn normalize(embedding: &[f32]) -> Result<Vec<f32>, SemanticError> {
179    if embedding.is_empty() {
180        return Err(SemanticError::Empty);
181    }
182    if embedding.iter().any(|x| !x.is_finite()) {
183        return Err(SemanticError::NotFinite);
184    }
185    let norm = embedding.iter().map(|&x| f64::from(x) * f64::from(x)).sum::<f64>().sqrt();
186    if !norm.is_normal() {
187        return Err(SemanticError::ZeroVector);
188    }
189    let v: Vec<f32> = embedding.iter().map(|&x| (f64::from(x) / norm) as f32).collect();
190    if v.iter().all(|&x| x == 0.0) {
191        return Err(SemanticError::ZeroVector);
192    }
193    Ok(v)
194}
195
196/// Cosine similarity of two embeddings, or `None` when either is empty, not finite or zero, or
197/// their dimensions differ.
198pub fn cosine_similarity(a: &[f32], b: &[f32]) -> Option<f32> {
199    if a.len() != b.len() {
200        return None;
201    }
202    let (a, b) = (normalize(a).ok()?, normalize(b).ok()?);
203    Some(dot(&a, &b))
204}
205
206fn dot(a: &[f32], b: &[f32]) -> f32 {
207    let s: f64 = a.iter().zip(b).map(|(&x, &y)| f64::from(x) * f64::from(y)).sum();
208    (s as f32).clamp(-1.0, 1.0)
209}
210
211struct Entry<V> {
212    id: u64,
213    vector: Vec<f32>,
214    value: V,
215    stored: Instant,
216    used: u64,
217}
218
219struct Scope<V> {
220    dimension: usize,
221    entries: Vec<Entry<V>>,
222}
223
224struct State<V> {
225    tick: u64,
226    next_id: u64,
227    scopes: HashMap<String, Scope<V>>,
228    stats: SemanticStats,
229}
230
231impl<V> State<V> {
232    fn len(&self) -> usize {
233        self.scopes.values().map(|s| s.entries.len()).sum()
234    }
235
236    fn drop_empty(&mut self) {
237        self.scopes.retain(|_, s| !s.entries.is_empty());
238    }
239
240    fn purge_expired(&mut self, ttl: Option<Duration>, now: Instant) {
241        let Some(ttl) = ttl else { return };
242        let mut gone = 0;
243        for s in self.scopes.values_mut() {
244            let before = s.entries.len();
245            s.entries.retain(|e| !expired(e.stored, ttl, now));
246            gone += (before - s.entries.len()) as u64;
247        }
248        self.stats.expired += gone;
249        self.drop_empty();
250    }
251
252    fn evict_lru(&mut self) {
253        let oldest = self
254            .scopes
255            .iter()
256            .flat_map(|(k, s)| s.entries.iter().enumerate().map(move |(i, e)| (e.used, k, i)))
257            .min_by_key(|(used, _, _)| *used)
258            .map(|(_, k, i)| (k.clone(), i));
259        if let Some((k, i)) = oldest
260            && let Some(s) = self.scopes.get_mut(&k)
261        {
262            s.entries.swap_remove(i);
263            self.stats.evictions += 1;
264        }
265        self.drop_empty();
266    }
267}
268
269fn expired(stored: Instant, ttl: Duration, now: Instant) -> bool {
270    now.saturating_duration_since(stored) >= ttl
271}
272
273/// Embedding-similarity cache: the nearest stored embedding in the same scope, by cosine
274/// similarity, stands in when it reaches the threshold.
275///
276/// Bounded and least-recently-used across scopes like [`MemoryStore`](crate::MemoryStore), with
277/// an optional TTL. Values default to [`CachedAnswer`] but may be any `Clone` type. Callers
278/// decide what may be cached; for infer/2 requests check [`may_read`](crate::may_read) and
279/// [`may_store`](crate::may_store) first.
280pub struct SemanticCache<V = CachedAnswer> {
281    config: SemanticConfig,
282    state: Mutex<State<V>>,
283}
284
285impl<V: Clone> SemanticCache<V> {
286    /// In memory, at most `max_entries`, with the default threshold and no TTL.
287    pub fn new(max_entries: usize) -> Self {
288        Self::with_config(SemanticConfig::new(max_entries))
289    }
290
291    pub fn with_config(config: SemanticConfig) -> Self {
292        let config = SemanticConfig { max_entries: config.max_entries.max(1), ..config };
293        Self { config, state: Mutex::new(State { tick: 0, next_id: 1, scopes: HashMap::new(), stats: SemanticStats::default() }) }
294    }
295
296    pub fn config(&self) -> &SemanticConfig {
297        &self.config
298    }
299
300    fn lock(&self) -> std::sync::MutexGuard<'_, State<V>> {
301        self.state.lock().unwrap_or_else(|e| e.into_inner())
302    }
303
304    fn check(&self, scope: Option<&Scope<V>>, v: &[f32]) -> Result<(), SemanticError> {
305        let expected = self.config.dimension.or(scope.map(|s| s.dimension));
306        match expected {
307            Some(expected) if expected != v.len() => Err(SemanticError::DimensionMismatch { expected, found: v.len() }),
308            _ => Ok(()),
309        }
310    }
311
312    /// The most similar live entry in `scope`: a [`Lookup::Hit`] when its similarity reaches the
313    /// threshold (and the entry counts as used), a [`Lookup::Miss`] with the best score otherwise.
314    pub fn lookup(&self, scope: &str, embedding: &[f32]) -> Result<Lookup<V>, SemanticError> {
315        self.lookup_at(scope, embedding, Instant::now())
316    }
317
318    fn lookup_at(&self, scope: &str, embedding: &[f32], now: Instant) -> Result<Lookup<V>, SemanticError> {
319        self.lookup_with_vector(scope, embedding, now).map(|(l, _)| l)
320    }
321
322    /// [`lookup`](Self::lookup), also returning the hit's stored (normalized) embedding.
323    pub(crate) fn lookup_with_vector(&self, scope: &str, embedding: &[f32], now: Instant) -> Result<(Lookup<V>, Option<Vec<f32>>), SemanticError> {
324        let query = normalize(embedding)?;
325        let mut g = self.lock();
326        g.purge_expired(self.config.ttl, now);
327        self.check(g.scopes.get(scope), &query)?;
328        g.tick += 1;
329        let tick = g.tick;
330        let threshold = self.config.threshold;
331        let best = g.scopes.get_mut(scope).and_then(|s| s.entries.iter_mut().map(|e| (dot(&e.vector, &query), e)).max_by(|a, b| a.0.total_cmp(&b.0)));
332        let (result, vector) = match best {
333            Some((score, e)) if score >= threshold => {
334                e.used = tick;
335                (Lookup::Hit { value: e.value.clone(), score, id: e.id }, Some(e.vector.clone()))
336            }
337            other => (Lookup::Miss { best: other.map(|(score, _)| score) }, None),
338        };
339        if result.is_hit() {
340            g.stats.hits += 1;
341        } else {
342            g.stats.misses += 1;
343        }
344        Ok((result, vector))
345    }
346
347    /// Stores `value` under `embedding` in `scope` and returns the entry's id. An entry with the
348    /// same direction in the scope is replaced (keeping its id); otherwise, when full, expired
349    /// entries go first, then the least recently used.
350    pub fn insert(&self, scope: &str, embedding: &[f32], value: V) -> Result<u64, SemanticError> {
351        self.insert_at(scope, embedding, value, Instant::now())
352    }
353
354    pub(crate) fn insert_at(&self, scope: &str, embedding: &[f32], value: V, now: Instant) -> Result<u64, SemanticError> {
355        let vector = normalize(embedding)?;
356        let mut g = self.lock();
357        g.purge_expired(self.config.ttl, now);
358        self.check(g.scopes.get(scope), &vector)?;
359        g.tick += 1;
360        let tick = g.tick;
361        if let Some(e) = g.scopes.get_mut(scope).and_then(|s| s.entries.iter_mut().find(|e| dot(&e.vector, &vector) >= SAME_ENTRY)) {
362            e.vector = vector;
363            e.value = value;
364            e.stored = now;
365            e.used = tick;
366            return Ok(e.id);
367        }
368        while g.len() >= self.config.max_entries {
369            g.evict_lru();
370        }
371        let id = g.next_id;
372        g.next_id += 1;
373        let dimension = vector.len();
374        g.scopes.entry(scope.to_owned()).or_insert_with(|| Scope { dimension, entries: Vec::new() }).entries.push(Entry {
375            id,
376            vector,
377            value,
378            stored: now,
379            used: tick,
380        });
381        Ok(id)
382    }
383
384    /// Removes entry `id` and returns its value.
385    pub fn remove(&self, id: u64) -> Option<V> {
386        let mut g = self.lock();
387        let found = g.scopes.values_mut().find_map(|s| {
388            let i = s.entries.iter().position(|e| e.id == id)?;
389            Some(s.entries.swap_remove(i).value)
390        });
391        g.drop_empty();
392        found
393    }
394
395    /// Removes every entry in `scope` and returns how many there were.
396    pub fn remove_scope(&self, scope: &str) -> usize {
397        self.lock().scopes.remove(scope).map_or(0, |s| s.entries.len())
398    }
399
400    /// Removes every entry and resets the counters.
401    pub fn clear(&self) {
402        let mut g = self.lock();
403        g.scopes.clear();
404        g.stats = SemanticStats::default();
405    }
406
407    /// Entries stored, expired ones not yet dropped included.
408    pub fn len(&self) -> usize {
409        self.lock().len()
410    }
411
412    pub fn is_empty(&self) -> bool {
413        self.len() == 0
414    }
415
416    pub fn stats(&self) -> SemanticStats {
417        let g = self.lock();
418        SemanticStats { entries: g.len(), ..g.stats }
419    }
420}
421
422#[derive(Serialize, Deserialize)]
423struct SnapshotEntry<V> {
424    scope: String,
425    vector: Vec<f32>,
426    /// Age when written, so the TTL keeps counting after a restore.
427    age_ms: u64,
428    value: V,
429}
430
431#[derive(Serialize, Deserialize)]
432struct Snapshot<V> {
433    v: u8,
434    entries: Vec<SnapshotEntry<V>>,
435}
436
437impl<V: Clone + Serialize + DeserializeOwned> SemanticCache<V> {
438    /// The live entries as CBOR, least recently used first, for [`restore`](Self::restore).
439    pub fn snapshot(&self) -> Result<Vec<u8>, SemanticError> {
440        let now = Instant::now();
441        let g = self.lock();
442        let mut entries: Vec<(u64, SnapshotEntry<V>)> = g
443            .scopes
444            .iter()
445            .flat_map(|(k, s)| s.entries.iter().map(move |e| (k, e)))
446            .filter(|(_, e)| self.config.ttl.is_none_or(|ttl| !expired(e.stored, ttl, now)))
447            .map(|(k, e)| {
448                let age_ms = u64::try_from(now.saturating_duration_since(e.stored).as_millis()).unwrap_or(u64::MAX);
449                (e.used, SnapshotEntry { scope: k.clone(), vector: e.vector.clone(), age_ms, value: e.value.clone() })
450            })
451            .collect();
452        entries.sort_by_key(|(used, _)| *used);
453        let snap = Snapshot { v: 1, entries: entries.into_iter().map(|(_, e)| e).collect() };
454        to_cbor(&snap).map_err(|e| SemanticError::Snapshot(e.to_string()))
455    }
456
457    /// A cache with `config` holding the entries of a [`snapshot`](Self::snapshot). Entries that
458    /// fail validation under `config` (dimension, finite) or have expired are skipped; the most
459    /// recently used are kept when there are more than `max_entries`.
460    pub fn restore(config: SemanticConfig, bytes: &[u8]) -> Result<Self, SemanticError> {
461        let snap: Snapshot<V> = from_cbor(bytes).map_err(|e| SemanticError::Snapshot(e.to_string()))?;
462        if snap.v != 1 {
463            return Err(SemanticError::Snapshot(format!("unknown snapshot version {}", snap.v)));
464        }
465        let cache = Self::with_config(config);
466        let now = Instant::now();
467        for e in snap.entries {
468            let stored = now.checked_sub(Duration::from_millis(e.age_ms)).unwrap_or(now);
469            if cache.config.ttl.is_some_and(|ttl| expired(stored, ttl, now)) {
470                continue;
471            }
472            let _ = cache.insert_at(&e.scope, &e.vector, e.value, stored);
473        }
474        cache.lock().stats = SemanticStats::default();
475        Ok(cache)
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482
483    fn cache(max: usize, threshold: f32) -> SemanticCache<&'static str> {
484        SemanticCache::with_config(SemanticConfig::new(max).with_threshold(threshold))
485    }
486
487    #[test]
488    fn exact_and_close_embeddings_hit() {
489        let c = cache(8, 0.9);
490        let id = c.insert("s", &[1.0, 0.0, 0.0], "a").unwrap();
491        match c.lookup("s", &[2.0, 0.0, 0.0]).unwrap() {
492            Lookup::Hit { value, score, id: hit } => {
493                assert_eq!((value, hit), ("a", id));
494                assert!((score - 1.0).abs() < 1e-6, "{score}");
495            }
496            other => panic!("{other:?}"),
497        }
498        let near = c.lookup("s", &[1.0, 0.1, 0.0]).unwrap();
499        assert!(near.is_hit() && near.score().unwrap() > 0.99);
500        assert_eq!(near.into_value(), Some("a"));
501    }
502
503    #[test]
504    fn below_threshold_misses_with_its_best_score() {
505        let c = cache(8, 0.9);
506        c.insert("s", &[1.0, 0.0], "a").unwrap();
507        let l = c.lookup("s", &[1.0, 1.0]).unwrap();
508        assert!(!l.is_hit());
509        let best = l.score().unwrap();
510        assert!((best - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-5, "{best}");
511        assert_eq!(c.lookup("empty", &[1.0, 0.0]).unwrap(), Lookup::Miss { best: None });
512        assert!(cache(8, 0.7).insert("s", &[1.0, 0.0], "a").is_ok());
513    }
514
515    #[test]
516    fn most_similar_entry_wins() {
517        let c = cache(8, 0.5);
518        c.insert("s", &[1.0, 0.0, 0.0], "x").unwrap();
519        c.insert("s", &[0.8, 0.6, 0.0], "xy").unwrap();
520        c.insert("s", &[0.0, 1.0, 0.0], "y").unwrap();
521        assert_eq!(c.lookup("s", &[0.7, 0.7, 0.0]).unwrap().into_value(), Some("xy"));
522        assert_eq!(c.lookup("s", &[0.1, 0.9, 0.0]).unwrap().into_value(), Some("y"));
523        assert_eq!(c.lookup("s", &[0.9, 0.05, 0.1]).unwrap().into_value(), Some("x"));
524    }
525
526    #[test]
527    fn scopes_never_cross() {
528        let c = cache(8, 0.9);
529        let a = scope_key(&["qwen3-8b", "rev1", "sys-hash"]);
530        let b = scope_key(&["qwen3-8b", "rev2", "sys-hash"]);
531        assert_ne!(a, b);
532        assert_ne!(scope_key(&["ab", "c"]), scope_key(&["a", "bc"]), "parts are length-prefixed");
533        assert_eq!(a.len(), 64);
534        c.insert(&a, &[1.0, 0.0], "from a").unwrap();
535        assert_eq!(c.lookup(&b, &[1.0, 0.0]).unwrap(), Lookup::Miss { best: None });
536        c.insert(&b, &[1.0, 0.0], "from b").unwrap();
537        assert_eq!(c.lookup(&a, &[1.0, 0.0]).unwrap().into_value(), Some("from a"));
538        assert_eq!(c.lookup(&b, &[1.0, 0.0]).unwrap().into_value(), Some("from b"));
539        // Scopes may even use different dimensions.
540        c.insert("other", &[1.0, 0.0, 0.0], "3d").unwrap();
541        assert_eq!(c.len(), 3);
542    }
543
544    #[test]
545    fn dimensions_are_checked() {
546        let c = cache(8, 0.9);
547        c.insert("s", &[1.0, 0.0], "a").unwrap();
548        let e = SemanticError::DimensionMismatch { expected: 2, found: 3 };
549        assert_eq!(c.lookup("s", &[1.0, 0.0, 0.0]), Err(e.clone()));
550        assert_eq!(c.insert("s", &[1.0, 0.0, 0.0], "b"), Err(e));
551        assert_eq!(c.remove_scope("s"), 1);
552        c.insert("s", &[1.0, 0.0, 0.0], "b").unwrap();
553
554        let fixed: SemanticCache<u8> = SemanticCache::with_config(SemanticConfig::new(4).with_dimension(4));
555        assert_eq!(fixed.insert("s", &[1.0, 2.0], 1), Err(SemanticError::DimensionMismatch { expected: 4, found: 2 }));
556        assert_eq!(fixed.lookup("new", &[1.0]), Err(SemanticError::DimensionMismatch { expected: 4, found: 1 }));
557        assert!(fixed.insert("s", &[1.0, 2.0, 3.0, 4.0], 1).is_ok());
558        assert_eq!(cosine_similarity(&[1.0], &[1.0, 0.0]), None);
559    }
560
561    #[test]
562    fn nan_zero_and_empty_embeddings_are_refused() {
563        let c = cache(8, 0.9);
564        assert_eq!(c.insert("s", &[], "a"), Err(SemanticError::Empty));
565        assert_eq!(c.insert("s", &[f32::NAN, 1.0], "a"), Err(SemanticError::NotFinite));
566        assert_eq!(c.insert("s", &[f32::INFINITY, 1.0], "a"), Err(SemanticError::NotFinite));
567        assert_eq!(c.insert("s", &[0.0, 0.0], "a"), Err(SemanticError::ZeroVector));
568        assert_eq!(c.insert("s", &[-0.0, 0.0], "a"), Err(SemanticError::ZeroVector));
569        assert!(c.is_empty());
570        c.insert("s", &[1.0, 0.0], "a").unwrap();
571        assert_eq!(c.lookup("s", &[f32::NAN, 0.0]), Err(SemanticError::NotFinite));
572        assert_eq!(c.lookup("s", &[0.0, 0.0]), Err(SemanticError::ZeroVector));
573        assert_eq!(c.stats().misses + c.stats().hits, 0, "refused lookups aren't counted");
574        assert_eq!(cosine_similarity(&[0.0, 0.0], &[1.0, 0.0]), None);
575        // A NaN threshold keeps the default; out-of-range ones clamp.
576        assert_eq!(SemanticConfig::new(1).with_threshold(f32::NAN).threshold, DEFAULT_THRESHOLD);
577        assert_eq!(SemanticConfig::new(1).with_threshold(3.0).threshold, 1.0);
578        // Large values don't overflow the norm.
579        assert!(normalize(&[f32::MAX, f32::MAX]).is_ok());
580    }
581
582    #[test]
583    fn entries_expire_after_the_ttl() {
584        let c: SemanticCache<&str> = SemanticCache::with_config(SemanticConfig::new(8).with_threshold(0.9).with_ttl(Duration::from_secs(60)));
585        let t0 = Instant::now();
586        c.insert_at("s", &[1.0, 0.0], "old", t0).unwrap();
587        c.insert_at("s", &[0.0, 1.0], "new", t0 + Duration::from_secs(30)).unwrap();
588        assert!(c.lookup_at("s", &[1.0, 0.0], t0 + Duration::from_secs(59)).unwrap().is_hit());
589        assert_eq!(c.lookup_at("s", &[1.0, 0.0], t0 + Duration::from_secs(60)).unwrap(), Lookup::Miss { best: Some(0.0) });
590        assert_eq!(c.len(), 1);
591        assert_eq!(c.stats().expired, 1);
592        // Re-inserting refreshes the age.
593        c.insert_at("s", &[0.0, 1.0], "new2", t0 + Duration::from_secs(80)).unwrap();
594        assert_eq!(c.lookup_at("s", &[0.0, 1.0], t0 + Duration::from_secs(130)).unwrap().into_value(), Some("new2"));
595        assert!(c.lookup_at("s", &[0.0, 1.0], t0 + Duration::from_secs(140)).unwrap().score().is_none());
596        assert!(c.is_empty());
597    }
598
599    #[test]
600    fn evicts_least_recently_used_across_scopes() {
601        let c = cache(2, 0.9);
602        c.insert("s", &[1.0, 0.0], "a").unwrap();
603        c.insert("t", &[0.0, 1.0], "b").unwrap();
604        assert!(c.lookup("s", &[1.0, 0.0]).unwrap().is_hit());
605        c.insert("s", &[0.0, 1.0], "c").unwrap();
606        assert_eq!(c.len(), 2);
607        assert!(c.lookup("s", &[1.0, 0.0]).unwrap().is_hit());
608        assert_eq!(c.lookup("t", &[0.0, 1.0]).unwrap(), Lookup::Miss { best: None });
609        assert_eq!(c.stats().evictions, 1);
610    }
611
612    #[test]
613    fn same_direction_replaces_instead_of_duplicating() {
614        let c = cache(4, 0.9);
615        let id = c.insert("s", &[1.0, 1.0], "a").unwrap();
616        assert_eq!(c.insert("s", &[3.0, 3.0], "b").unwrap(), id);
617        assert_eq!(c.len(), 1);
618        assert_eq!(c.lookup("s", &[1.0, 1.0]).unwrap().into_value(), Some("b"));
619    }
620
621    #[test]
622    fn remove_clear_and_stats() {
623        let c = cache(8, 0.9);
624        let a = c.insert("s", &[1.0, 0.0], "a").unwrap();
625        c.insert("s", &[0.0, 1.0], "b").unwrap();
626        c.insert("t", &[0.0, 1.0], "c").unwrap();
627        assert_eq!(c.remove(a), Some("a"));
628        assert_eq!(c.remove(a), None);
629        assert!(!c.lookup("s", &[1.0, 0.0]).unwrap().is_hit());
630        assert!(c.lookup("s", &[0.0, 1.0]).unwrap().is_hit());
631        let s = c.stats();
632        assert_eq!((s.entries, s.hits, s.misses, s.evictions, s.expired), (2, 1, 1, 0, 0));
633        assert_eq!(c.remove_scope("t"), 1);
634        assert_eq!(c.remove_scope("t"), 0);
635        c.clear();
636        assert!(c.is_empty());
637        assert_eq!(c.stats(), SemanticStats::default());
638    }
639
640    #[test]
641    fn snapshot_round_trips_answers() {
642        let config = SemanticConfig::new(8).with_threshold(0.9).with_ttl(Duration::from_secs(3600));
643        let c: SemanticCache = SemanticCache::with_config(config.clone());
644        c.insert("s", &[1.0, 0.0], CachedAnswer::new("m", "hello", "stop")).unwrap();
645        c.insert("t", &[0.0, 1.0], CachedAnswer::new("m", "other", "stop")).unwrap();
646        let bytes = c.snapshot().unwrap();
647        let back: SemanticCache = SemanticCache::restore(config, &bytes).unwrap();
648        assert_eq!(back.len(), 2);
649        assert_eq!(back.lookup("s", &[1.0, 0.01]).unwrap().into_value().map(|a| a.text), Some("hello".into()));
650        assert_eq!(back.stats().hits, 1);
651        // A smaller cache keeps the most recently used; a fixed dimension skips others.
652        let small: SemanticCache = SemanticCache::restore(SemanticConfig::new(1), &bytes).unwrap();
653        assert_eq!(small.len(), 1);
654        let fixed: SemanticCache = SemanticCache::restore(SemanticConfig::new(8).with_dimension(3), &bytes).unwrap();
655        assert!(fixed.is_empty());
656        assert!(matches!(SemanticCache::<CachedAnswer>::restore(SemanticConfig::new(1), &[0xff]), Err(SemanticError::Snapshot(_))));
657    }
658
659    #[test]
660    fn shared_across_threads() {
661        let c = std::sync::Arc::new(cache(64, 0.9));
662        let handles: Vec<_> = (0..4)
663            .map(|i| {
664                let c = c.clone();
665                std::thread::spawn(move || {
666                    let scope = format!("s{i}");
667                    c.insert(&scope, &[1.0, i as f32], "v").unwrap();
668                    assert!(c.lookup(&scope, &[1.0, i as f32]).unwrap().is_hit());
669                })
670            })
671            .collect();
672        for h in handles {
673            h.join().unwrap();
674        }
675        assert_eq!(c.len(), 4);
676    }
677}