Skip to main content

trustformers_mobile/optimization/
adaptive_cache_manager.rs

1//! Adaptive Cache Manager with LRU and Smart Eviction
2//!
3//! This module provides an advanced caching system for mobile deployment with:
4//! - LRU (Least Recently Used) eviction
5//! - Adaptive eviction based on memory pressure
6//! - Frequency-based retention
7//! - Size-aware caching
8//! - Access pattern learning
9//! - Multi-tier caching (memory, disk)
10
11use serde::{Deserialize, Serialize};
12use std::collections::{HashMap, VecDeque};
13use std::hash::{Hash, Hasher};
14use std::path::{Path, PathBuf};
15use std::sync::{Arc, Mutex};
16use std::time::{Duration, Instant};
17use trustformers_core::errors::{Result, TrustformersError};
18
19/// Cache eviction strategy
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21pub enum EvictionStrategy {
22    /// Least Recently Used - evict oldest accessed items
23    LRU,
24    /// Least Frequently Used - evict least accessed items
25    LFU,
26    /// Adaptive - combine LRU and LFU based on access patterns
27    Adaptive,
28    /// Size-aware - prioritize smaller items when memory is tight
29    SizeAware,
30    /// Priority-based - use explicit priorities
31    Priority,
32}
33
34/// Cache entry with metadata
35#[derive(Debug, Clone)]
36pub struct CacheEntry<T> {
37    /// The cached data
38    pub data: T,
39    /// Size in bytes
40    pub size_bytes: usize,
41    /// Last access time
42    pub last_accessed: Instant,
43    /// Access count
44    pub access_count: u64,
45    /// Priority (higher = more important to keep)
46    pub priority: u32,
47    /// Creation time
48    pub created_at: Instant,
49    /// Expiry time (None = never expires)
50    pub expires_at: Option<Instant>,
51}
52
53impl<T> CacheEntry<T> {
54    /// Create new cache entry
55    pub fn new(data: T, size_bytes: usize) -> Self {
56        let now = Instant::now();
57        Self {
58            data,
59            size_bytes,
60            last_accessed: now,
61            access_count: 0,
62            priority: 0,
63            created_at: now,
64            expires_at: None,
65        }
66    }
67
68    /// Mark as accessed
69    pub fn mark_accessed(&mut self) {
70        self.last_accessed = Instant::now();
71        self.access_count += 1;
72    }
73
74    /// Check if expired
75    pub fn is_expired(&self) -> bool {
76        if let Some(expires_at) = self.expires_at {
77            Instant::now() > expires_at
78        } else {
79            false
80        }
81    }
82
83    /// Get age in seconds
84    pub fn age_seconds(&self) -> f64 {
85        self.created_at.elapsed().as_secs_f64()
86    }
87
88    /// Get time since last access in seconds
89    pub fn idle_seconds(&self) -> f64 {
90        self.last_accessed.elapsed().as_secs_f64()
91    }
92}
93
94/// Adaptive cache configuration
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct AdaptiveCacheConfig {
97    /// Maximum memory budget in bytes
98    pub max_memory_bytes: usize,
99
100    /// Soft limit (trigger eviction) as fraction of max
101    pub soft_limit_fraction: f32,
102
103    /// Hard limit (aggressive eviction) as fraction of max
104    pub hard_limit_fraction: f32,
105
106    /// Eviction strategy
107    pub eviction_strategy: EvictionStrategy,
108
109    /// Enable access pattern learning
110    pub learn_patterns: bool,
111
112    /// Default entry TTL (time to live)
113    pub default_ttl: Option<Duration>,
114
115    /// Enable disk-backed cache
116    pub disk_cache_enabled: bool,
117
118    /// Disk cache directory
119    pub disk_cache_dir: Option<PathBuf>,
120
121    /// Maximum disk cache size
122    pub max_disk_cache_bytes: usize,
123}
124
125impl Default for AdaptiveCacheConfig {
126    fn default() -> Self {
127        Self {
128            max_memory_bytes: 512 * 1024 * 1024, // 512MB
129            soft_limit_fraction: 0.75,
130            hard_limit_fraction: 0.9,
131            eviction_strategy: EvictionStrategy::Adaptive,
132            learn_patterns: true,
133            default_ttl: Some(Duration::from_secs(3600)), // 1 hour
134            disk_cache_enabled: false,
135            disk_cache_dir: None,
136            max_disk_cache_bytes: 2 * 1024 * 1024 * 1024, // 2GB
137        }
138    }
139}
140
141/// Access pattern statistics
142#[derive(Debug, Clone)]
143struct AccessPatternStats {
144    /// Total accesses
145    total_accesses: u64,
146    /// Sequential access count
147    sequential_count: u64,
148    /// Random access count
149    random_count: u64,
150    /// Average access frequency
151    avg_frequency: f64,
152    /// Last access times (for detecting patterns)
153    recent_accesses: VecDeque<Instant>,
154}
155
156impl Default for AccessPatternStats {
157    fn default() -> Self {
158        Self {
159            total_accesses: 0,
160            sequential_count: 0,
161            random_count: 0,
162            avg_frequency: 0.0,
163            recent_accesses: VecDeque::with_capacity(100),
164        }
165    }
166}
167
168/// Adaptive cache manager
169pub struct AdaptiveCacheManager<K: Hash + Eq + Clone, V: Clone> {
170    /// Configuration
171    config: AdaptiveCacheConfig,
172
173    /// Cache storage
174    cache: Arc<Mutex<HashMap<K, CacheEntry<V>>>>,
175
176    /// LRU order (most recent at back)
177    lru_order: Arc<Mutex<VecDeque<K>>>,
178
179    /// Current memory usage
180    current_memory: Arc<Mutex<usize>>,
181
182    /// Access pattern statistics
183    patterns: Arc<Mutex<HashMap<K, AccessPatternStats>>>,
184
185    /// Cache hit/miss statistics
186    stats: Arc<Mutex<CacheStats>>,
187}
188
189/// Cache statistics
190#[derive(Debug, Clone, Default, Serialize, Deserialize)]
191pub struct CacheStats {
192    /// Total cache hits
193    pub hits: u64,
194    /// Total cache misses
195    pub misses: u64,
196    /// Total evictions
197    pub evictions: u64,
198    /// Total items added
199    pub inserts: u64,
200    /// Current item count
201    pub item_count: usize,
202    /// Current memory usage
203    pub memory_bytes: usize,
204    /// Peak memory usage
205    pub peak_memory_bytes: usize,
206}
207
208impl CacheStats {
209    /// Calculate hit rate
210    pub fn hit_rate(&self) -> f64 {
211        let total = self.hits + self.misses;
212        if total == 0 {
213            0.0
214        } else {
215            self.hits as f64 / total as f64
216        }
217    }
218
219    /// Calculate average item size
220    pub fn avg_item_size(&self) -> usize {
221        self.memory_bytes.checked_div(self.item_count).unwrap_or(0)
222    }
223}
224
225impl<K: Hash + Eq + Clone, V: Clone> AdaptiveCacheManager<K, V> {
226    /// Create new adaptive cache manager
227    pub fn new(config: AdaptiveCacheConfig) -> Self {
228        Self {
229            config,
230            cache: Arc::new(Mutex::new(HashMap::new())),
231            lru_order: Arc::new(Mutex::new(VecDeque::new())),
232            current_memory: Arc::new(Mutex::new(0)),
233            patterns: Arc::new(Mutex::new(HashMap::new())),
234            stats: Arc::new(Mutex::new(CacheStats::default())),
235        }
236    }
237
238    /// Get value from cache
239    pub fn get(&self, key: &K) -> Option<V> {
240        let mut cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
241        let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
242
243        if let Some(entry) = cache.get_mut(key) {
244            // Check if expired
245            if entry.is_expired() {
246                drop(cache);
247                drop(stats);
248                self.remove(key);
249                return None;
250            }
251
252            // Update access metadata
253            entry.mark_accessed();
254
255            // Update LRU order
256            let mut lru = self.lru_order.lock().unwrap_or_else(|p| p.into_inner());
257            if let Some(pos) = lru.iter().position(|k| k == key) {
258                lru.remove(pos);
259            }
260            lru.push_back(key.clone());
261
262            // Update access patterns
263            if self.config.learn_patterns {
264                self.update_access_pattern(key);
265            }
266
267            stats.hits += 1;
268            Some(entry.data.clone())
269        } else {
270            stats.misses += 1;
271            None
272        }
273    }
274
275    /// Insert value into cache
276    pub fn insert(&self, key: K, value: V, size_bytes: usize) -> Result<()> {
277        self.insert_with_priority(key, value, size_bytes, 0)
278    }
279
280    /// Insert value with priority
281    pub fn insert_with_priority(
282        &self,
283        key: K,
284        value: V,
285        size_bytes: usize,
286        priority: u32,
287    ) -> Result<()> {
288        // Check if we need to evict
289        let mut current_mem = self.current_memory.lock().unwrap_or_else(|p| p.into_inner());
290        let soft_limit =
291            (self.config.max_memory_bytes as f32 * self.config.soft_limit_fraction) as usize;
292
293        if *current_mem + size_bytes > soft_limit {
294            drop(current_mem);
295            self.evict_to_fit(size_bytes)?;
296            current_mem = self.current_memory.lock().unwrap_or_else(|p| p.into_inner());
297        }
298
299        // Create cache entry
300        let mut entry = CacheEntry::new(value, size_bytes);
301        entry.priority = priority;
302
303        if let Some(ttl) = self.config.default_ttl {
304            entry.expires_at = Some(Instant::now() + ttl);
305        }
306
307        // Insert into cache
308        let mut cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
309        cache.insert(key.clone(), entry);
310
311        // Update LRU order
312        let mut lru = self.lru_order.lock().unwrap_or_else(|p| p.into_inner());
313        lru.push_back(key.clone());
314
315        // Update memory tracking
316        *current_mem += size_bytes;
317
318        // Update statistics
319        let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
320        stats.inserts += 1;
321        stats.item_count = cache.len();
322        stats.memory_bytes = *current_mem;
323        stats.peak_memory_bytes = stats.peak_memory_bytes.max(*current_mem);
324
325        Ok(())
326    }
327
328    /// Remove value from cache
329    pub fn remove(&self, key: &K) -> Option<V> {
330        let mut cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
331
332        if let Some(entry) = cache.remove(key) {
333            // Update LRU order
334            let mut lru = self.lru_order.lock().unwrap_or_else(|p| p.into_inner());
335            if let Some(pos) = lru.iter().position(|k| k == key) {
336                lru.remove(pos);
337            }
338
339            // Update memory tracking
340            let mut current_mem = self.current_memory.lock().unwrap_or_else(|p| p.into_inner());
341            *current_mem = current_mem.saturating_sub(entry.size_bytes);
342
343            // Update statistics
344            let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
345            stats.item_count = cache.len();
346            stats.memory_bytes = *current_mem;
347
348            Some(entry.data)
349        } else {
350            None
351        }
352    }
353
354    /// Clear all cache entries
355    pub fn clear(&self) {
356        let mut cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
357        cache.clear();
358
359        let mut lru = self.lru_order.lock().unwrap_or_else(|p| p.into_inner());
360        lru.clear();
361
362        let mut current_mem = self.current_memory.lock().unwrap_or_else(|p| p.into_inner());
363        *current_mem = 0;
364
365        let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
366        stats.item_count = 0;
367        stats.memory_bytes = 0;
368    }
369
370    /// Evict entries to fit new data
371    fn evict_to_fit(&self, required_bytes: usize) -> Result<()> {
372        let target_memory =
373            (self.config.max_memory_bytes as f32 * self.config.soft_limit_fraction) as usize;
374        let current_mem = *self.current_memory.lock().unwrap_or_else(|p| p.into_inner());
375
376        if current_mem + required_bytes <= target_memory {
377            return Ok(());
378        }
379
380        let to_free = (current_mem + required_bytes) - target_memory;
381        let mut freed = 0;
382
383        match self.config.eviction_strategy {
384            EvictionStrategy::LRU => {
385                freed = self.evict_lru(to_free)?;
386            },
387            EvictionStrategy::LFU => {
388                freed = self.evict_lfu(to_free)?;
389            },
390            EvictionStrategy::Adaptive => {
391                freed = self.evict_adaptive(to_free)?;
392            },
393            EvictionStrategy::SizeAware => {
394                freed = self.evict_size_aware(to_free)?;
395            },
396            EvictionStrategy::Priority => {
397                freed = self.evict_by_priority(to_free)?;
398            },
399        }
400
401        if freed < to_free {
402            return Err(TrustformersError::runtime_error(
403                "Failed to free enough memory through eviction".to_string(),
404            ));
405        }
406
407        Ok(())
408    }
409
410    /// LRU eviction - evict least recently used
411    fn evict_lru(&self, to_free: usize) -> Result<usize> {
412        let mut freed = 0;
413        let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
414
415        while freed < to_free {
416            let key = {
417                let mut lru = self.lru_order.lock().unwrap_or_else(|p| p.into_inner());
418                lru.pop_front()
419            };
420
421            if let Some(key) = key {
422                // Get the size BEFORE removing the entry
423                let entry_size = {
424                    let cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
425                    cache.get(&key).map(|e| e.size_bytes).unwrap_or(0)
426                };
427
428                drop(stats);
429                if self.remove(&key).is_some() {
430                    freed += entry_size;
431                    stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
432                    stats.evictions += 1;
433                } else {
434                    break;
435                }
436            } else {
437                break;
438            }
439        }
440
441        Ok(freed)
442    }
443
444    /// LFU eviction - evict least frequently used
445    fn evict_lfu(&self, to_free: usize) -> Result<usize> {
446        let cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
447
448        // Sort by access count (ascending)
449        let mut entries: Vec<_> = cache.iter().collect();
450        entries.sort_by_key(|(_, entry)| entry.access_count);
451
452        // Collect keys to evict
453        let mut keys_to_evict = Vec::new();
454        let mut freed_estimate = 0;
455        for (k, e) in entries {
456            if freed_estimate >= to_free {
457                break;
458            }
459            freed_estimate += e.size_bytes;
460            keys_to_evict.push((k.clone(), e.size_bytes));
461        }
462
463        drop(cache);
464
465        let mut freed = 0;
466        for (key, size) in keys_to_evict.iter() {
467            self.remove(key);
468            freed += size;
469        }
470
471        // Update stats after all removals (avoid deadlock)
472        let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
473        stats.evictions += keys_to_evict.len() as u64;
474
475        Ok(freed)
476    }
477
478    /// Adaptive eviction - combine LRU and LFU based on access patterns
479    fn evict_adaptive(&self, to_free: usize) -> Result<usize> {
480        let cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
481
482        // Calculate adaptive score: combines recency and frequency
483        let mut entries: Vec<_> = cache
484            .iter()
485            .map(|(k, e)| {
486                let recency_score = 1.0 / (1.0 + e.idle_seconds());
487                let frequency_score = e.access_count as f64 / (1.0 + e.age_seconds());
488                let priority_score = e.priority as f64 / 100.0;
489
490                // Combined score (higher = more important to keep)
491                let score = recency_score * 0.4 + frequency_score * 0.4 + priority_score * 0.2;
492                (k, e, score)
493            })
494            .collect();
495
496        // Sort by score (ascending - evict lowest scores first)
497        entries
498            .sort_by(|(_, _, a), (_, _, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
499
500        // Collect keys to evict
501        let mut keys_to_evict = Vec::new();
502        let mut freed_estimate = 0;
503        for (k, e, _) in entries {
504            if freed_estimate >= to_free {
505                break;
506            }
507            freed_estimate += e.size_bytes;
508            keys_to_evict.push((k.clone(), e.size_bytes));
509        }
510
511        drop(cache);
512
513        let mut freed = 0;
514        for (key, size) in keys_to_evict.iter() {
515            self.remove(key);
516            freed += size;
517        }
518
519        // Update stats after all removals (avoid deadlock)
520        let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
521        stats.evictions += keys_to_evict.len() as u64;
522
523        Ok(freed)
524    }
525
526    /// Size-aware eviction - prioritize smaller items when under pressure
527    fn evict_size_aware(&self, to_free: usize) -> Result<usize> {
528        let cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
529
530        // Prefer evicting larger items first to free more space quickly
531        let mut entries: Vec<_> = cache.iter().collect();
532        entries.sort_by_key(|(_, entry)| std::cmp::Reverse(entry.size_bytes));
533
534        // Collect keys to evict
535        let mut keys_to_evict = Vec::new();
536        let mut freed_estimate = 0;
537        for (k, e) in entries {
538            if freed_estimate >= to_free {
539                break;
540            }
541            freed_estimate += e.size_bytes;
542            keys_to_evict.push((k.clone(), e.size_bytes));
543        }
544
545        drop(cache);
546
547        let mut freed = 0;
548        for (key, size) in keys_to_evict.iter() {
549            self.remove(key);
550            freed += size;
551        }
552
553        // Update stats after all removals (avoid deadlock)
554        let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
555        stats.evictions += keys_to_evict.len() as u64;
556
557        Ok(freed)
558    }
559
560    /// Priority-based eviction - evict lowest priority first
561    fn evict_by_priority(&self, to_free: usize) -> Result<usize> {
562        let cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
563
564        let mut entries: Vec<_> = cache.iter().collect();
565        entries.sort_by_key(|(_, entry)| entry.priority);
566
567        // Collect keys to evict
568        let mut keys_to_evict = Vec::new();
569        let mut freed_estimate = 0;
570        for (k, e) in entries {
571            if freed_estimate >= to_free {
572                break;
573            }
574            freed_estimate += e.size_bytes;
575            keys_to_evict.push((k.clone(), e.size_bytes));
576        }
577
578        drop(cache);
579
580        let mut freed = 0;
581        for (key, size) in keys_to_evict.iter() {
582            self.remove(key);
583            freed += size;
584        }
585
586        // Update stats after all removals (avoid deadlock)
587        let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
588        stats.evictions += keys_to_evict.len() as u64;
589
590        Ok(freed)
591    }
592
593    /// Update access pattern statistics
594    fn update_access_pattern(&self, key: &K) {
595        let mut patterns = self.patterns.lock().unwrap_or_else(|p| p.into_inner());
596        let stats = patterns.entry(key.clone()).or_default();
597
598        stats.total_accesses += 1;
599        stats.recent_accesses.push_back(Instant::now());
600
601        // Keep only recent 100 accesses
602        if stats.recent_accesses.len() > 100 {
603            stats.recent_accesses.pop_front();
604        }
605
606        // Update frequency
607        if stats.recent_accesses.len() >= 2 {
608            if let (Some(back), Some(front)) =
609                (stats.recent_accesses.back(), stats.recent_accesses.front())
610            {
611                let time_span = back.duration_since(*front).as_secs_f64();
612                stats.avg_frequency = stats.recent_accesses.len() as f64 / time_span.max(1.0);
613            }
614        }
615    }
616
617    /// Get cache statistics
618    pub fn stats(&self) -> CacheStats {
619        self.stats.lock().unwrap_or_else(|p| p.into_inner()).clone()
620    }
621
622    /// Get current memory usage
623    pub fn memory_usage(&self) -> usize {
624        *self.current_memory.lock().unwrap_or_else(|p| p.into_inner())
625    }
626
627    /// Check if cache contains key
628    pub fn contains(&self, key: &K) -> bool {
629        self.cache.lock().unwrap_or_else(|p| p.into_inner()).contains_key(key)
630    }
631
632    /// Get cache size (number of entries)
633    pub fn len(&self) -> usize {
634        self.cache.lock().unwrap_or_else(|p| p.into_inner()).len()
635    }
636
637    /// Check if cache is empty
638    pub fn is_empty(&self) -> bool {
639        self.len() == 0
640    }
641}
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646
647    #[test]
648    fn test_lru_eviction() {
649        let config = AdaptiveCacheConfig {
650            max_memory_bytes: 1000,
651            // Use 1.0 so eviction only happens when exceeding max_memory_bytes
652            soft_limit_fraction: 1.0,
653            eviction_strategy: EvictionStrategy::LRU,
654            ..Default::default()
655        };
656
657        let cache: AdaptiveCacheManager<String, Vec<u8>> = AdaptiveCacheManager::new(config);
658
659        // Insert items (300 * 3 = 900 bytes, under 1000 limit)
660        cache.insert("a".to_string(), vec![0u8; 300], 300).expect("Insert failed");
661        cache.insert("b".to_string(), vec![0u8; 300], 300).expect("Insert failed");
662        cache.insert("c".to_string(), vec![0u8; 300], 300).expect("Insert failed");
663
664        // This should trigger eviction of "a" (oldest) to make room
665        // 900 + 300 = 1200 > 1000, need to free at least 200 bytes -> evict "a" (300 bytes)
666        cache.insert("d".to_string(), vec![0u8; 300], 300).expect("Insert failed");
667
668        assert!(!cache.contains(&"a".to_string()));
669        assert!(cache.contains(&"b".to_string()));
670        assert!(cache.contains(&"c".to_string()));
671        assert!(cache.contains(&"d".to_string()));
672    }
673
674    #[test]
675    fn test_adaptive_eviction() {
676        let config = AdaptiveCacheConfig {
677            max_memory_bytes: 1000,
678            // Use 1.0 so eviction only happens when exceeding max_memory_bytes
679            soft_limit_fraction: 1.0,
680            eviction_strategy: EvictionStrategy::Adaptive,
681            ..Default::default()
682        };
683
684        let cache: AdaptiveCacheManager<String, Vec<u8>> = AdaptiveCacheManager::new(config);
685
686        // Insert items (300 * 3 = 900 bytes, under 1000 limit)
687        cache.insert("a".to_string(), vec![0u8; 300], 300).expect("Insert failed");
688        cache.insert("b".to_string(), vec![0u8; 300], 300).expect("Insert failed");
689        cache.insert("c".to_string(), vec![0u8; 300], 300).expect("Insert failed");
690
691        // Access "a" multiple times to increase its frequency
692        for _ in 0..10 {
693            cache.get(&"a".to_string());
694        }
695
696        // This should evict "b" or "c" (lower score), not "a"
697        cache.insert("d".to_string(), vec![0u8; 300], 300).expect("Insert failed");
698
699        assert!(cache.contains(&"a".to_string()));
700        assert!(cache.contains(&"d".to_string()));
701    }
702
703    #[test]
704    fn test_cache_stats() {
705        let config = AdaptiveCacheConfig::default();
706        let cache: AdaptiveCacheManager<String, String> = AdaptiveCacheManager::new(config);
707
708        cache
709            .insert("key1".to_string(), "value1".to_string(), 100)
710            .expect("Insert failed");
711
712        cache.get(&"key1".to_string());
713        cache.get(&"key2".to_string());
714
715        let stats = cache.stats();
716        assert_eq!(stats.hits, 1);
717        assert_eq!(stats.misses, 1);
718        assert_eq!(stats.hit_rate(), 0.5);
719    }
720
721    #[test]
722    fn test_priority_eviction() {
723        let config = AdaptiveCacheConfig {
724            max_memory_bytes: 1000,
725            // Use 1.0 so eviction only happens when exceeding max_memory_bytes
726            soft_limit_fraction: 1.0,
727            eviction_strategy: EvictionStrategy::Priority,
728            ..Default::default()
729        };
730
731        let cache: AdaptiveCacheManager<String, Vec<u8>> = AdaptiveCacheManager::new(config);
732
733        // Insert with different priorities (300 * 3 = 900 bytes, under 1000 limit)
734        cache
735            .insert_with_priority("low".to_string(), vec![0u8; 300], 300, 1)
736            .expect("Insert failed");
737        cache
738            .insert_with_priority("high".to_string(), vec![0u8; 300], 300, 10)
739            .expect("Insert failed");
740        cache
741            .insert_with_priority("medium".to_string(), vec![0u8; 300], 300, 5)
742            .expect("Insert failed");
743
744        // This should evict "low" (lowest priority)
745        cache
746            .insert_with_priority("new".to_string(), vec![0u8; 300], 300, 5)
747            .expect("Insert failed");
748
749        assert!(!cache.contains(&"low".to_string()));
750        assert!(cache.contains(&"high".to_string()));
751        assert!(cache.contains(&"medium".to_string()));
752    }
753}