1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21pub enum EvictionStrategy {
22 LRU,
24 LFU,
26 Adaptive,
28 SizeAware,
30 Priority,
32}
33
34#[derive(Debug, Clone)]
36pub struct CacheEntry<T> {
37 pub data: T,
39 pub size_bytes: usize,
41 pub last_accessed: Instant,
43 pub access_count: u64,
45 pub priority: u32,
47 pub created_at: Instant,
49 pub expires_at: Option<Instant>,
51}
52
53impl<T> CacheEntry<T> {
54 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 pub fn mark_accessed(&mut self) {
70 self.last_accessed = Instant::now();
71 self.access_count += 1;
72 }
73
74 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 pub fn age_seconds(&self) -> f64 {
85 self.created_at.elapsed().as_secs_f64()
86 }
87
88 pub fn idle_seconds(&self) -> f64 {
90 self.last_accessed.elapsed().as_secs_f64()
91 }
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct AdaptiveCacheConfig {
97 pub max_memory_bytes: usize,
99
100 pub soft_limit_fraction: f32,
102
103 pub hard_limit_fraction: f32,
105
106 pub eviction_strategy: EvictionStrategy,
108
109 pub learn_patterns: bool,
111
112 pub default_ttl: Option<Duration>,
114
115 pub disk_cache_enabled: bool,
117
118 pub disk_cache_dir: Option<PathBuf>,
120
121 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, 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)), disk_cache_enabled: false,
135 disk_cache_dir: None,
136 max_disk_cache_bytes: 2 * 1024 * 1024 * 1024, }
138 }
139}
140
141#[derive(Debug, Clone)]
143struct AccessPatternStats {
144 total_accesses: u64,
146 sequential_count: u64,
148 random_count: u64,
150 avg_frequency: f64,
152 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
168pub struct AdaptiveCacheManager<K: Hash + Eq + Clone, V: Clone> {
170 config: AdaptiveCacheConfig,
172
173 cache: Arc<Mutex<HashMap<K, CacheEntry<V>>>>,
175
176 lru_order: Arc<Mutex<VecDeque<K>>>,
178
179 current_memory: Arc<Mutex<usize>>,
181
182 patterns: Arc<Mutex<HashMap<K, AccessPatternStats>>>,
184
185 stats: Arc<Mutex<CacheStats>>,
187}
188
189#[derive(Debug, Clone, Default, Serialize, Deserialize)]
191pub struct CacheStats {
192 pub hits: u64,
194 pub misses: u64,
196 pub evictions: u64,
198 pub inserts: u64,
200 pub item_count: usize,
202 pub memory_bytes: usize,
204 pub peak_memory_bytes: usize,
206}
207
208impl CacheStats {
209 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 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 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 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 if entry.is_expired() {
246 drop(cache);
247 drop(stats);
248 self.remove(key);
249 return None;
250 }
251
252 entry.mark_accessed();
254
255 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 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 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 pub fn insert_with_priority(
282 &self,
283 key: K,
284 value: V,
285 size_bytes: usize,
286 priority: u32,
287 ) -> Result<()> {
288 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 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 let mut cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
309 cache.insert(key.clone(), entry);
310
311 let mut lru = self.lru_order.lock().unwrap_or_else(|p| p.into_inner());
313 lru.push_back(key.clone());
314
315 *current_mem += size_bytes;
317
318 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 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 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 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 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 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 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 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 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 fn evict_lfu(&self, to_free: usize) -> Result<usize> {
446 let cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
447
448 let mut entries: Vec<_> = cache.iter().collect();
450 entries.sort_by_key(|(_, entry)| entry.access_count);
451
452 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 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 fn evict_adaptive(&self, to_free: usize) -> Result<usize> {
480 let cache = self.cache.lock().unwrap_or_else(|p| p.into_inner());
481
482 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 let score = recency_score * 0.4 + frequency_score * 0.4 + priority_score * 0.2;
492 (k, e, score)
493 })
494 .collect();
495
496 entries
498 .sort_by(|(_, _, a), (_, _, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
499
500 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 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 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 let mut entries: Vec<_> = cache.iter().collect();
532 entries.sort_by_key(|(_, entry)| std::cmp::Reverse(entry.size_bytes));
533
534 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 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 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 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 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 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 if stats.recent_accesses.len() > 100 {
603 stats.recent_accesses.pop_front();
604 }
605
606 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 pub fn stats(&self) -> CacheStats {
619 self.stats.lock().unwrap_or_else(|p| p.into_inner()).clone()
620 }
621
622 pub fn memory_usage(&self) -> usize {
624 *self.current_memory.lock().unwrap_or_else(|p| p.into_inner())
625 }
626
627 pub fn contains(&self, key: &K) -> bool {
629 self.cache.lock().unwrap_or_else(|p| p.into_inner()).contains_key(key)
630 }
631
632 pub fn len(&self) -> usize {
634 self.cache.lock().unwrap_or_else(|p| p.into_inner()).len()
635 }
636
637 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 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 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 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 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 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 for _ in 0..10 {
693 cache.get(&"a".to_string());
694 }
695
696 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 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 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 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}