memd 1.9.0

Local memory CLI for AI agents with hybrid retrieval
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
//! Semantic query cache with similarity-based lookup
//!
//! The SemanticCache provides sub-millisecond response for repeated or similar queries
//! by caching query embeddings alongside their results. Cache entries are invalidated
//! via TTL or when the underlying data version changes.

use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use moka::sync::Cache;
use parking_lot::RwLock;
use sha2::{Digest, Sha256};

use crate::types::{ChunkId, TenantId};

/// Configuration for the semantic cache
#[derive(Debug, Clone)]
pub struct SemanticCacheConfig {
    /// Cosine similarity threshold for cache hit (default 0.85)
    pub similarity_threshold: f32,
    /// TTL in seconds (default 2700 = 45 minutes)
    pub ttl_seconds: u64,
    /// Maximum number of cache entries (default 10_000)
    pub max_entries: u64,
    /// Confidence boost on each cache hit (default 0.1)
    pub confidence_boost_on_hit: f32,
    /// Confidence decay rate per hour (default 0.05)
    pub confidence_decay_rate: f32,
}

impl Default for SemanticCacheConfig {
    fn default() -> Self {
        Self {
            similarity_threshold: 0.85,
            ttl_seconds: 2700, // 45 minutes (middle of 30-60 range)
            max_entries: 10_000,
            confidence_boost_on_hit: 0.1,
            confidence_decay_rate: 0.05,
        }
    }
}

/// A cached search result with minimal data for quick response
#[derive(Debug, Clone)]
pub struct CachedResult {
    /// The chunk ID
    pub chunk_id: ChunkId,
    /// Similarity/relevance score
    pub score: f32,
    /// Preview of text content (first 200 chars)
    pub text_preview: String,
}

/// A cache entry storing query results with version tracking
#[derive(Debug, Clone)]
pub struct CacheEntry {
    /// The query embedding that produced these results
    pub query_embedding: Vec<f32>,
    /// Cached search results
    pub results: Vec<CachedResult>,
    /// Tenant that owns this cache entry
    pub tenant_id: TenantId,
    /// Optional project scope
    pub project_id: Option<String>,
    /// Memory version at time of caching (for invalidation)
    pub memory_version: u64,
    /// When this entry was created (Unix ms)
    pub created_at: i64,
    /// When this entry was last hit (Unix ms)
    pub last_hit: i64,
    /// Number of cache hits
    pub hit_count: u32,
    /// Confidence score (0.0-1.0)
    pub confidence: f32,
}

/// Result returned on a cache hit
#[derive(Debug, Clone)]
pub struct CacheHit {
    /// The cached results
    pub results: Vec<CachedResult>,
    /// Cosine similarity between query and cached query
    pub similarity: f32,
    /// Current confidence of the cache entry
    pub confidence: f32,
    /// Age of the cache entry in milliseconds
    pub age_ms: u64,
    /// Key used to identify this cache entry
    pub cache_key: String,
}

/// Internal cache value with retrieval metadata.
#[derive(Debug, Clone)]
struct CacheRecord {
    entry: CacheEntry,
    retrieval_limit: usize,
}

/// Index entry for fast similarity lookup
struct QueryIndexEntry {
    /// Cache key for lookup in moka cache
    cache_key: String,
    /// Query embedding for similarity computation
    embedding: Vec<f32>,
    /// Tenant for filtering
    tenant_id: TenantId,
    /// Optional project for filtering
    project_id: Option<String>,
}

/// Cache statistics
#[derive(Debug, Clone, Default)]
pub struct CacheStats {
    /// Total number of lookup attempts
    pub total_lookups: u64,
    /// Number of cache hits
    pub cache_hits: u64,
    /// Number of cache misses
    pub cache_misses: u64,
    /// Number of version-based invalidations
    pub version_invalidations: u64,
    /// Number of TTL expirations (tracked via moka eviction listener)
    pub ttl_expirations: u64,
    /// Average confidence across all entries
    pub avg_confidence: f32,
    /// Current number of entries
    pub entry_count: usize,
}

/// Atomic counters for thread-safe statistics
struct AtomicStats {
    total_lookups: AtomicU64,
    cache_hits: AtomicU64,
    cache_misses: AtomicU64,
    version_invalidations: AtomicU64,
    ttl_expirations: AtomicU64,
}

impl Default for AtomicStats {
    fn default() -> Self {
        Self {
            total_lookups: AtomicU64::new(0),
            cache_hits: AtomicU64::new(0),
            cache_misses: AtomicU64::new(0),
            version_invalidations: AtomicU64::new(0),
            ttl_expirations: AtomicU64::new(0),
        }
    }
}

/// Semantic query cache with similarity-based lookup
///
/// Caches query embeddings and their results, allowing similar queries
/// to be served from cache. Entries are invalidated via TTL or version tracking.
pub struct SemanticCache {
    /// Moka cache with TTL-based expiration
    entries: Cache<String, CacheRecord>,
    /// Index for similarity search (protected by RwLock)
    query_index: RwLock<Vec<QueryIndexEntry>>,
    /// Configuration
    config: SemanticCacheConfig,
    /// Atomic statistics counters
    stats: AtomicStats,
}

impl SemanticCache {
    /// Create a new semantic cache with the given configuration
    pub fn new(config: SemanticCacheConfig) -> Self {
        let entries = Cache::builder()
            .max_capacity(config.max_entries)
            .time_to_live(Duration::from_secs(config.ttl_seconds))
            .build();

        Self {
            entries,
            query_index: RwLock::new(Vec::new()),
            config,
            stats: AtomicStats::default(),
        }
    }

    /// Look up a similar query in the cache
    ///
    /// Returns a cache hit if a similar query (cosine > threshold) is found
    /// and the cache entry's version is >= current_version.
    pub fn lookup(
        &self,
        query_embedding: &[f32],
        tenant_id: &TenantId,
        project_id: Option<&str>,
        current_version: u64,
    ) -> Option<CacheHit> {
        self.lookup_with_limit(query_embedding, tenant_id, project_id, current_version, 0)
    }

    /// Look up a similar query with enough coverage for `requested_limit`.
    pub(crate) fn lookup_with_limit(
        &self,
        query_embedding: &[f32],
        tenant_id: &TenantId,
        project_id: Option<&str>,
        current_version: u64,
        requested_limit: usize,
    ) -> Option<CacheHit> {
        self.stats.total_lookups.fetch_add(1, Ordering::Relaxed);

        let now_ms = current_time_ms();
        let query_index = self.query_index.read();

        // Find best matching entry above threshold
        let mut best_match: Option<(String, f32)> = None;

        for entry in query_index.iter() {
            // Filter by tenant
            if entry.tenant_id != *tenant_id {
                continue;
            }

            // Filter by project (None matches None, Some matches Some)
            match (&entry.project_id, project_id) {
                (None, None) => {}
                (Some(a), Some(b)) if a == b => {}
                _ => continue,
            }

            // Compute similarity
            let similarity = cosine_similarity(query_embedding, &entry.embedding);
            if similarity >= self.config.similarity_threshold
                && best_match.as_ref().is_none_or(|(_, s)| similarity > *s)
            {
                best_match = Some((entry.cache_key.clone(), similarity));
            }
        }

        drop(query_index);

        // Check if the cached entry is still valid
        let (cache_key, similarity) = best_match?;
        let mut record = self.entries.get(&cache_key)?;

        // Version check: entry must be from current or newer version
        if record.entry.memory_version < current_version {
            self.stats
                .version_invalidations
                .fetch_add(1, Ordering::Relaxed);
            self.stats.cache_misses.fetch_add(1, Ordering::Relaxed);
            return None;
        }

        // Reuse results only when the cached search requested at least this limit.
        if record.retrieval_limit < requested_limit {
            self.stats.cache_misses.fetch_add(1, Ordering::Relaxed);
            return None;
        }

        // Update hit statistics
        record.entry.last_hit = now_ms;
        record.entry.hit_count += 1;
        record.entry.confidence =
            (record.entry.confidence + self.config.confidence_boost_on_hit).min(1.0);

        // Re-insert with updated stats
        self.entries.insert(cache_key.clone(), record.clone());

        self.stats.cache_hits.fetch_add(1, Ordering::Relaxed);

        Some(CacheHit {
            results: record.entry.results.clone(),
            similarity,
            confidence: record.entry.confidence,
            age_ms: (now_ms - record.entry.created_at).max(0) as u64,
            cache_key,
        })
    }

    /// Insert a new cache entry
    pub fn insert(
        &self,
        query_embedding: Vec<f32>,
        tenant_id: TenantId,
        project_id: Option<String>,
        results: Vec<CachedResult>,
        memory_version: u64,
    ) {
        let retrieval_limit = results.len();
        self.insert_with_limit(
            query_embedding,
            tenant_id,
            project_id,
            results,
            memory_version,
            retrieval_limit,
        );
    }

    /// Insert results produced by a search with the given retrieval limit.
    pub(crate) fn insert_with_limit(
        &self,
        query_embedding: Vec<f32>,
        tenant_id: TenantId,
        project_id: Option<String>,
        results: Vec<CachedResult>,
        memory_version: u64,
        retrieval_limit: usize,
    ) {
        let cache_key = embedding_hash(&query_embedding, &tenant_id, project_id.as_deref());
        let now_ms = current_time_ms();

        let entry = CacheEntry {
            query_embedding: query_embedding.clone(),
            results,
            tenant_id: tenant_id.clone(),
            project_id: project_id.clone(),
            memory_version,
            created_at: now_ms,
            last_hit: now_ms,
            hit_count: 0,
            confidence: 0.5, // Initial confidence
        };

        // Add to moka cache
        self.entries.insert(
            cache_key.clone(),
            CacheRecord {
                entry,
                retrieval_limit,
            },
        );

        // Add to query index
        let index_entry = QueryIndexEntry {
            cache_key,
            embedding: query_embedding,
            tenant_id,
            project_id,
        };

        let mut query_index = self.query_index.write();
        if let Some(existing) = query_index
            .iter_mut()
            .find(|existing| existing.cache_key == index_entry.cache_key)
        {
            *existing = index_entry;
        } else {
            query_index.push(index_entry);
        }
    }

    /// Invalidate all cache entries for a tenant
    pub fn invalidate_tenant(&self, tenant_id: &TenantId) {
        let mut query_index = self.query_index.write();
        let keys_to_remove: Vec<String> = query_index
            .iter()
            .filter(|e| e.tenant_id == *tenant_id)
            .map(|e| e.cache_key.clone())
            .collect();

        for key in &keys_to_remove {
            self.entries.invalidate(key);
        }

        query_index.retain(|e| e.tenant_id != *tenant_id);
    }

    /// Invalidate cache entries below the given version
    pub fn invalidate_by_version(&self, tenant_id: &TenantId, min_version: u64) {
        let mut query_index = self.query_index.write();
        let mut keys_to_remove = Vec::new();

        for entry in query_index.iter() {
            if entry.tenant_id == *tenant_id {
                if let Some(cached) = self.entries.get(&entry.cache_key) {
                    if cached.entry.memory_version < min_version {
                        keys_to_remove.push(entry.cache_key.clone());
                    }
                }
            }
        }

        for key in &keys_to_remove {
            self.entries.invalidate(key);
            self.stats
                .version_invalidations
                .fetch_add(1, Ordering::Relaxed);
        }

        query_index.retain(|e| !keys_to_remove.contains(&e.cache_key));
    }

    /// Invalidate cache entries containing any of the given chunk IDs
    pub fn invalidate_chunks(&self, chunk_ids: &[ChunkId]) {
        let mut query_index = self.query_index.write();
        let mut keys_to_remove = Vec::new();

        for entry in query_index.iter() {
            if let Some(cached) = self.entries.get(&entry.cache_key) {
                let contains_chunk = cached
                    .entry
                    .results
                    .iter()
                    .any(|r| chunk_ids.contains(&r.chunk_id));
                if contains_chunk {
                    keys_to_remove.push(entry.cache_key.clone());
                }
            }
        }

        for key in &keys_to_remove {
            self.entries.invalidate(key);
        }

        query_index.retain(|e| !keys_to_remove.contains(&e.cache_key));
    }

    /// Get current cache statistics
    pub fn get_stats(&self) -> CacheStats {
        let query_index = self.query_index.read();
        let entry_count = query_index.len();

        // Calculate average confidence
        let mut total_confidence = 0.0f32;
        let mut count = 0u32;

        for entry in query_index.iter() {
            if let Some(cached) = self.entries.get(&entry.cache_key) {
                total_confidence += cached.entry.confidence;
                count += 1;
            }
        }

        let avg_confidence = if count > 0 {
            total_confidence / count as f32
        } else {
            0.0
        };

        CacheStats {
            total_lookups: self.stats.total_lookups.load(Ordering::Relaxed),
            cache_hits: self.stats.cache_hits.load(Ordering::Relaxed),
            cache_misses: self.stats.cache_misses.load(Ordering::Relaxed),
            version_invalidations: self.stats.version_invalidations.load(Ordering::Relaxed),
            ttl_expirations: self.stats.ttl_expirations.load(Ordering::Relaxed),
            avg_confidence,
            entry_count,
        }
    }

    /// Remove index entries that are no longer in the moka cache
    ///
    /// This should be called periodically to clean up expired entries from the index.
    pub fn prune_index(&self) {
        let mut query_index = self.query_index.write();
        let before_count = query_index.len();

        query_index.retain(|e| self.entries.contains_key(&e.cache_key));

        let removed = before_count - query_index.len();
        if removed > 0 {
            self.stats
                .ttl_expirations
                .fetch_add(removed as u64, Ordering::Relaxed);
        }
    }
}

/// Compute cosine similarity between two vectors
///
/// Returns 0.0 for zero vectors to handle edge cases gracefully.
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() || a.is_empty() {
        return 0.0;
    }

    let mut dot_product = 0.0f32;
    let mut norm_a = 0.0f32;
    let mut norm_b = 0.0f32;

    for (x, y) in a.iter().zip(b.iter()) {
        dot_product += x * y;
        norm_a += x * x;
        norm_b += y * y;
    }

    let norm_a = norm_a.sqrt();
    let norm_b = norm_b.sqrt();

    if norm_a == 0.0 || norm_b == 0.0 {
        return 0.0;
    }

    dot_product / (norm_a * norm_b)
}

/// Generate a hash-based cache key from embedding and tenant info
fn embedding_hash(embedding: &[f32], tenant_id: &TenantId, project_id: Option<&str>) -> String {
    let mut hasher = Sha256::new();

    let tenant = tenant_id.as_str().as_bytes();
    hasher.update((tenant.len() as u64).to_le_bytes());
    hasher.update(tenant);

    match project_id {
        None => hasher.update([0]),
        Some(project) => {
            hasher.update([1]);
            hasher.update((project.len() as u64).to_le_bytes());
            hasher.update(project.as_bytes());
        }
    }

    // Include embedding bytes
    for val in embedding {
        hasher.update(val.to_le_bytes());
    }

    let result = hasher.finalize();
    // Use first 16 bytes (32 hex chars) for reasonable uniqueness
    hex::encode(&result[..16])
}

/// Get current time in milliseconds since Unix epoch
fn current_time_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

/// Hex encoding helper (avoiding extra dependency)
mod hex {
    pub fn encode(bytes: &[u8]) -> String {
        bytes.iter().map(|b| format!("{:02x}", b)).collect()
    }
}

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

    fn make_tenant(name: &str) -> TenantId {
        TenantId::new(name).unwrap()
    }

    fn make_embedding(seed: u64) -> Vec<f32> {
        // Create a simple normalized embedding for testing
        let mut vec: Vec<f32> = (0..384)
            .map(|i| ((seed + i) % 100) as f32 / 100.0)
            .collect();
        let norm: f32 = vec.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm > 0.0 {
            for v in &mut vec {
                *v /= norm;
            }
        }
        vec
    }

    fn make_similar_embedding(base: &[f32], noise: f32) -> Vec<f32> {
        // Create an embedding similar to base with some noise
        let mut vec = base.to_vec();
        for (i, v) in vec.iter_mut().enumerate() {
            *v += (i as f32 * noise).sin() * noise;
        }
        // Renormalize
        let norm: f32 = vec.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm > 0.0 {
            for v in &mut vec {
                *v /= norm;
            }
        }
        vec
    }

    fn make_chunk_id() -> ChunkId {
        ChunkId::new()
    }

    fn make_result(chunk_id: &ChunkId) -> Vec<CachedResult> {
        vec![CachedResult {
            chunk_id: chunk_id.clone(),
            score: 1.0,
            text_preview: String::new(),
        }]
    }

    #[test]
    fn test_cache_hit_flow() {
        let config = SemanticCacheConfig::default();
        let cache = SemanticCache::new(config);

        let tenant = make_tenant("test_tenant");
        let embedding = make_embedding(42);
        let chunk_id = make_chunk_id();

        let results = vec![CachedResult {
            chunk_id: chunk_id.clone(),
            score: 0.95,
            text_preview: "Test content".to_string(),
        }];

        // Insert entry with version 1
        cache.insert(embedding.clone(), tenant.clone(), None, results.clone(), 1);

        // Lookup with similar query should hit
        let similar = make_similar_embedding(&embedding, 0.01);
        let hit = cache.lookup(&similar, &tenant, None, 1);
        assert!(hit.is_some(), "Similar query should hit cache");

        let hit = hit.unwrap();
        assert!(
            hit.similarity > 0.85,
            "Similarity should be above threshold"
        );
        assert_eq!(hit.results.len(), 1);

        // Lookup with dissimilar query should miss
        let dissimilar = make_embedding(999);
        let miss = cache.lookup(&dissimilar, &tenant, None, 1);
        assert!(miss.is_none(), "Dissimilar query should miss cache");

        // Check hit count was incremented
        let stats = cache.get_stats();
        assert_eq!(stats.cache_hits, 1);
        assert_eq!(stats.cache_misses, 0);
        assert_eq!(stats.total_lookups, 2);
    }

    #[test]
    fn test_version_invalidation() {
        let config = SemanticCacheConfig::default();
        let cache = SemanticCache::new(config);

        let tenant = make_tenant("test_tenant");
        let embedding = make_embedding(42);
        let chunk_id = make_chunk_id();

        let results = vec![CachedResult {
            chunk_id,
            score: 0.95,
            text_preview: "Test content".to_string(),
        }];

        // Insert entry with version 5
        cache.insert(embedding.clone(), tenant.clone(), None, results, 5);

        // Lookup with current_version 5 should hit
        let hit = cache.lookup(&embedding, &tenant, None, 5);
        assert!(hit.is_some(), "Version 5 lookup should hit");

        // Lookup with current_version 6 should miss (stale)
        let miss = cache.lookup(&embedding, &tenant, None, 6);
        assert!(miss.is_none(), "Version 6 lookup should miss (stale entry)");

        // Call invalidate_by_version
        cache.invalidate_by_version(&tenant, 6);

        // Verify entry removed from index
        let stats = cache.get_stats();
        assert_eq!(stats.entry_count, 0);
    }

    #[test]
    fn test_tenant_isolation() {
        let config = SemanticCacheConfig::default();
        let cache = SemanticCache::new(config);

        let tenant_a = make_tenant("tenant_a");
        let tenant_b = make_tenant("tenant_b");
        let embedding = make_embedding(42);
        let chunk_id = make_chunk_id();

        let results = vec![CachedResult {
            chunk_id,
            score: 0.95,
            text_preview: "Test content".to_string(),
        }];

        // Insert entry for tenant_a
        cache.insert(embedding.clone(), tenant_a.clone(), None, results, 1);

        // Lookup as tenant_b should miss
        let miss = cache.lookup(&embedding, &tenant_b, None, 1);
        assert!(miss.is_none(), "Tenant B should not see Tenant A's cache");

        // Lookup as tenant_a should hit
        let hit = cache.lookup(&embedding, &tenant_a, None, 1);
        assert!(hit.is_some(), "Tenant A should see its own cache");
    }

    #[test]
    fn test_confidence_mechanics() {
        let config = SemanticCacheConfig {
            confidence_boost_on_hit: 0.1,
            ..Default::default()
        };
        let cache = SemanticCache::new(config);

        let tenant = make_tenant("test_tenant");
        let embedding = make_embedding(42);
        let chunk_id = make_chunk_id();

        let results = vec![CachedResult {
            chunk_id,
            score: 0.95,
            text_preview: "Test content".to_string(),
        }];

        // Insert entry (initial confidence 0.5)
        cache.insert(embedding.clone(), tenant.clone(), None, results, 1);

        // First hit
        let hit1 = cache.lookup(&embedding, &tenant, None, 1).unwrap();
        assert!(
            (hit1.confidence - 0.6).abs() < 0.01,
            "Confidence should be 0.6 after first hit"
        );

        // Second hit
        let hit2 = cache.lookup(&embedding, &tenant, None, 1).unwrap();
        assert!(
            (hit2.confidence - 0.7).abs() < 0.01,
            "Confidence should be 0.7 after second hit"
        );

        // Third hit
        let hit3 = cache.lookup(&embedding, &tenant, None, 1).unwrap();
        assert!(
            (hit3.confidence - 0.8).abs() < 0.01,
            "Confidence should be 0.8 after third hit"
        );
    }

    #[test]
    fn test_result_limit_controls_cache_acceptance() {
        let cache = SemanticCache::new(SemanticCacheConfig::default());
        let tenant = make_tenant("test_tenant");
        let embedding = make_embedding(42);
        let results = [make_chunk_id(), make_chunk_id()]
            .iter()
            .map(|chunk_id| CachedResult {
                chunk_id: chunk_id.clone(),
                score: 0.9,
                text_preview: String::new(),
            })
            .collect();

        cache.insert_with_limit(embedding.clone(), tenant.clone(), None, results, 1, 3);

        let repeat = cache
            .lookup_with_limit(&embedding, &tenant, None, 1, 3)
            .unwrap();
        assert_eq!(repeat.results.len(), 2);

        let smaller = cache
            .lookup_with_limit(&embedding, &tenant, None, 1, 2)
            .unwrap();
        assert_eq!(smaller.results.len(), 2);

        let confidence_before_miss = cache.get_stats().avg_confidence;
        assert!(cache
            .lookup_with_limit(&embedding, &tenant, None, 1, 5)
            .is_none());

        let stats = cache.get_stats();
        assert_eq!(stats.total_lookups, 3);
        assert_eq!(stats.cache_hits, 2);
        assert_eq!(stats.cache_misses, 1);
        assert!((stats.avg_confidence - confidence_before_miss).abs() < f32::EPSILON);
    }

    #[test]
    fn test_chunk_invalidation() {
        let config = SemanticCacheConfig::default();
        let cache = SemanticCache::new(config);

        let tenant = make_tenant("test_tenant");
        let embedding = make_embedding(42);
        let chunk_a = make_chunk_id();
        let chunk_b = make_chunk_id();

        let results = vec![
            CachedResult {
                chunk_id: chunk_a.clone(),
                score: 0.95,
                text_preview: "Content A".to_string(),
            },
            CachedResult {
                chunk_id: chunk_b.clone(),
                score: 0.85,
                text_preview: "Content B".to_string(),
            },
        ];

        // Insert entry with results containing chunk_a
        cache.insert(embedding.clone(), tenant.clone(), None, results, 1);

        // Verify entry exists
        let hit = cache.lookup(&embedding, &tenant, None, 1);
        assert!(hit.is_some());

        // Invalidate chunk_a
        cache.invalidate_chunks(&[chunk_a]);

        // Verify entry removed
        let miss = cache.lookup(&embedding, &tenant, None, 1);
        assert!(
            miss.is_none(),
            "Entry should be removed after chunk invalidation"
        );

        let stats = cache.get_stats();
        assert_eq!(stats.entry_count, 0);
    }

    #[test]
    fn test_project_isolation() {
        let config = SemanticCacheConfig::default();
        let cache = SemanticCache::new(config);

        let tenant = make_tenant("test_tenant");
        let embedding = make_embedding(42);
        let chunk_id = make_chunk_id();

        let results = vec![CachedResult {
            chunk_id,
            score: 0.95,
            text_preview: "Test content".to_string(),
        }];

        // Insert entry for project_a
        cache.insert(
            embedding.clone(),
            tenant.clone(),
            Some("project_a".to_string()),
            results.clone(),
            1,
        );

        // Lookup with project_b should miss
        let miss = cache.lookup(&embedding, &tenant, Some("project_b"), 1);
        assert!(miss.is_none(), "Project B should not see Project A's cache");

        // Lookup with project_a should hit
        let hit = cache.lookup(&embedding, &tenant, Some("project_a"), 1);
        assert!(hit.is_some(), "Project A should see its own cache");

        // Lookup with no project should miss
        let miss_no_project = cache.lookup(&embedding, &tenant, None, 1);
        assert!(
            miss_no_project.is_none(),
            "No project should not see Project A's cache"
        );
    }

    #[test]
    fn test_cache_keys_isolate_ambiguous_scopes() {
        let cache = SemanticCache::new(SemanticCacheConfig::default());
        let embedding = make_embedding(42);
        let scopes = [
            (make_tenant("ab"), Some("c".to_string()), make_chunk_id()),
            (make_tenant("a"), Some("bc".to_string()), make_chunk_id()),
            (make_tenant("scope"), None, make_chunk_id()),
            (make_tenant("scope"), Some(String::new()), make_chunk_id()),
        ];

        for (tenant, project, chunk_id) in &scopes {
            cache.insert(
                embedding.clone(),
                tenant.clone(),
                project.clone(),
                make_result(chunk_id),
                1,
            );
        }
        assert_eq!(cache.get_stats().entry_count, 4);
        for (tenant, project, chunk_id) in &scopes {
            let hit = cache
                .lookup(&embedding, tenant, project.as_deref(), 1)
                .unwrap();
            assert_eq!(&hit.results[0].chunk_id, chunk_id);
        }
    }

    #[test]
    fn test_cache_replacement_keeps_index_bounded() {
        let cache = SemanticCache::new(SemanticCacheConfig::default());
        let embedding = make_embedding(42);
        let tenant = make_tenant("test_tenant");
        let first = make_chunk_id();
        let replacement = make_chunk_id();

        cache.insert(
            embedding.clone(),
            tenant.clone(),
            None,
            make_result(&first),
            1,
        );
        cache.insert(
            embedding.clone(),
            tenant.clone(),
            None,
            make_result(&replacement),
            1,
        );

        assert_eq!(cache.get_stats().entry_count, 1);
        let hit = cache.lookup(&embedding, &tenant, None, 1).unwrap();
        assert_eq!(hit.results[0].chunk_id, replacement);
    }

    #[test]
    fn test_cosine_similarity() {
        // Identical vectors should have similarity 1.0
        let a = vec![1.0, 0.0, 0.0];
        assert!((cosine_similarity(&a, &a) - 1.0).abs() < 0.001);

        // Orthogonal vectors should have similarity 0.0
        let b = vec![0.0, 1.0, 0.0];
        assert!(cosine_similarity(&a, &b).abs() < 0.001);

        // Opposite vectors should have similarity -1.0
        let c = vec![-1.0, 0.0, 0.0];
        assert!((cosine_similarity(&a, &c) - (-1.0)).abs() < 0.001);

        // Zero vectors should return 0.0
        let zero = vec![0.0, 0.0, 0.0];
        assert_eq!(cosine_similarity(&a, &zero), 0.0);
        assert_eq!(cosine_similarity(&zero, &a), 0.0);

        // Different length vectors should return 0.0
        let d = vec![1.0, 0.0];
        assert_eq!(cosine_similarity(&a, &d), 0.0);
    }

    #[test]
    fn test_prune_index() {
        // Use very short TTL for testing
        let config = SemanticCacheConfig {
            ttl_seconds: 1,
            ..Default::default()
        };
        let cache = SemanticCache::new(config);

        let tenant = make_tenant("test_tenant");
        let embedding = make_embedding(42);
        let chunk_id = make_chunk_id();

        let results = vec![CachedResult {
            chunk_id,
            score: 0.95,
            text_preview: "Test content".to_string(),
        }];

        cache.insert(embedding, tenant, None, results, 1);

        // Wait for TTL to expire
        std::thread::sleep(std::time::Duration::from_secs(2));

        // Prune should remove expired entries from index
        cache.prune_index();

        let stats = cache.get_stats();
        assert_eq!(stats.entry_count, 0, "Expired entries should be pruned");
    }

    #[test]
    fn test_stats_tracking() {
        let config = SemanticCacheConfig::default();
        let cache = SemanticCache::new(config);

        let tenant = make_tenant("test_tenant");
        let embedding1 = make_embedding(42);
        let embedding2 = make_embedding(999);
        let chunk_id = make_chunk_id();

        let results = vec![CachedResult {
            chunk_id,
            score: 0.95,
            text_preview: "Test content".to_string(),
        }];

        cache.insert(embedding1.clone(), tenant.clone(), None, results, 1);

        // Hit
        cache.lookup(&embedding1, &tenant, None, 1);
        // Miss (dissimilar)
        cache.lookup(&embedding2, &tenant, None, 1);

        let stats = cache.get_stats();
        assert_eq!(stats.total_lookups, 2);
        assert_eq!(stats.cache_hits, 1);
        assert_eq!(stats.cache_misses, 0); // Dissimilar query doesn't increment miss counter
        assert_eq!(stats.entry_count, 1);
    }
}