ares-rag 0.9.1

Retrieval-augmented generation pipeline for ARES
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
//! Embedding Cache for RAG Pipeline
//!
//! This module provides caching for text embeddings to avoid re-computing
//! vectors for unchanged content. This is especially valuable for:
//!
//! - Large document re-indexing
//! - Frequently accessed documents
//! - Multi-collection setups with shared documents
//!
//! # Cache Key Strategy
//!
//! Cache keys are computed as SHA-256 hashes of `text + model_name` to ensure:
//! - Unique keys for different content
//! - Model-specific embeddings (different models produce different vectors)
//! - Consistent keys across restarts
//!
//! # Implementation
//!
//! Uses the `lru` crate for O(1) get/put operations with proper LRU eviction.
//! The cache is thread-safe via `parking_lot::Mutex`.
//!
//! # Example
//!
//! ```ignore
//! use ares::rag::cache::{EmbeddingCache, LruEmbeddingCache, CacheConfig};
//!
//! // Create a cache with 512MB max size
//! let cache = LruEmbeddingCache::new(CacheConfig {
//!     max_size_bytes: 512 * 1024 * 1024,
//!     ..Default::default()
//! });
//!
//! // Check cache before computing embedding
//! let key = cache.compute_key("hello world", "bge-small-en-v1.5");
//! if let Some(embedding) = cache.get(&key).await {
//!     // Use cached embedding
//! } else {
//!     // Compute and cache
//!     let embedding = embed("hello world").await?;
//!     cache.set(&key, embedding.clone(), None).await?;
//! }
//! ```

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

use lru::LruCache;
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use ares_types::types::Result;

// ============================================================================
// Cache Types
// ============================================================================

/// Statistics for cache performance monitoring
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CacheStats {
    /// Number of cache hits
    pub hits: u64,
    /// Number of cache misses
    pub misses: u64,
    /// Current size in bytes (approximate)
    pub size_bytes: u64,
    /// Number of entries in cache
    pub entry_count: usize,
    /// Number of evictions due to capacity
    pub evictions: u64,
}

impl CacheStats {
    /// Calculate hit rate as a percentage
    pub fn hit_rate(&self) -> f64 {
        let total = self.hits + self.misses;
        if total == 0 {
            0.0
        } else {
            (self.hits as f64 / total as f64) * 100.0
        }
    }
}

/// Configuration for the embedding cache
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    /// Maximum cache size in bytes (default: 256MB)
    #[serde(default = "default_max_size_bytes")]
    pub max_size_bytes: u64,

    /// Default TTL for cache entries (None = no expiry)
    #[serde(default)]
    pub default_ttl: Option<Duration>,

    /// Whether the cache is enabled
    #[serde(default = "default_enabled")]
    pub enabled: bool,
}

fn default_max_size_bytes() -> u64 {
    256 * 1024 * 1024 // 256 MB
}

fn default_enabled() -> bool {
    true
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_size_bytes: default_max_size_bytes(),
            default_ttl: None,
            enabled: default_enabled(),
        }
    }
}

// ============================================================================
// Cache Trait
// ============================================================================

/// Trait for embedding cache implementations
///
/// This trait defines the interface for caching embeddings. Implementations
/// can use different backends (in-memory, Redis, disk, etc.).
pub trait EmbeddingCache: Send + Sync {
    /// Get an embedding from the cache
    fn get(&self, key: &str) -> Option<Vec<f32>>;

    /// Store an embedding in the cache with optional TTL
    fn set(&self, key: &str, embedding: Vec<f32>, ttl: Option<Duration>) -> Result<()>;

    /// Remove an entry from the cache
    fn invalidate(&self, key: &str) -> Result<()>;

    /// Clear all entries from the cache
    fn clear(&self) -> Result<()>;

    /// Get cache statistics
    fn stats(&self) -> CacheStats;

    /// Compute a cache key for the given text and model
    fn compute_key(&self, text: &str, model: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(text.as_bytes());
        hasher.update(b"|");
        hasher.update(model.as_bytes());
        format!("{:x}", hasher.finalize())
    }

    /// Check if the cache is enabled
    fn is_enabled(&self) -> bool;
}

// ============================================================================
// LRU Cache Entry
// ============================================================================

/// A cache entry with metadata for expiration
#[derive(Debug, Clone)]
struct CacheEntry {
    /// The cached embedding vector
    embedding: Vec<f32>,
    /// Optional expiry time
    expires_at: Option<Instant>,
    /// Size in bytes (approximate)
    size_bytes: usize,
}

impl CacheEntry {
    fn new(embedding: Vec<f32>, ttl: Option<Duration>) -> Self {
        let now = Instant::now();
        let size_bytes = embedding.len() * std::mem::size_of::<f32>();
        Self {
            embedding,
            expires_at: ttl.map(|d| now + d),
            size_bytes,
        }
    }

    fn is_expired(&self) -> bool {
        self.expires_at
            .map(|exp| Instant::now() > exp)
            .unwrap_or(false)
    }
}

// ============================================================================
// LRU Embedding Cache
// ============================================================================

/// Default maximum number of entries in the LRU cache
const DEFAULT_MAX_ENTRIES: usize = 10_000;

/// In-memory LRU cache for embeddings
///
/// Uses the `lru` crate for O(1) get/put operations with proper LRU eviction.
/// Thread-safe via `parking_lot::Mutex`.
///
/// # Memory Management
///
/// The cache limits entries by count (not bytes) for simplicity and O(1) operations.
/// The `max_size_bytes` config is used to estimate max entries based on average
/// embedding size (assuming 384-dimensional embeddings = 1536 bytes each).
pub struct LruEmbeddingCache {
    /// The LRU cache storage (key -> CacheEntry)
    cache: Mutex<LruCache<String, CacheEntry>>,
    /// Configuration
    config: CacheConfig,
    /// Current size in bytes (approximate)
    current_size: AtomicU64,
    /// Cache hit counter
    hits: AtomicU64,
    /// Cache miss counter
    misses: AtomicU64,
    /// Eviction counter
    evictions: AtomicU64,
}

impl LruEmbeddingCache {
    /// Create a new LRU embedding cache with the given configuration
    pub fn new(config: CacheConfig) -> Self {
        // Estimate max entries from max_size_bytes
        // Assume average embedding is 384 dimensions = 1536 bytes
        let avg_entry_size = 384 * std::mem::size_of::<f32>(); // 1536 bytes
        let max_entries = (config.max_size_bytes as usize / avg_entry_size).max(100);
        let capacity = NonZeroUsize::new(max_entries)
            .unwrap_or(NonZeroUsize::new(DEFAULT_MAX_ENTRIES).unwrap());

        Self {
            cache: Mutex::new(LruCache::new(capacity)),
            config,
            current_size: AtomicU64::new(0),
            hits: AtomicU64::new(0),
            misses: AtomicU64::new(0),
            evictions: AtomicU64::new(0),
        }
    }

    /// Create a cache with default configuration
    pub fn with_defaults() -> Self {
        Self::new(CacheConfig::default())
    }

    /// Create a cache with a specific max size in bytes
    pub fn with_max_size(max_size_bytes: u64) -> Self {
        Self::new(CacheConfig {
            max_size_bytes,
            ..Default::default()
        })
    }

    /// Create a cache with a specific max entry count
    pub fn with_max_entries(max_entries: usize) -> Self {
        let capacity = NonZeroUsize::new(max_entries)
            .unwrap_or(NonZeroUsize::new(DEFAULT_MAX_ENTRIES).unwrap());
        Self {
            cache: Mutex::new(LruCache::new(capacity)),
            config: CacheConfig::default(),
            current_size: AtomicU64::new(0),
            hits: AtomicU64::new(0),
            misses: AtomicU64::new(0),
            evictions: AtomicU64::new(0),
        }
    }

    /// Remove expired entries from the cache
    pub fn cleanup_expired(&self) {
        let mut cache = self.cache.lock();
        let mut expired_keys = Vec::new();

        // Collect expired keys (can't remove while iterating)
        for (key, entry) in cache.iter() {
            if entry.is_expired() {
                expired_keys.push(key.clone());
            }
        }

        // Remove expired entries
        for key in expired_keys {
            if let Some(entry) = cache.pop(&key) {
                self.current_size
                    .fetch_sub(entry.size_bytes as u64, Ordering::Relaxed);
            }
        }
    }

    /// Get the current cache size in bytes
    pub fn size_bytes(&self) -> u64 {
        self.current_size.load(Ordering::Relaxed)
    }

    /// Get the number of entries in the cache
    pub fn len(&self) -> usize {
        self.cache.lock().len()
    }

    /// Check if the cache is empty
    pub fn is_empty(&self) -> bool {
        self.cache.lock().is_empty()
    }
}

impl EmbeddingCache for LruEmbeddingCache {
    fn get(&self, key: &str) -> Option<Vec<f32>> {
        if !self.config.enabled {
            return None;
        }

        let mut cache = self.cache.lock();

        // get() in lru crate automatically promotes to most recently used
        if let Some(entry) = cache.get(key) {
            if entry.is_expired() {
                // Remove expired entry
                let entry = cache.pop(key).unwrap();
                self.current_size
                    .fetch_sub(entry.size_bytes as u64, Ordering::Relaxed);
                self.misses.fetch_add(1, Ordering::Relaxed);
                return None;
            }
            self.hits.fetch_add(1, Ordering::Relaxed);
            Some(entry.embedding.clone())
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
            None
        }
    }

    fn set(&self, key: &str, embedding: Vec<f32>, ttl: Option<Duration>) -> Result<()> {
        if !self.config.enabled {
            return Ok(());
        }

        let entry = CacheEntry::new(embedding, ttl.or(self.config.default_ttl));
        let entry_size = entry.size_bytes;

        let mut cache = self.cache.lock();

        // Remove old entry if exists (to update size tracking)
        if let Some(old_entry) = cache.pop(key) {
            self.current_size
                .fetch_sub(old_entry.size_bytes as u64, Ordering::Relaxed);
        }

        // Check if cache is at capacity before push
        let was_at_capacity = cache.len() == cache.cap().get();

        // Push new entry (LRU eviction happens automatically if at capacity)
        if let Some((_, evicted)) = cache.push(key.to_string(), entry) {
            // An entry was evicted
            self.current_size
                .fetch_sub(evicted.size_bytes as u64, Ordering::Relaxed);
            self.evictions.fetch_add(1, Ordering::Relaxed);
        } else if was_at_capacity {
            // We were at capacity but push didn't return evicted (shouldn't happen)
            // but handle it just in case
            self.evictions.fetch_add(1, Ordering::Relaxed);
        }

        // Update size
        self.current_size
            .fetch_add(entry_size as u64, Ordering::Relaxed);

        Ok(())
    }

    fn invalidate(&self, key: &str) -> Result<()> {
        let mut cache = self.cache.lock();
        if let Some(entry) = cache.pop(key) {
            self.current_size
                .fetch_sub(entry.size_bytes as u64, Ordering::Relaxed);
        }
        Ok(())
    }

    fn clear(&self) -> Result<()> {
        let mut cache = self.cache.lock();
        cache.clear();
        self.current_size.store(0, Ordering::Relaxed);
        Ok(())
    }

    fn stats(&self) -> CacheStats {
        CacheStats {
            hits: self.hits.load(Ordering::Relaxed),
            misses: self.misses.load(Ordering::Relaxed),
            size_bytes: self.current_size.load(Ordering::Relaxed),
            entry_count: self.cache.lock().len(),
            evictions: self.evictions.load(Ordering::Relaxed),
        }
    }

    fn is_enabled(&self) -> bool {
        self.config.enabled
    }
}

// ============================================================================
// No-Op Cache
// ============================================================================

/// A no-op cache that doesn't store anything
///
/// Useful for disabling caching without changing the code structure.
#[derive(Debug, Default)]
pub struct NoOpCache;

impl NoOpCache {
    /// Create a new no-op cache
    pub fn new() -> Self {
        Self
    }
}

impl EmbeddingCache for NoOpCache {
    fn get(&self, _key: &str) -> Option<Vec<f32>> {
        None
    }

    fn set(&self, _key: &str, _embedding: Vec<f32>, _ttl: Option<Duration>) -> Result<()> {
        Ok(())
    }

    fn invalidate(&self, _key: &str) -> Result<()> {
        Ok(())
    }

    fn clear(&self) -> Result<()> {
        Ok(())
    }

    fn stats(&self) -> CacheStats {
        CacheStats::default()
    }

    fn is_enabled(&self) -> bool {
        false
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    #[test]
    fn test_cache_concurrent_reads_and_writes() {
        use std::sync::Arc;
        use std::thread;

        let cache = Arc::new(LruEmbeddingCache::with_max_entries(100));
        let mut handles = Vec::new();
        for i in 0..8 {
            let cache = Arc::clone(&cache);
            handles.push(thread::spawn(move || {
                let key = format!("key-{i}");
                let embedding = vec![i as f32; 4];
                cache.set(&key, embedding, None).unwrap();
                for _ in 0..10 {
                    let _ = cache.get(&key);
                }
            }));
        }
        for h in handles {
            h.join().unwrap();
        }
        assert!(cache.len() > 0);
    }

    use super::*;

    #[test]
    fn test_cache_key_computation() {
        let cache = LruEmbeddingCache::with_defaults();

        let key1 = cache.compute_key("hello world", "bge-small-en-v1.5");
        let key2 = cache.compute_key("hello world", "bge-small-en-v1.5");
        let key3 = cache.compute_key("hello world", "bge-base-en-v1.5");
        let key4 = cache.compute_key("different text", "bge-small-en-v1.5");

        // Same input should produce same key
        assert_eq!(key1, key2);
        // Different model should produce different key
        assert_ne!(key1, key3);
        // Different text should produce different key
        assert_ne!(key1, key4);
    }

    #[test]
    fn test_cache_set_and_get() {
        let cache = LruEmbeddingCache::with_defaults();
        let key = "test_key";
        let embedding = vec![1.0, 2.0, 3.0, 4.0];

        // Initially empty
        assert!(cache.get(key).is_none());
        assert_eq!(cache.stats().misses, 1);

        // Set and get
        cache.set(key, embedding.clone(), None).unwrap();
        let retrieved = cache.get(key);

        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap(), embedding);
        assert_eq!(cache.stats().hits, 1);
    }

    #[test]
    fn test_cache_invalidate() {
        let cache = LruEmbeddingCache::with_defaults();
        let key = "test_key";
        let embedding = vec![1.0, 2.0, 3.0];

        cache.set(key, embedding, None).unwrap();
        assert!(cache.get(key).is_some());

        cache.invalidate(key).unwrap();
        assert!(cache.get(key).is_none());
    }

    #[test]
    fn test_cache_clear() {
        let cache = LruEmbeddingCache::with_defaults();

        cache.set("key1", vec![1.0, 2.0], None).unwrap();
        cache.set("key2", vec![3.0, 4.0], None).unwrap();

        assert_eq!(cache.len(), 2);
        assert!(cache.size_bytes() > 0);

        cache.clear().unwrap();

        assert_eq!(cache.len(), 0);
        assert_eq!(cache.size_bytes(), 0);
    }

    #[test]
    fn test_cache_lru_eviction() {
        // Create a small cache with exactly 2 entries to test LRU eviction
        let cache = LruEmbeddingCache::with_max_entries(2);

        let embedding1 = vec![1.0, 2.0, 3.0, 4.0];
        let embedding2 = vec![5.0, 6.0, 7.0, 8.0];
        let embedding3 = vec![9.0, 10.0, 11.0, 12.0];

        cache.set("key1", embedding1.clone(), None).unwrap();
        cache.set("key2", embedding2.clone(), None).unwrap();

        // Both should be present
        assert!(cache.get("key1").is_some());
        assert!(cache.get("key2").is_some());

        // Adding a third should evict the LRU (key1, since key2 was accessed more recently)
        cache.set("key3", embedding3.clone(), None).unwrap();

        // key1 should be evicted
        assert!(cache.get("key1").is_none());
        // key2 and key3 should exist
        assert!(cache.get("key2").is_some());
        assert!(cache.get("key3").is_some());

        assert!(cache.stats().evictions > 0);
    }

    #[test]
    fn test_cache_ttl_expiry() {
        let cache = LruEmbeddingCache::with_defaults();
        let key = "test_key";
        let embedding = vec![1.0, 2.0, 3.0];

        // Set with 0 duration TTL (immediate expiry)
        cache
            .set(key, embedding, Some(Duration::from_nanos(1)))
            .unwrap();

        // Sleep briefly to ensure expiry
        std::thread::sleep(Duration::from_millis(1));

        // Should be expired
        assert!(cache.get(key).is_none());
    }

    #[test]
    fn test_cache_stats() {
        let cache = LruEmbeddingCache::with_defaults();

        // Generate some activity
        cache.set("key1", vec![1.0, 2.0], None).unwrap();
        let _ = cache.get("key1"); // hit
        let _ = cache.get("key2"); // miss
        let _ = cache.get("key3"); // miss

        let stats = cache.stats();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.misses, 2);
        assert_eq!(stats.entry_count, 1);
        assert!(stats.size_bytes > 0);
    }

    #[test]
    fn test_cache_hit_rate() {
        let stats = CacheStats {
            hits: 75,
            misses: 25,
            size_bytes: 0,
            entry_count: 0,
            evictions: 0,
        };

        assert!((stats.hit_rate() - 75.0).abs() < 0.001);
    }

    #[test]
    fn test_noop_cache() {
        let cache = NoOpCache::new();

        // Set should succeed but not store
        cache.set("key", vec![1.0, 2.0], None).unwrap();

        // Get should always return None
        assert!(cache.get("key").is_none());

        // Stats should be empty
        let stats = cache.stats();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
        assert!(!cache.is_enabled());
    }

    #[test]
    fn test_cache_disabled() {
        let cache = LruEmbeddingCache::new(CacheConfig {
            enabled: false,
            ..Default::default()
        });

        // Set should succeed but not store
        cache.set("key", vec![1.0, 2.0], None).unwrap();

        // Get should return None when disabled
        assert!(cache.get("key").is_none());
        assert!(!cache.is_enabled());
    }

    #[test]
    fn test_cache_update_existing() {
        let cache = LruEmbeddingCache::with_defaults();
        let key = "test_key";

        cache.set(key, vec![1.0, 2.0], None).unwrap();
        let size1 = cache.size_bytes();

        // Update with different embedding
        cache.set(key, vec![3.0, 4.0, 5.0, 6.0], None).unwrap();
        let size2 = cache.size_bytes();

        // Size should have changed (old removed, new added)
        assert!(size2 > size1);
        assert_eq!(cache.len(), 1);

        // Should get the new value
        let retrieved = cache.get(key).unwrap();
        assert_eq!(retrieved, vec![3.0, 4.0, 5.0, 6.0]);
    }
    #[test]
    fn test_cache_hit_rate_zero_requests() {
        let stats = CacheStats::default();
        assert_eq!(stats.hit_rate(), 0.0);
    }

    #[test]
    fn test_cache_cleanup_expired() {
        let cache = LruEmbeddingCache::with_max_entries(10);
        cache
            .set("expired", vec![1.0], Some(Duration::from_nanos(1)))
            .unwrap();
        cache.set("fresh", vec![2.0], None).unwrap();
        std::thread::sleep(Duration::from_millis(2));
        cache.cleanup_expired();
        assert!(cache.get("expired").is_none());
        assert!(cache.get("fresh").is_some());
    }

    #[test]
    fn test_cache_with_max_size_constructor() {
        let cache = LruEmbeddingCache::with_max_size(10_000);
        assert!(cache.is_empty());
        cache.set("k", vec![1.0; 8], None).unwrap();
        assert_eq!(cache.len(), 1);
    }

    #[test]
    fn test_cache_is_empty() {
        let cache = LruEmbeddingCache::with_defaults();
        assert!(cache.is_empty());
        cache.set("k", vec![1.0], None).unwrap();
        assert!(!cache.is_empty());
    }

    #[test]
    fn test_cache_config_serde_roundtrip() {
        let config = CacheConfig {
            max_size_bytes: 1024,
            default_ttl: Some(Duration::from_secs(60)),
            enabled: true,
        };
        let parsed: CacheConfig = serde_json::from_str(&serde_json::to_string(&config).unwrap())
            .unwrap();
        assert_eq!(parsed.max_size_bytes, 1024);
        assert!(parsed.enabled);
        assert_eq!(parsed.default_ttl, Some(Duration::from_secs(60)));
    }

    #[test]
    fn test_cache_get_drops_expired_entry() {
        let cache = LruEmbeddingCache::with_defaults();
        cache
            .set("k", vec![1.0, 2.0], Some(Duration::from_nanos(1)))
            .unwrap();
        std::thread::sleep(Duration::from_millis(2));
        assert!(cache.get("k").is_none());
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_noop_cache_invalidate_and_clear() {
        let cache = NoOpCache::new();
        cache.invalidate("missing").unwrap();
        cache.clear().unwrap();
    }

    #[test]
    fn test_cache_stats_serde_roundtrip() {
        let stats = CacheStats {
            hits: 10,
            misses: 5,
            size_bytes: 4096,
            entry_count: 3,
            evictions: 2,
        };
        let parsed: CacheStats =
            serde_json::from_str(&serde_json::to_string(&stats).unwrap()).unwrap();
        assert_eq!(parsed.hits, 10);
        assert_eq!(parsed.misses, 5);
        assert_eq!(parsed.size_bytes, 4096);
        assert_eq!(parsed.entry_count, 3);
        assert_eq!(parsed.evictions, 2);
        assert!((parsed.hit_rate() - stats.hit_rate()).abs() < f64::EPSILON);
    }

    #[test]
    fn test_cache_config_serde_defaults() {
        let parsed: CacheConfig = serde_json::from_str("{}").unwrap();
        assert_eq!(parsed.max_size_bytes, 256 * 1024 * 1024);
        assert!(parsed.enabled);
        assert_eq!(parsed.default_ttl, None);

        let partial: CacheConfig =
            serde_json::from_str(r#"{"enabled":false,"max_size_bytes":512}"#).unwrap();
        assert!(!partial.enabled);
        assert_eq!(partial.max_size_bytes, 512);
        assert_eq!(partial.default_ttl, None);
    }

    #[test]
    fn test_cache_key_sha256_properties() {
        let cache = LruEmbeddingCache::with_defaults();

        let mut hasher = Sha256::new();
        hasher.update(b"hello");
        hasher.update(b"|");
        hasher.update(b"model");
        let expected = format!("{:x}", hasher.finalize());

        let key = cache.compute_key("hello", "model");
        assert_eq!(key, expected);
        assert_eq!(key.len(), 64);
        assert!(key.chars().all(|c| c.is_ascii_hexdigit()));

        assert_eq!(cache.compute_key("", ""), cache.compute_key("", ""));
        assert_ne!(cache.compute_key("", ""), cache.compute_key("", "x"));
        // Pipe separator is ambiguous when text or model contain '|'.
        assert_eq!(
            cache.compute_key("a|b", "c"),
            cache.compute_key("a", "b|c")
        );
        assert_ne!(
            cache.compute_key("hello", "model-a"),
            cache.compute_key("hello", "model-b")
        );
        assert_ne!(cache.compute_key("α", "m"), cache.compute_key("a", "m"));
    }

    #[test]
    fn test_cache_uses_config_default_ttl() {
        let cache = LruEmbeddingCache::new(CacheConfig {
            default_ttl: Some(Duration::from_nanos(1)),
            ..Default::default()
        });

        cache.set("k", vec![1.0, 2.0], None).unwrap();
        std::thread::sleep(Duration::from_millis(2));

        assert!(cache.get("k").is_none());
        assert_eq!(cache.stats().misses, 1);
    }

    #[test]
    fn test_cache_lru_get_promotes_entry() {
        let cache = LruEmbeddingCache::with_max_entries(2);

        cache.set("key1", vec![1.0], None).unwrap();
        cache.set("key2", vec![2.0], None).unwrap();

        // Promote key1 so key2 becomes LRU before inserting key3.
        assert!(cache.get("key1").is_some());

        cache.set("key3", vec![3.0], None).unwrap();

        assert!(cache.get("key1").is_some());
        assert!(cache.get("key3").is_some());
        assert!(cache.get("key2").is_none());
        assert!(cache.stats().evictions >= 1);
    }

    #[test]
    fn test_cache_invalidate_missing_key_is_noop() {
        let cache = LruEmbeddingCache::with_defaults();
        cache.set("present", vec![1.0, 2.0], None).unwrap();

        let bytes_before = cache.size_bytes();
        let len_before = cache.len();

        cache.invalidate("absent").unwrap();

        assert_eq!(cache.size_bytes(), bytes_before);
        assert_eq!(cache.len(), len_before);
        assert!(cache.get("present").is_some());
    }

    #[test]
    fn test_cache_cleanup_expired_noop_when_fresh() {
        let cache = LruEmbeddingCache::with_max_entries(4);
        cache.set("fresh", vec![1.0, 2.0], None).unwrap();

        cache.cleanup_expired();

        assert_eq!(cache.len(), 1);
        assert!(cache.get("fresh").is_some());
    }

    /// Mock in-memory backend for trait-level integration tests.
    struct MockEmbeddingCache {
        store: Mutex<std::collections::HashMap<String, Vec<f32>>>,
    }

    impl MockEmbeddingCache {
        fn new() -> Self {
            Self {
                store: Mutex::new(std::collections::HashMap::new()),
            }
        }
    }

    impl EmbeddingCache for MockEmbeddingCache {
        fn get(&self, key: &str) -> Option<Vec<f32>> {
            self.store.lock().get(key).cloned()
        }

        fn set(&self, key: &str, embedding: Vec<f32>, _ttl: Option<Duration>) -> Result<()> {
            self.store.lock().insert(key.to_string(), embedding);
            Ok(())
        }

        fn invalidate(&self, key: &str) -> Result<()> {
            self.store.lock().remove(key);
            Ok(())
        }

        fn clear(&self) -> Result<()> {
            self.store.lock().clear();
            Ok(())
        }

        fn stats(&self) -> CacheStats {
            CacheStats {
                entry_count: self.store.lock().len(),
                ..Default::default()
            }
        }

        fn is_enabled(&self) -> bool {
            true
        }
    }

    fn exercise_embedding_cache(cache: &dyn EmbeddingCache) {
        let key = cache.compute_key("integration text", "test-model");
        assert!(cache.get(&key).is_none());

        let embedding = vec![0.1, 0.2, 0.3];
        cache.set(&key, embedding.clone(), None).unwrap();
        assert_eq!(cache.get(&key), Some(embedding));

        cache.invalidate(&key).unwrap();
        assert!(cache.get(&key).is_none());

        cache.set(&key, vec![9.0], None).unwrap();
        cache.clear().unwrap();
        assert!(cache.get(&key).is_none());
        assert_eq!(cache.stats().entry_count, 0);
    }

    #[test]
    fn test_mock_storage_backend_integration() {
        exercise_embedding_cache(&MockEmbeddingCache::new());
    }

    #[test]
    fn test_lru_cache_trait_object_integration() {
        let cache: Box<dyn EmbeddingCache> = Box::new(LruEmbeddingCache::with_max_entries(8));
        exercise_embedding_cache(cache.as_ref());
        assert!(cache.is_enabled());
    }


}