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