Skip to main content

vtcode_core/cache/
mod.rs

1//! Unified caching system for VT Code
2//!
3//! This module provides a consolidated caching framework that replaces
4//! the multiple duplicate cache implementations throughout the codebase.
5//!
6//! Uses interior mutability with `RwLock` to allow `&self` methods,
7//! following the pattern from matklad's "Caches in Rust" article.
8
9use anyhow::Result;
10use rustc_hash::FxHashMap;
11use serde::{Deserialize, Serialize};
12use std::sync::{Arc, RwLock};
13use std::time::{Duration, SystemTime};
14
15/// Default TTL for cache entries (2 minutes for memory-constrained environments)
16pub const DEFAULT_CACHE_TTL: Duration = Duration::from_secs(120);
17
18/// Default maximum cache capacity (reduced from 10,000 to 1,000 for memory efficiency)
19pub const DEFAULT_MAX_CACHE_CAPACITY: usize = 1_000;
20
21/// Maximum number of items to return in context-limited operations
22pub const MAX_CONTEXT_ITEMS: usize = 5;
23
24/// Unified cache key trait for all cache types
25pub trait CacheKey: Send + Sync + std::hash::Hash + Eq + Clone + 'static {
26    fn to_cache_key(&self) -> String;
27}
28
29/// Unified cache value trait
30pub trait CacheValue: Send + Sync + Clone + 'static {}
31
32impl<T> CacheValue for T where T: Send + Sync + Clone + 'static {}
33
34/// Cache statistics with consistent structure across all cache types
35#[derive(Debug, Clone, Serialize, Deserialize, Default)]
36pub struct CacheStats {
37    pub hits: u64,
38    pub misses: u64,
39    pub evictions: u64,
40    pub current_size: usize,
41    pub max_size: usize,
42    pub total_memory_bytes: u64,
43}
44
45/// Cache entry with metadata
46#[derive(Debug, Clone)]
47pub struct CacheEntry<V> {
48    pub value: Arc<V>,
49    pub created_at: SystemTime,
50    pub last_accessed: SystemTime,
51    pub access_count: u64,
52    pub size_bytes: u64,
53}
54
55impl<V> CacheEntry<V> {
56    pub fn new(value: V, size_bytes: u64) -> Self {
57        Self::from_arc(Arc::new(value), size_bytes)
58    }
59
60    pub fn from_arc(value: Arc<V>, size_bytes: u64) -> Self {
61        let now = SystemTime::now();
62        Self {
63            value,
64            created_at: now,
65            last_accessed: now,
66            access_count: 1,
67            size_bytes,
68        }
69    }
70
71    pub fn mark_accessed(&mut self) {
72        self.last_accessed = SystemTime::now();
73        self.access_count += 1;
74    }
75
76    pub fn is_expired(&self, ttl: Duration) -> bool {
77        SystemTime::now()
78            .duration_since(self.created_at)
79            .map(|age| age > ttl)
80            .unwrap_or(true)
81    }
82}
83
84/// Unified cache backend with configurable eviction policies
85///
86/// Uses interior mutability via `RwLock` to allow `&self` methods,
87/// enabling easier use in concurrent contexts without borrow checker conflicts.
88pub struct UnifiedCache<K, V> {
89    inner: RwLock<UnifiedCacheInner<K, V>>,
90}
91
92/// Internal state for `UnifiedCache`, protected by `RwLock`
93struct UnifiedCacheInner<K, V> {
94    entries: FxHashMap<K, CacheEntry<V>>,
95    max_size: usize,
96    /// Configured TTL, kept so pressure tuning can set an absolute factor instead
97    /// of compounding reductions on every observation.
98    base_ttl: Duration,
99    ttl: Duration,
100    stats: CacheStats,
101    eviction_policy: EvictionPolicy,
102}
103
104#[derive(Debug, Clone, Copy)]
105pub enum EvictionPolicy {
106    /// Least Recently Used
107    Lru,
108    /// Least Frequently Used
109    Lfu,
110    /// First In, First Out
111    Fifo,
112    /// Time-based expiration only
113    TtlOnly,
114}
115
116impl<K, V> UnifiedCache<K, V>
117where
118    K: CacheKey,
119    V: CacheValue,
120{
121    pub fn new(max_size: usize, ttl: Duration, eviction_policy: EvictionPolicy) -> Self {
122        Self {
123            inner: RwLock::new(UnifiedCacheInner {
124                entries: FxHashMap::with_capacity_and_hasher(max_size, Default::default()),
125                max_size,
126                base_ttl: ttl,
127                ttl,
128                stats: CacheStats { max_size, ..Default::default() },
129                eviction_policy,
130            }),
131        }
132    }
133
134    /// Get value from cache with zero-copy access by default.
135    ///
136    /// Uses a read-first fast path and only attempts a non-blocking write lock
137    /// for best-effort metadata/stat updates.
138    pub fn get(&self, key: &K) -> Option<Arc<V>> {
139        enum LookupState<T> {
140            Hit(Arc<T>),
141            Expired,
142            Miss,
143        }
144
145        let state = {
146            let inner = self.inner.read().unwrap_or_else(|e| e.into_inner());
147            let ttl = inner.ttl;
148
149            match inner.entries.get(key) {
150                Some(entry) if !entry.is_expired(ttl) => LookupState::Hit(Arc::clone(&entry.value)),
151                Some(_) => LookupState::Expired,
152                None => LookupState::Miss,
153            }
154        };
155
156        match state {
157            LookupState::Hit(value) => {
158                if let Ok(mut inner) = self.inner.try_write() {
159                    if let Some(entry) = inner.entries.get_mut(key) {
160                        entry.mark_accessed();
161                    }
162                    inner.stats.hits += 1;
163                }
164                Some(value)
165            }
166            LookupState::Expired => {
167                if let Ok(mut inner) = self.inner.try_write() {
168                    let ttl = inner.ttl;
169                    let should_remove = inner.entries.get(key).map(|entry| entry.is_expired(ttl)).unwrap_or(false);
170                    if should_remove {
171                        Self::remove_inner(&mut inner, key);
172                    }
173                    inner.stats.misses += 1;
174                }
175                None
176            }
177            LookupState::Miss => {
178                if let Ok(mut inner) = self.inner.try_write() {
179                    inner.stats.misses += 1;
180                }
181                None
182            }
183        }
184    }
185
186    /// Get owned value (explicitly clones when needed)
187    pub fn get_owned(&self, key: &K) -> Option<V> {
188        self.get(key).map(|arc| (*arc).clone())
189    }
190
191    /// Insert value into cache with automatic eviction
192    pub fn insert(&self, key: K, value: V, size_bytes: u64) {
193        self.insert_entry(key, CacheEntry::new(value, size_bytes));
194    }
195
196    /// Insert an already shared value without cloning its payload.
197    pub fn insert_arc(&self, key: K, value: Arc<V>, size_bytes: u64) {
198        self.insert_entry(key, CacheEntry::from_arc(value, size_bytes));
199    }
200
201    fn insert_entry(&self, key: K, entry: CacheEntry<V>) {
202        let Ok(mut inner) = self.inner.write() else {
203            return;
204        };
205
206        // Remove expired entries first
207        Self::remove_expired_entries_inner(&mut inner);
208
209        // A zero-capacity cache must remain bounded and reject all inserts.
210        if inner.max_size == 0 {
211            return;
212        }
213
214        let size_bytes = entry.size_bytes;
215
216        // Replacements do not consume another capacity slot, so they must not
217        // evict an unrelated entry when the cache is full.
218        if let Some(current) = inner.entries.get_mut(&key) {
219            let previous = std::mem::replace(current, entry);
220            inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_sub(previous.size_bytes);
221            inner.stats.current_size = inner.entries.len();
222            inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_add(size_bytes);
223            return;
224        }
225
226        // Batch evict if over capacity: remove 10% of entries at once
227        // to avoid repeated O(n) scans on consecutive inserts
228        if inner.entries.len() >= inner.max_size {
229            let to_remove = (inner.max_size / 10).max(1);
230            Self::evict_batch_inner(&mut inner, to_remove);
231        }
232
233        inner.entries.insert(key, entry);
234        inner.stats.current_size = inner.entries.len();
235        inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_add(size_bytes);
236    }
237
238    /// Remove expired entries based on TTL
239    fn remove_expired_entries_inner(inner: &mut UnifiedCacheInner<K, V>) {
240        let ttl = inner.ttl;
241        Self::remove_entries_where_inner(inner, |_, entry| entry.is_expired(ttl));
242    }
243
244    /// Remove matching entries in place without cloning keys or retaining values.
245    fn remove_entries_where_inner<F>(inner: &mut UnifiedCacheInner<K, V>, mut predicate: F) -> usize
246    where
247        F: FnMut(&K, &CacheEntry<V>) -> bool,
248    {
249        let UnifiedCacheInner { entries, stats, .. } = inner;
250        let previous_size = entries.len();
251        entries.retain(|key, entry| {
252            if predicate(key, entry) {
253                stats.total_memory_bytes = stats.total_memory_bytes.saturating_sub(entry.size_bytes);
254                false
255            } else {
256                true
257            }
258        });
259        stats.current_size = entries.len();
260        previous_size - entries.len()
261    }
262
263    /// Batch-evict `count` entries based on the eviction policy.
264    /// Performs a single O(n log n) sort instead of `count` × O(n) linear scans.
265    /// Returns the number of evicted entries, cloning only their keys.
266    fn evict_batch_inner(inner: &mut UnifiedCacheInner<K, V>, count: usize) -> usize {
267        if count == 0 || inner.entries.is_empty() {
268            return 0;
269        }
270
271        let keys_to_remove: Vec<K> = {
272            let mut entries: Vec<_> = inner.entries.iter().collect();
273            match inner.eviction_policy {
274                EvictionPolicy::Lru => entries.sort_by_key(|(_, entry)| entry.last_accessed),
275                EvictionPolicy::Lfu => entries.sort_by_key(|(_, entry)| entry.access_count),
276                EvictionPolicy::Fifo | EvictionPolicy::TtlOnly => {
277                    entries.sort_by_key(|(_, entry)| entry.created_at);
278                }
279            }
280            entries.into_iter().take(count).map(|(key, _)| key.clone()).collect()
281        };
282
283        for key in &keys_to_remove {
284            Self::remove_inner(inner, key);
285        }
286        inner.stats.evictions += keys_to_remove.len() as u64;
287        keys_to_remove.len()
288    }
289
290    fn remove_inner(inner: &mut UnifiedCacheInner<K, V>, key: &K) {
291        if let Some(entry) = inner.entries.remove(key) {
292            inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_sub(entry.size_bytes);
293            inner.stats.current_size = inner.entries.len();
294        }
295    }
296
297    /// Get cache statistics (returns owned clone)
298    pub fn stats(&self) -> CacheStats {
299        self.inner.read().map(|inner| inner.stats.clone()).unwrap_or_default()
300    }
301
302    /// Clear all entries
303    pub fn clear(&self) {
304        if let Ok(mut inner) = self.inner.write() {
305            inner.entries.clear();
306            inner.stats.current_size = 0;
307            inner.stats.total_memory_bytes = 0;
308        }
309    }
310
311    /// Remove a single cache entry by exact key.
312    pub fn remove(&self, key: &K) {
313        let Ok(mut inner) = self.inner.write() else {
314            return;
315        };
316        Self::remove_inner(&mut inner, key);
317    }
318
319    /// Get current size
320    pub fn len(&self) -> usize {
321        self.inner.read().map(|inner| inner.entries.len()).unwrap_or(0)
322    }
323
324    pub fn is_empty(&self) -> bool {
325        self.len() == 0
326    }
327
328    /// Invalidate cache entries matching a key prefix (selective eviction)
329    /// This replaces the old "clear entire cache" behavior with granular eviction
330    ///
331    /// # Example
332    /// ```ignore
333    /// cache.invalidate_prefix("grep_file:/workspace/src/");
334    /// // Only removes entries for that specific file, not entire cache
335    /// ```
336    pub fn invalidate_prefix(&self, prefix: &str) {
337        self.remove_where(|key| key.to_cache_key().starts_with(prefix));
338    }
339
340    /// Invalidate entries for a specific target path (e.g., file path)
341    /// This is a convenience wrapper for file-based invalidation
342    ///
343    /// # Example
344    /// ```ignore
345    /// cache.invalidate_path("/workspace/src/main.rs");
346    /// // Removes all cache entries related to this file
347    /// ```
348    pub fn invalidate_path(&self, path: &str) {
349        self.invalidate_prefix(&format!("{path}:"));
350    }
351
352    /// Invalidate cache entries matching a key suffix (selective eviction)
353    ///
354    /// # Example
355    /// ```ignore
356    /// cache.invalidate_suffix(":/workspace/src/main.rs");
357    /// // Only removes entries for that specific file
358    /// ```
359    pub fn invalidate_suffix(&self, suffix: &str) {
360        self.remove_where(|key| key.to_cache_key().ends_with(suffix));
361    }
362
363    /// Invalidate cache entries containing a substring (selective eviction)
364    ///
365    /// # Example
366    /// ```ignore
367    /// cache.invalidate_containing("/workspace/src/main.rs");
368    /// // Removes entries where the cache key contains this path
369    /// ```
370    pub fn invalidate_containing(&self, substring: &str) {
371        self.remove_where(|key| key.to_cache_key().contains(substring));
372    }
373
374    /// Remove all entries that satisfy a predicate.
375    ///
376    /// Returns the number of removed entries without cloning keys or buffering matches.
377    pub fn remove_where<F>(&self, mut predicate: F) -> usize
378    where
379        F: FnMut(&K) -> bool,
380    {
381        let Ok(mut inner) = self.inner.write() else {
382            return 0;
383        };
384
385        Self::remove_entries_where_inner(&mut inner, |key, _| predicate(key))
386    }
387
388    /// Get total memory used by cache in bytes
389    pub fn total_memory_bytes(&self) -> u64 {
390        self.inner.read().map(|inner| inner.stats.total_memory_bytes).unwrap_or(0)
391    }
392
393    /// Estimate entry cost in bytes (for memory-aware decisions)
394    /// This is a heuristic based on entry metadata
395    pub fn estimate_entry_cost(entry: &CacheEntry<V>) -> u64 {
396        // Base: entry metadata + overhead
397        let base_overhead: u64 = 100; // Approximate Arc, SystemTime, etc.
398        let value_size = entry.size_bytes;
399        base_overhead + value_size
400    }
401
402    /// Set the effective TTL to `factor` times the *configured* TTL.
403    ///
404    /// Idempotent by design: pressure is observed repeatedly (e.g. once per turn),
405    /// so multiplying the current TTL on every call would shrink it geometrically
406    /// toward zero and leave no way to recover when pressure subsides. A factor of
407    /// `1.0` restores the original TTL. Factors are clamped to `[0, 1]`; a
408    /// non-finite factor leaves the current TTL unchanged.
409    pub fn reduce_ttl(&self, factor: f64) -> Duration {
410        let Ok(mut inner) = self.inner.write() else {
411            return Duration::ZERO;
412        };
413        if !factor.is_finite() {
414            return inner.ttl;
415        }
416        let factor = factor.clamp(0.0, 1.0);
417        // `Duration::mul_f64(1.0)` can panic for a near-`Duration::MAX` base
418        // because `u64::MAX as f64` rounds past the representable limit. Return
419        // the configured value directly so the restore contract is exact.
420        inner.ttl = if factor >= 1.0 {
421            inner.base_ttl
422        } else {
423            inner.base_ttl.mul_f64(factor)
424        };
425        inner.ttl
426    }
427
428    /// TTL this cache was configured with, before any pressure tuning.
429    pub fn base_ttl(&self) -> Duration {
430        self.inner.read().map(|inner| inner.base_ttl).unwrap_or(Duration::ZERO)
431    }
432
433    /// Evict entries under memory pressure (aggressive cleanup)
434    ///
435    /// When memory pressure increases:
436    /// 1. Remove all expired entries first
437    /// 2. Evict according to the configured policy until the live entry count
438    ///    reaches `floor(live_count * (100 - percent) / 100)`.
439    ///
440    /// Percentages are clamped to 100. The return count includes expired entries;
441    /// expiration does not increment the eviction statistic.
442    pub fn evict_under_pressure(&self, target_reduction_percent: u32) -> usize {
443        let Ok(mut inner) = self.inner.write() else {
444            return 0;
445        };
446
447        // Clamp percentage to 0-100
448        let target_percent = std::cmp::min(100, target_reduction_percent);
449
450        // Remove expired entries first (most efficient cleanup)
451        let expired_before = inner.entries.len();
452        Self::remove_expired_entries_inner(&mut inner);
453        let expired_removed = expired_before - inner.entries.len();
454
455        // Calculate target size
456        let current_size = inner.entries.len();
457        let target_size = (current_size * (100 - target_percent) as usize) / 100;
458
459        expired_removed + Self::evict_batch_inner(&mut inner, current_size - target_size)
460    }
461
462    /// Evict `floor(entry_count * percent / 100)` entries using the configured policy.
463    /// Percentages are clamped to 100. Returns the number of entries removed.
464    pub fn clear_least_used(&self, percent_to_clear: u32) -> usize {
465        let Ok(mut inner) = self.inner.write() else {
466            return 0;
467        };
468
469        let percent = std::cmp::min(100, percent_to_clear);
470        let entries_to_remove = (inner.entries.len() * percent as usize) / 100;
471
472        Self::evict_batch_inner(&mut inner, entries_to_remove)
473    }
474
475    /// Get entries sorted by "usefulness" (access count and recency)
476    /// Higher score = more useful (keep these)
477    pub fn entries_by_usefulness(&self) -> Vec<(K, CacheEntry<V>)> {
478        let Ok(inner) = self.inner.read() else {
479            return Vec::new();
480        };
481
482        let now = SystemTime::now();
483        let mut entries: Vec<(K, CacheEntry<V>, u64)> = inner
484            .entries
485            .iter()
486            .map(|(k, entry)| {
487                // Score = access_count * recency_factor
488                let age_secs = now.duration_since(entry.last_accessed).unwrap_or_default().as_secs();
489
490                // Recency factor: recent entries get higher score
491                let recency_factor = std::cmp::max(1_u64, 3600 / (age_secs + 1));
492                let usefulness_score = entry.access_count * recency_factor;
493
494                (k.clone(), entry.clone(), usefulness_score)
495            })
496            .collect();
497
498        // Sort by usefulness descending (highest first)
499        entries.sort_by_key(|(_, _, score)| std::cmp::Reverse(*score));
500        entries.into_iter().map(|(k, e, _)| (k, e)).collect()
501    }
502}
503
504/// Helper function to estimate JSON value size without allocation
505pub fn estimate_json_size(value: &serde_json::Value) -> u64 {
506    match value {
507        serde_json::Value::Null => 4,
508        serde_json::Value::Bool(_) => 5,
509        serde_json::Value::Number(n) => n.to_string().len() as u64,
510        serde_json::Value::String(s) => s.len() as u64,
511        serde_json::Value::Array(arr) => arr
512            .iter()
513            .map(estimate_json_size)
514            .fold(0u64, |acc, size| acc.saturating_add(size)),
515        serde_json::Value::Object(obj) => obj
516            .iter()
517            .map(|(k, v)| (k.len() as u64).saturating_add(estimate_json_size(v)).saturating_add(3)) // +3 for quotes and colon
518            .fold(0u64, |acc, size| acc.saturating_add(size)),
519    }
520}
521
522/// Helper function to create cache key from serializable data
523pub fn create_cache_key<T: Serialize>(data: &T) -> Result<String> {
524    let json_bytes = serde_json::to_vec(data)?;
525
526    // Use a simple hash function instead of blake3 to avoid dependency
527    let mut hash = 0u64;
528    for (i, byte) in json_bytes.iter().enumerate() {
529        hash = hash.wrapping_mul(31).wrapping_add(*byte as u64);
530        hash = hash.rotate_left((i % 64) as u32);
531    }
532
533    Ok(format!("{hash:016x}"))
534}
535
536/// Context-aware cache that limits results to MAX_CONTEXT_ITEMS
537pub struct ContextAwareCache<K, V> {
538    inner: UnifiedCache<K, V>,
539}
540
541impl<K, V> ContextAwareCache<K, V>
542where
543    K: CacheKey,
544    V: CacheValue,
545{
546    pub fn new(max_size: usize, ttl: Duration, eviction_policy: EvictionPolicy) -> Self {
547        Self {
548            inner: UnifiedCache::new(max_size, ttl, eviction_policy),
549        }
550    }
551
552    /// Get results with automatic context limitation
553    pub fn get_context_limited<F>(&self, keys: &[K], mut process_fn: F) -> Vec<V>
554    where
555        F: FnMut(&K) -> Option<V>,
556    {
557        let mut results = Vec::with_capacity(MAX_CONTEXT_ITEMS.min(keys.len()));
558        let mut overflow_count = 0;
559
560        for key in keys {
561            if results.len() >= MAX_CONTEXT_ITEMS {
562                overflow_count += 1;
563                continue;
564            }
565
566            if let Some(value) = self.inner.get(key) {
567                results.push((*value).clone());
568            } else if let Some(value) = process_fn(key) {
569                // Cache the result for future use
570                let size = size_of_val(&value) as u64;
571                self.inner.insert(key.clone(), value.clone(), size);
572                results.push(value);
573            }
574        }
575
576        // Add overflow indication if needed
577        if overflow_count > 0 {
578            // This would need to be handled by the caller to add overflow indication
579            // For now, we just limit the results
580        }
581
582        results
583    }
584
585    pub fn stats(&self) -> CacheStats {
586        self.inner.stats()
587    }
588}
589
590#[cfg(test)]
591mod eviction_tests;
592
593#[cfg(test)]
594mod tests {
595    use super::*;
596
597    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
598    struct TestKey(String);
599
600    impl CacheKey for TestKey {
601        fn to_cache_key(&self) -> String {
602            self.0.clone()
603        }
604    }
605
606    #[test]
607    fn test_cache_basic_operations() {
608        let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
609        let key = TestKey("test".into());
610        let value: String = "test_value".into();
611
612        // Insert and retrieve
613        cache.insert(key.clone(), value.clone(), 100);
614        assert_eq!(*cache.get(&key).unwrap(), value);
615
616        // Check stats
617        let stats = cache.stats();
618        assert_eq!(stats.hits, 1);
619        assert_eq!(stats.misses, 0);
620        assert_eq!(stats.current_size, 1);
621    }
622
623    #[test]
624    fn insert_arc_preserves_value_arc_and_statistics() {
625        let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
626        let key = TestKey("arc".into());
627        let value = Arc::new("shared value".to_string());
628
629        cache.insert_arc(key.clone(), Arc::clone(&value), value.len() as u64);
630
631        let cached = cache.get(&key).expect("inserted value should be cached");
632        assert!(Arc::ptr_eq(&cached, &value));
633        assert_eq!(cache.stats().total_memory_bytes, value.len() as u64);
634    }
635
636    #[test]
637    fn replacing_entry_updates_memory_statistics() {
638        let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
639        let key = TestKey("replacement".into());
640
641        cache.insert(key.clone(), "small".to_string(), 5);
642        cache.insert(key, "larger replacement".to_string(), 18);
643
644        let stats = cache.stats();
645        assert_eq!(stats.current_size, 1);
646        assert_eq!(stats.total_memory_bytes, 18);
647    }
648
649    #[test]
650    fn replacing_entry_at_capacity_does_not_evict() {
651        let cache = UnifiedCache::new(1, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
652        let key = TestKey("replacement".into());
653
654        cache.insert(key.clone(), "old".to_string(), 3);
655        cache.insert(key.clone(), "new value".to_string(), 9);
656
657        assert_eq!(cache.get_owned(&key).as_deref(), Some("new value"));
658        let stats = cache.stats();
659        assert_eq!(stats.current_size, 1);
660        assert_eq!(stats.evictions, 0);
661        assert_eq!(stats.total_memory_bytes, 9);
662    }
663
664    #[test]
665    fn zero_capacity_cache_rejects_entries() {
666        let cache = UnifiedCache::new(0, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
667
668        cache.insert(TestKey("rejected".into()), "value".to_string(), 5);
669
670        assert_eq!(cache.len(), 0);
671        assert_eq!(cache.total_memory_bytes(), 0);
672        assert_eq!(cache.stats().evictions, 0);
673    }
674
675    #[test]
676    fn test_cache_expiration() {
677        let cache = UnifiedCache::new(10, Duration::from_millis(100), EvictionPolicy::Lru);
678        let key = TestKey("test".into());
679        let value: String = "test_value".into();
680
681        cache.insert(key.clone(), value, 100);
682        assert!(cache.get(&key).is_some());
683
684        // Wait for expiration
685        std::thread::sleep(Duration::from_millis(150));
686        assert!(cache.get(&key).is_none());
687    }
688
689    #[test]
690    fn test_context_limited_cache() {
691        let cache = ContextAwareCache::new(100, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
692        let keys: Vec<TestKey> = (0..10).map(|i| TestKey(i.to_string())).collect();
693
694        let results = cache.get_context_limited(&keys, |key| Some(format!("value_{}", key.0)));
695
696        // Should be limited to MAX_CONTEXT_ITEMS (5)
697        assert_eq!(results.len(), MAX_CONTEXT_ITEMS);
698        assert_eq!(results[0], "value_0");
699        assert_eq!(results[4], "value_4");
700    }
701
702    #[test]
703    fn test_pressure_aware_total_memory() {
704        let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
705
706        // Insert three entries with known sizes
707        cache.insert(TestKey("k1".into()), "v1".to_string(), 100);
708        cache.insert(TestKey("k2".into()), "v2".to_string(), 200);
709        cache.insert(TestKey("k3".into()), "v3".to_string(), 300);
710
711        // Total should be 600 bytes
712        assert_eq!(cache.total_memory_bytes(), 600);
713    }
714
715    #[test]
716    fn pressure_ttl_is_idempotent_and_recoverable() {
717        let cache: UnifiedCache<TestKey, String> = UnifiedCache::new(10, Duration::from_secs(300), EvictionPolicy::Lru);
718
719        assert_eq!(cache.base_ttl(), Duration::from_secs(300));
720        assert_eq!(cache.reduce_ttl(0.4), Duration::from_secs(120));
721        // Sustained pressure at the same level must not compound toward zero.
722        assert_eq!(cache.reduce_ttl(0.4), Duration::from_secs(120));
723        assert_eq!(cache.reduce_ttl(0.1), Duration::from_secs(30));
724        // Recovery when pressure subsides.
725        assert_eq!(cache.reduce_ttl(1.0), Duration::from_secs(300));
726    }
727
728    #[test]
729    fn pressure_ttl_clamps_out_of_range_factors_and_ignores_non_finite() {
730        let cache: UnifiedCache<TestKey, String> = UnifiedCache::new(10, Duration::from_secs(300), EvictionPolicy::Lru);
731        assert_eq!(cache.reduce_ttl(0.5), Duration::from_secs(150));
732
733        // Non-finite factors leave the current TTL alone (no panic, no reset).
734        assert_eq!(cache.reduce_ttl(f64::NAN), Duration::from_secs(150));
735        assert_eq!(cache.reduce_ttl(f64::INFINITY), Duration::from_secs(150));
736        // Out-of-range factors clamp to the documented [0, 1] interval.
737        assert_eq!(cache.reduce_ttl(-1.0), Duration::ZERO);
738        assert_eq!(cache.reduce_ttl(2.0), Duration::from_secs(300));
739    }
740
741    #[test]
742    fn pressure_ttl_restore_never_panics_for_max_duration() {
743        let cache: UnifiedCache<TestKey, String> = UnifiedCache::new(1, Duration::MAX, EvictionPolicy::Lru);
744        assert_eq!(cache.reduce_ttl(0.5), Duration::from_secs(1 << 63));
745        assert_eq!(cache.reduce_ttl(1.0), Duration::MAX);
746    }
747
748    #[test]
749    fn test_pressure_aware_evict_under_pressure() {
750        let cache: UnifiedCache<TestKey, String> =
751            UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
752
753        // Insert 10 entries
754        for i in 0..10 {
755            cache.insert(TestKey(format!("key_{i}")), format!("value_{i}"), 100);
756        }
757
758        assert_eq!(cache.len(), 10);
759
760        // Evict to 50% (remove 5 entries)
761        let removed = cache.evict_under_pressure(50);
762        assert_eq!(removed, 5);
763        assert_eq!(cache.len(), 5);
764    }
765
766    #[test]
767    fn test_pressure_aware_clear_least_used() {
768        let cache: UnifiedCache<TestKey, String> =
769            UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
770
771        // Insert 10 entries
772        for i in 0..10 {
773            cache.insert(TestKey(format!("key_{i}")), format!("value_{i}"), 100);
774        }
775
776        // Access some entries to mark them as used
777        let _ = cache.get(&TestKey("key_0".into()));
778        let _ = cache.get(&TestKey("key_1".into()));
779
780        assert_eq!(cache.len(), 10);
781
782        // Clear 30% least used
783        let removed = cache.clear_least_used(30);
784        assert!(removed <= 4, "Should remove ~3 entries (30% of 10)");
785        assert!(cache.len() >= 6, "Should have ~7 entries left");
786    }
787
788    #[test]
789    fn test_pressure_aware_entries_by_usefulness() {
790        let cache: UnifiedCache<TestKey, String> =
791            UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
792
793        // Insert and access entries with different patterns
794        cache.insert(TestKey("hot".into()), "value".to_string(), 100);
795        cache.insert(TestKey("cold".into()), "value".to_string(), 100);
796        cache.insert(TestKey("warm".into()), "value".to_string(), 100);
797
798        // Access "hot" multiple times
799        for _ in 0..5 {
800            let _ = cache.get(&TestKey("hot".into()));
801        }
802
803        // Access "warm" once
804        let _ = cache.get(&TestKey("warm".into()));
805
806        // "cold" is never accessed after insert
807
808        let usefulness = cache.entries_by_usefulness();
809        assert_eq!(usefulness.len(), 3);
810
811        // "hot" should be first (most useful)
812        assert_eq!(usefulness[0].0.0, "hot");
813    }
814
815    #[test]
816    fn test_pressure_aware_estimate_entry_cost() {
817        let entry = CacheEntry::new("test_value".to_string(), 1000);
818        let cost = UnifiedCache::<TestKey, String>::estimate_entry_cost(&entry);
819
820        // Cost should be at least the value size + overhead
821        assert!(cost >= 1000);
822        assert!(cost <= 1200); // Should be close to 1100 (1000 + 100 overhead)
823    }
824}