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