Skip to main content

oxirs_chat/
response_cache.rs

1//! # RAG Response Cache
2//!
3//! An in-memory LRU cache for RAG (Retrieval-Augmented Generation) responses with:
4//!
5//! - **TTL-based expiry**: entries older than their TTL are transparently ignored.
6//! - **LRU eviction**: when the cache is full, the least-recently-used entry is dropped.
7//! - **Semantic-key hashing**: queries are hashed with FNV-1a so the key is a fixed-size `u64`.
8//! - **Hit/miss statistics**: monotonically incrementing counters for observability.
9//!
10//! ## Example
11//!
12//! ```rust
13//! use oxirs_chat::response_cache::ResponseCache;
14//!
15//! let mut cache = ResponseCache::new(100, 60_000); // capacity=100, ttl=1 min
16//! cache.put("What is RDF?", "RDF is a data model.".to_string(), 0);
17//! assert_eq!(
18//!     cache.get("What is RDF?", 30_000),
19//!     Some("RDF is a data model.".to_string())
20//! );
21//! assert!(cache.get("What is RDF?", 70_000).is_none()); // expired
22//! ```
23
24use std::collections::{HashMap, VecDeque};
25
26// ─── FNV-1a hash ──────────────────────────────────────────────────────────────
27
28/// FNV-1a 64-bit hash of a byte slice (no external crate required).
29fn fnv1a_hash(data: &[u8]) -> u64 {
30    const FNV_OFFSET_BASIS: u64 = 14_695_981_039_346_656_037;
31    const FNV_PRIME: u64 = 1_099_511_628_211;
32
33    let mut hash = FNV_OFFSET_BASIS;
34    for byte in data {
35        hash ^= *byte as u64;
36        hash = hash.wrapping_mul(FNV_PRIME);
37    }
38    hash
39}
40
41/// Compute the cache key hash for a query string.
42fn query_hash(query: &str) -> u64 {
43    fnv1a_hash(query.as_bytes())
44}
45
46// ─── Data structures ──────────────────────────────────────────────────────────
47
48/// A single entry stored in the response cache.
49#[derive(Debug, Clone)]
50pub struct CacheEntry {
51    /// FNV-1a hash of the original query string.
52    pub query_hash: u64,
53    /// The cached response text.
54    pub response: String,
55    /// Absolute timestamp (ms since epoch or monotonic reference) when stored.
56    pub created_at: u64,
57    /// Number of times this entry has been successfully retrieved.
58    pub access_count: usize,
59    /// Lifetime of this entry in milliseconds.
60    pub ttl_ms: u64,
61}
62
63impl CacheEntry {
64    /// Returns `true` if the entry has not yet expired relative to `now_ms`.
65    pub fn is_valid(&self, now_ms: u64) -> bool {
66        now_ms < self.created_at.saturating_add(self.ttl_ms)
67    }
68}
69
70/// Snapshot of cache performance counters.
71#[derive(Debug, Clone, Default)]
72pub struct CacheStats {
73    /// Number of successful cache lookups.
74    pub hits: u64,
75    /// Number of unsuccessful cache lookups (including expired entries).
76    pub misses: u64,
77    /// Number of entries evicted to make room for new ones.
78    pub evictions: u64,
79    /// Current number of live (potentially expired) entries in the cache.
80    pub entries: usize,
81}
82
83// ─── ResponseCache ────────────────────────────────────────────────────────────
84
85/// LRU cache for RAG responses with per-entry TTL.
86///
87/// Internally uses:
88/// - A `HashMap<u64, CacheEntry>` for O(1) lookup by hash.
89/// - A `VecDeque<u64>` that records insertion/access order for LRU eviction.
90pub struct ResponseCache {
91    capacity: usize,
92    default_ttl_ms: u64,
93    entries: HashMap<u64, CacheEntry>,
94    /// Front = most recently used, back = least recently used.
95    lru_order: VecDeque<u64>,
96    stats: CacheStats,
97}
98
99impl ResponseCache {
100    /// Create a new cache with the given `capacity` (maximum number of entries)
101    /// and `default_ttl_ms` (entry lifetime in milliseconds).
102    pub fn new(capacity: usize, default_ttl_ms: u64) -> Self {
103        Self {
104            capacity: capacity.max(1),
105            default_ttl_ms,
106            entries: HashMap::new(),
107            lru_order: VecDeque::new(),
108            stats: CacheStats::default(),
109        }
110    }
111
112    // ── public API ──────────────────────────────────────────────────────────
113
114    /// Look up a cached response for `query` at the given timestamp.
115    ///
116    /// - Returns `Some(response)` if an unexpired entry exists and updates
117    ///   `access_count` and the hit counter.
118    /// - Returns `None` (and increments the miss counter) otherwise.
119    pub fn get(&mut self, query: &str, now_ms: u64) -> Option<String> {
120        let key = query_hash(query);
121
122        match self.entries.get_mut(&key) {
123            Some(entry) if entry.is_valid(now_ms) => {
124                entry.access_count += 1;
125                self.stats.hits += 1;
126                let response = entry.response.clone();
127                // Move to front of LRU queue.
128                self.touch_lru(key);
129                Some(response)
130            }
131            _ => {
132                self.stats.misses += 1;
133                None
134            }
135        }
136    }
137
138    /// Insert or replace a cache entry for `query`.
139    ///
140    /// If the cache is at capacity, the least-recently-used entry is evicted first.
141    pub fn put(&mut self, query: &str, response: String, now_ms: u64) {
142        let key = query_hash(query);
143
144        // Evict if at capacity and this is a new key.
145        if !self.entries.contains_key(&key) && self.entries.len() >= self.capacity {
146            self.evict_lru();
147        }
148
149        // Remove old LRU position if key already exists.
150        if self.entries.contains_key(&key) {
151            self.lru_order.retain(|&k| k != key);
152        }
153
154        let entry = CacheEntry {
155            query_hash: key,
156            response,
157            created_at: now_ms,
158            access_count: 0,
159            ttl_ms: self.default_ttl_ms,
160        };
161
162        self.entries.insert(key, entry);
163        self.lru_order.push_front(key);
164        self.stats.entries = self.entries.len();
165    }
166
167    /// Remove the entry for `query` (if any).
168    ///
169    /// Returns `true` if an entry was actually removed.
170    pub fn invalidate(&mut self, query: &str) -> bool {
171        let key = query_hash(query);
172        if self.entries.remove(&key).is_some() {
173            self.lru_order.retain(|&k| k != key);
174            self.stats.entries = self.entries.len();
175            true
176        } else {
177            false
178        }
179    }
180
181    /// Remove all entries whose TTL has elapsed relative to `now_ms`.
182    ///
183    /// Returns the number of entries that were purged.
184    pub fn invalidate_expired(&mut self, now_ms: u64) -> usize {
185        let expired_keys: Vec<u64> = self
186            .entries
187            .iter()
188            .filter(|(_, e)| !e.is_valid(now_ms))
189            .map(|(k, _)| *k)
190            .collect();
191
192        let count = expired_keys.len();
193        for key in expired_keys {
194            self.entries.remove(&key);
195            self.lru_order.retain(|&k| k != key);
196        }
197
198        self.stats.entries = self.entries.len();
199        count
200    }
201
202    /// Return a reference to the current statistics.
203    pub fn stats(&self) -> &CacheStats {
204        &self.stats
205    }
206
207    /// Current number of stored entries (including potentially expired ones).
208    pub fn len(&self) -> usize {
209        self.entries.len()
210    }
211
212    /// Returns `true` when the cache contains no entries.
213    pub fn is_empty(&self) -> bool {
214        self.entries.is_empty()
215    }
216
217    /// Maximum number of entries the cache can hold.
218    pub fn capacity(&self) -> usize {
219        self.capacity
220    }
221
222    /// The default TTL applied to new entries.
223    pub fn default_ttl_ms(&self) -> u64 {
224        self.default_ttl_ms
225    }
226
227    /// Clear all entries and reset statistics.
228    pub fn clear(&mut self) {
229        self.entries.clear();
230        self.lru_order.clear();
231        self.stats = CacheStats::default();
232    }
233
234    // ── internal helpers ────────────────────────────────────────────────────
235
236    /// Move `key` to the front of the LRU deque (most-recently-used position).
237    fn touch_lru(&mut self, key: u64) {
238        self.lru_order.retain(|&k| k != key);
239        self.lru_order.push_front(key);
240    }
241
242    /// Remove the least-recently-used entry from the cache.
243    fn evict_lru(&mut self) {
244        if let Some(lru_key) = self.lru_order.pop_back() {
245            self.entries.remove(&lru_key);
246            self.stats.evictions += 1;
247            self.stats.entries = self.entries.len();
248        }
249    }
250}
251
252// ─── Tests ────────────────────────────────────────────────────────────────────
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    // ── FNV-1a hash ──────────────────────────────────────────────────────────
259
260    #[test]
261    fn test_hash_deterministic() {
262        assert_eq!(query_hash("hello"), query_hash("hello"));
263    }
264
265    #[test]
266    fn test_hash_different_inputs() {
267        assert_ne!(query_hash("hello"), query_hash("world"));
268    }
269
270    #[test]
271    fn test_hash_empty_string() {
272        let h = query_hash("");
273        // Should not panic and should return the FNV offset basis (no bytes mixed).
274        let _ = h;
275    }
276
277    // ── CacheEntry helpers ───────────────────────────────────────────────────
278
279    #[test]
280    fn test_entry_is_valid_before_expiry() {
281        let entry = CacheEntry {
282            query_hash: 1,
283            response: "r".to_string(),
284            created_at: 1000,
285            access_count: 0,
286            ttl_ms: 5000,
287        };
288        assert!(entry.is_valid(5999));
289    }
290
291    #[test]
292    fn test_entry_is_invalid_after_expiry() {
293        let entry = CacheEntry {
294            query_hash: 1,
295            response: "r".to_string(),
296            created_at: 1000,
297            access_count: 0,
298            ttl_ms: 5000,
299        };
300        assert!(!entry.is_valid(6001));
301    }
302
303    #[test]
304    fn test_entry_exact_boundary_invalid() {
305        let entry = CacheEntry {
306            query_hash: 1,
307            response: "r".to_string(),
308            created_at: 1000,
309            access_count: 0,
310            ttl_ms: 5000,
311        };
312        // now == created_at + ttl_ms  => NOT valid (strict <)
313        assert!(!entry.is_valid(6000));
314    }
315
316    // ── new ──────────────────────────────────────────────────────────────────
317
318    #[test]
319    fn test_new_cache_is_empty() {
320        let cache = ResponseCache::new(100, 60_000);
321        assert!(cache.is_empty());
322        assert_eq!(cache.len(), 0);
323    }
324
325    #[test]
326    fn test_new_cache_capacity_stored() {
327        let cache = ResponseCache::new(50, 10_000);
328        assert_eq!(cache.capacity(), 50);
329    }
330
331    #[test]
332    fn test_new_cache_ttl_stored() {
333        let cache = ResponseCache::new(50, 99_999);
334        assert_eq!(cache.default_ttl_ms(), 99_999);
335    }
336
337    // ── put / get ────────────────────────────────────────────────────────────
338
339    #[test]
340    fn test_basic_put_and_get() {
341        let mut cache = ResponseCache::new(10, 60_000);
342        cache.put("q1", "response1".to_string(), 0);
343        assert_eq!(cache.get("q1", 1000), Some("response1".to_string()));
344    }
345
346    #[test]
347    fn test_get_missing_returns_none() {
348        let mut cache = ResponseCache::new(10, 60_000);
349        assert!(cache.get("nonexistent", 0).is_none());
350    }
351
352    #[test]
353    fn test_get_after_ttl_expiry_returns_none() {
354        let mut cache = ResponseCache::new(10, 5_000);
355        cache.put("q", "r".to_string(), 0);
356        assert!(cache.get("q", 5_001).is_none());
357    }
358
359    #[test]
360    fn test_get_within_ttl_succeeds() {
361        let mut cache = ResponseCache::new(10, 5_000);
362        cache.put("q", "r".to_string(), 1000);
363        assert!(cache.get("q", 5_999).is_some());
364    }
365
366    #[test]
367    fn test_put_updates_existing_entry() {
368        let mut cache = ResponseCache::new(10, 60_000);
369        cache.put("q", "v1".to_string(), 0);
370        cache.put("q", "v2".to_string(), 0);
371        assert_eq!(cache.get("q", 0), Some("v2".to_string()));
372        assert_eq!(cache.len(), 1); // still one entry
373    }
374
375    #[test]
376    fn test_put_multiple_entries() {
377        let mut cache = ResponseCache::new(10, 60_000);
378        cache.put("q1", "r1".to_string(), 0);
379        cache.put("q2", "r2".to_string(), 0);
380        cache.put("q3", "r3".to_string(), 0);
381        assert_eq!(cache.len(), 3);
382    }
383
384    // ── LRU eviction ─────────────────────────────────────────────────────────
385
386    #[test]
387    fn test_eviction_at_capacity() {
388        let mut cache = ResponseCache::new(3, 60_000);
389        cache.put("q1", "r1".to_string(), 0);
390        cache.put("q2", "r2".to_string(), 0);
391        cache.put("q3", "r3".to_string(), 0);
392        // Access q1 to make q2 the LRU
393        cache.get("q1", 0);
394        // Insert q4 — should evict q2 (LRU)
395        cache.put("q4", "r4".to_string(), 0);
396        assert_eq!(cache.len(), 3);
397        assert!(cache.get("q2", 0).is_none()); // evicted
398        assert!(cache.get("q1", 0).is_some()); // not evicted
399        assert!(cache.get("q3", 0).is_some()); // not evicted
400        assert!(cache.get("q4", 0).is_some()); // not evicted
401    }
402
403    #[test]
404    fn test_eviction_counter_increments() {
405        let mut cache = ResponseCache::new(2, 60_000);
406        cache.put("q1", "r1".to_string(), 0);
407        cache.put("q2", "r2".to_string(), 0);
408        cache.put("q3", "r3".to_string(), 0); // evicts one
409        assert_eq!(cache.stats().evictions, 1);
410    }
411
412    #[test]
413    fn test_no_eviction_within_capacity() {
414        let mut cache = ResponseCache::new(5, 60_000);
415        cache.put("q1", "r1".to_string(), 0);
416        cache.put("q2", "r2".to_string(), 0);
417        assert_eq!(cache.stats().evictions, 0);
418    }
419
420    // ── invalidate ───────────────────────────────────────────────────────────
421
422    #[test]
423    fn test_invalidate_existing_returns_true() {
424        let mut cache = ResponseCache::new(10, 60_000);
425        cache.put("q", "r".to_string(), 0);
426        assert!(cache.invalidate("q"));
427    }
428
429    #[test]
430    fn test_invalidate_missing_returns_false() {
431        let mut cache = ResponseCache::new(10, 60_000);
432        assert!(!cache.invalidate("nonexistent"));
433    }
434
435    #[test]
436    fn test_invalidate_removes_entry() {
437        let mut cache = ResponseCache::new(10, 60_000);
438        cache.put("q", "r".to_string(), 0);
439        cache.invalidate("q");
440        assert!(cache.get("q", 0).is_none());
441        assert_eq!(cache.len(), 0);
442    }
443
444    #[test]
445    fn test_invalidate_allows_reinsertion() {
446        let mut cache = ResponseCache::new(10, 60_000);
447        cache.put("q", "r1".to_string(), 0);
448        cache.invalidate("q");
449        cache.put("q", "r2".to_string(), 0);
450        assert_eq!(cache.get("q", 0), Some("r2".to_string()));
451    }
452
453    // ── invalidate_expired ───────────────────────────────────────────────────
454
455    #[test]
456    fn test_invalidate_expired_removes_stale() {
457        let mut cache = ResponseCache::new(10, 1_000);
458        cache.put("q1", "r1".to_string(), 0);
459        cache.put("q2", "r2".to_string(), 0);
460        let purged = cache.invalidate_expired(2_000); // both expired
461        assert_eq!(purged, 2);
462        assert!(cache.is_empty());
463    }
464
465    #[test]
466    fn test_invalidate_expired_keeps_fresh() {
467        let mut cache = ResponseCache::new(10, 10_000);
468        cache.put("q1", "r1".to_string(), 0); // expires at 10000
469        cache.put("q2", "r2".to_string(), 5_000); // expires at 15000
470        let purged = cache.invalidate_expired(11_000); // q1 expired, q2 fresh
471        assert_eq!(purged, 1);
472        assert_eq!(cache.len(), 1);
473        assert!(cache.get("q2", 11_000).is_some());
474    }
475
476    #[test]
477    fn test_invalidate_expired_none_expired() {
478        let mut cache = ResponseCache::new(10, 60_000);
479        cache.put("q", "r".to_string(), 0);
480        let purged = cache.invalidate_expired(1_000);
481        assert_eq!(purged, 0);
482        assert_eq!(cache.len(), 1);
483    }
484
485    #[test]
486    fn test_invalidate_expired_empty_cache() {
487        let mut cache = ResponseCache::new(10, 60_000);
488        assert_eq!(cache.invalidate_expired(0), 0);
489    }
490
491    // ── stats ────────────────────────────────────────────────────────────────
492
493    #[test]
494    fn test_stats_initial_zeros() {
495        let cache = ResponseCache::new(10, 60_000);
496        let s = cache.stats();
497        assert_eq!(s.hits, 0);
498        assert_eq!(s.misses, 0);
499        assert_eq!(s.evictions, 0);
500        assert_eq!(s.entries, 0);
501    }
502
503    #[test]
504    fn test_stats_hit_increments() {
505        let mut cache = ResponseCache::new(10, 60_000);
506        cache.put("q", "r".to_string(), 0);
507        cache.get("q", 0);
508        assert_eq!(cache.stats().hits, 1);
509    }
510
511    #[test]
512    fn test_stats_miss_increments() {
513        let mut cache = ResponseCache::new(10, 60_000);
514        cache.get("q", 0);
515        assert_eq!(cache.stats().misses, 1);
516    }
517
518    #[test]
519    fn test_stats_miss_on_expired() {
520        let mut cache = ResponseCache::new(10, 1_000);
521        cache.put("q", "r".to_string(), 0);
522        cache.get("q", 2_000); // expired => miss
523        assert_eq!(cache.stats().misses, 1);
524        assert_eq!(cache.stats().hits, 0);
525    }
526
527    #[test]
528    fn test_stats_entries_tracks_len() {
529        let mut cache = ResponseCache::new(10, 60_000);
530        cache.put("q1", "r1".to_string(), 0);
531        cache.put("q2", "r2".to_string(), 0);
532        assert_eq!(cache.stats().entries, 2);
533        cache.invalidate("q1");
534        assert_eq!(cache.stats().entries, 1);
535    }
536
537    // ── access_count ─────────────────────────────────────────────────────────
538
539    #[test]
540    fn test_access_count_increments_on_hit() {
541        let mut cache = ResponseCache::new(10, 60_000);
542        cache.put("q", "r".to_string(), 0);
543        cache.get("q", 0);
544        cache.get("q", 0);
545        let entry = cache.entries.get(&query_hash("q")).expect("entry exists");
546        assert_eq!(entry.access_count, 2);
547    }
548
549    // ── len / is_empty ───────────────────────────────────────────────────────
550
551    #[test]
552    fn test_is_empty_after_clear() {
553        let mut cache = ResponseCache::new(10, 60_000);
554        cache.put("q", "r".to_string(), 0);
555        cache.clear();
556        assert!(cache.is_empty());
557    }
558
559    #[test]
560    fn test_len_after_clear() {
561        let mut cache = ResponseCache::new(10, 60_000);
562        cache.put("q1", "r1".to_string(), 0);
563        cache.put("q2", "r2".to_string(), 0);
564        cache.clear();
565        assert_eq!(cache.len(), 0);
566    }
567
568    // ── clear ────────────────────────────────────────────────────────────────
569
570    #[test]
571    fn test_clear_resets_stats() {
572        let mut cache = ResponseCache::new(10, 60_000);
573        cache.put("q", "r".to_string(), 0);
574        cache.get("q", 0);
575        cache.clear();
576        assert_eq!(cache.stats().hits, 0);
577        assert_eq!(cache.stats().entries, 0);
578    }
579
580    // ── capacity guard ───────────────────────────────────────────────────────
581
582    #[test]
583    fn test_minimum_capacity_is_one() {
584        let cache = ResponseCache::new(0, 60_000);
585        assert_eq!(cache.capacity(), 1);
586    }
587
588    #[test]
589    fn test_large_capacity() {
590        let cache = ResponseCache::new(100_000, 3_600_000);
591        assert_eq!(cache.capacity(), 100_000);
592    }
593
594    // ── LRU ordering after multiple accesses ──────────────────────────────────
595
596    #[test]
597    fn test_lru_order_after_access() {
598        let mut cache = ResponseCache::new(3, 60_000);
599        cache.put("q1", "r1".to_string(), 0);
600        cache.put("q2", "r2".to_string(), 0);
601        cache.put("q3", "r3".to_string(), 0);
602        // Access q1 — now q2 is LRU
603        cache.get("q1", 0);
604        cache.get("q3", 0);
605        // q2 is LRU; inserting q4 should evict q2
606        cache.put("q4", "r4".to_string(), 0);
607        assert!(cache.get("q2", 0).is_none());
608        assert!(cache.get("q1", 0).is_some());
609        assert!(cache.get("q3", 0).is_some());
610        assert!(cache.get("q4", 0).is_some());
611    }
612
613    // ── edge cases ───────────────────────────────────────────────────────────
614
615    #[test]
616    fn test_zero_ttl_always_expired() {
617        let mut cache = ResponseCache::new(10, 0);
618        cache.put("q", "r".to_string(), 0);
619        // now_ms == 0, created_at == 0, ttl == 0 => 0 < 0 is false => expired
620        assert!(cache.get("q", 0).is_none());
621    }
622
623    #[test]
624    fn test_very_large_ttl() {
625        let mut cache = ResponseCache::new(10, u64::MAX / 2);
626        cache.put("q", "r".to_string(), 0);
627        assert!(cache.get("q", u64::MAX / 4).is_some());
628    }
629}