Skip to main content

oxirs_chat/
cache.rs

1//! Advanced Caching System for OxiRS Chat
2//!
3//! Implements multi-level caching for responses, contexts, embeddings, and query results
4//! with LRU eviction, TTL support, semantic caching, and intelligent cache warming strategies.
5
6pub mod semantic; // NEW: Semantic caching
7
8pub use semantic::{
9    CacheStatistics as SemanticCacheStatistics, SemanticCache, SemanticCacheConfig,
10};
11
12use anyhow::{anyhow, Result};
13use serde::{Deserialize, Serialize};
14use std::{
15    collections::{HashMap, VecDeque},
16    hash::{DefaultHasher, Hash, Hasher},
17    sync::Arc,
18    time::{Duration, SystemTime},
19};
20use tokio::sync::RwLock;
21use tracing::{debug, info, warn};
22
23use crate::{llm::LLMResponse, rag::AssembledContext, Message};
24
25/// Cache configuration with different strategies and policies
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct CacheConfig {
28    pub response_cache: CacheTierConfig,
29    pub context_cache: CacheTierConfig,
30    pub embedding_cache: CacheTierConfig,
31    pub query_cache: CacheTierConfig,
32    pub enable_warming: bool,
33    pub warming_strategies: Vec<WarmingStrategy>,
34    pub compression_enabled: bool,
35    pub persistence_enabled: bool,
36    pub persistence_interval: Duration,
37}
38
39impl Default for CacheConfig {
40    fn default() -> Self {
41        Self {
42            response_cache: CacheTierConfig {
43                max_size: 1000,
44                ttl: Duration::from_secs(3600), // 1 hour
45                eviction_policy: EvictionPolicy::LRU,
46                compression_threshold: 1024, // 1KB
47            },
48            context_cache: CacheTierConfig {
49                max_size: 500,
50                ttl: Duration::from_secs(1800), // 30 minutes
51                eviction_policy: EvictionPolicy::LFU,
52                compression_threshold: 2048, // 2KB
53            },
54            embedding_cache: CacheTierConfig {
55                max_size: 5000,
56                ttl: Duration::from_secs(86400), // 24 hours
57                eviction_policy: EvictionPolicy::LRU,
58                compression_threshold: 0, // No compression for embeddings
59            },
60            query_cache: CacheTierConfig {
61                max_size: 200,
62                ttl: Duration::from_secs(300), // 5 minutes
63                eviction_policy: EvictionPolicy::TTL,
64                compression_threshold: 512,
65            },
66            enable_warming: true,
67            warming_strategies: vec![
68                WarmingStrategy::FrequentQueries,
69                WarmingStrategy::RecentSessions,
70            ],
71            compression_enabled: true,
72            persistence_enabled: false,
73            persistence_interval: Duration::from_secs(300),
74        }
75    }
76}
77
78/// Configuration for individual cache tiers
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct CacheTierConfig {
81    pub max_size: usize,
82    pub ttl: Duration,
83    pub eviction_policy: EvictionPolicy,
84    pub compression_threshold: usize,
85}
86
87/// Cache eviction policies
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub enum EvictionPolicy {
90    LRU,  // Least Recently Used
91    LFU,  // Least Frequently Used
92    TTL,  // Time To Live only
93    FIFO, // First In, First Out
94}
95
96/// Cache warming strategies
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub enum WarmingStrategy {
99    FrequentQueries,
100    RecentSessions,
101    PopularEntities,
102    PredictivePatterns,
103}
104
105/// Pattern analysis results for predictive caching
106#[derive(Debug, Clone)]
107pub struct ConversationPatterns {
108    keyword_frequency: HashMap<String, usize>,
109    question_patterns: usize,
110    sparql_requests: usize,
111    graph_operations: usize,
112    hourly_activity: [usize; 24],
113    total_messages: usize,
114    question_confidence: f64,
115    sparql_confidence: f64,
116    pattern_confidence: f64,
117}
118
119impl ConversationPatterns {
120    fn new() -> Self {
121        Self {
122            keyword_frequency: HashMap::new(),
123            question_patterns: 0,
124            sparql_requests: 0,
125            graph_operations: 0,
126            hourly_activity: [0; 24],
127            total_messages: 0,
128            question_confidence: 0.0,
129            sparql_confidence: 0.0,
130            pattern_confidence: 0.0,
131        }
132    }
133
134    fn calculate_confidence(&mut self) {
135        self.total_messages = self.question_patterns + self.sparql_requests + self.graph_operations;
136
137        if self.total_messages > 0 {
138            self.question_confidence =
139                (self.question_patterns as f64 / self.total_messages as f64).min(1.0);
140            self.sparql_confidence =
141                (self.sparql_requests as f64 / self.total_messages as f64).min(1.0);
142
143            // Calculate overall pattern confidence based on activity consistency
144            let activity_variance = self.calculate_activity_variance();
145            self.pattern_confidence = (1.0 - activity_variance).max(0.3); // Minimum 30% confidence
146        }
147    }
148
149    fn calculate_activity_variance(&self) -> f64 {
150        let total_activity: usize = self.hourly_activity.iter().sum();
151        if total_activity == 0 {
152            return 1.0;
153        }
154
155        let mean = total_activity as f64 / 24.0;
156        let variance: f64 = self
157            .hourly_activity
158            .iter()
159            .map(|&activity| {
160                let diff = activity as f64 - mean;
161                diff * diff
162            })
163            .sum::<f64>()
164            / 24.0;
165
166        (variance.sqrt() / mean).min(1.0)
167    }
168}
169
170/// Cache prediction for smart warming
171#[derive(Debug, Clone)]
172pub struct CachePrediction {
173    key: String,
174    cache_type: PredictiveCacheType,
175    confidence: f64,
176    context: String,
177}
178
179/// Types of predictive cache entries
180#[derive(Debug, Clone)]
181pub enum PredictiveCacheType {
182    Response,
183    Context,
184    Embedding,
185    Query,
186}
187
188/// Cache entry with metadata
189#[derive(Debug, Clone)]
190struct CacheEntry<T> {
191    value: T,
192    created_at: SystemTime,
193    last_accessed: SystemTime,
194    access_count: usize,
195    ttl: Duration,
196    size_bytes: usize,
197    #[allow(dead_code)]
198    compression_used: bool,
199}
200
201impl<T> CacheEntry<T> {
202    fn new(value: T, ttl: Duration, size_bytes: usize) -> Self {
203        let now = SystemTime::now();
204        Self {
205            value,
206            created_at: now,
207            last_accessed: now,
208            access_count: 1,
209            ttl,
210            size_bytes,
211            compression_used: false,
212        }
213    }
214
215    fn is_expired(&self) -> bool {
216        self.created_at.elapsed().unwrap_or(Duration::ZERO) > self.ttl
217    }
218
219    fn update_access(&mut self) {
220        self.last_accessed = SystemTime::now();
221        self.access_count += 1;
222    }
223
224    fn age(&self) -> Duration {
225        self.created_at.elapsed().unwrap_or(Duration::ZERO)
226    }
227}
228
229/// Multi-level cache with different eviction policies
230struct CacheTier<T: Clone> {
231    config: CacheTierConfig,
232    entries: HashMap<String, CacheEntry<T>>,
233    access_order: VecDeque<String>,        // For LRU
234    frequency_map: HashMap<String, usize>, // For LFU
235    total_size: usize,
236}
237
238impl<T: Clone> CacheTier<T> {
239    fn new(config: CacheTierConfig) -> Self {
240        Self {
241            config,
242            entries: HashMap::new(),
243            access_order: VecDeque::new(),
244            frequency_map: HashMap::new(),
245            total_size: 0,
246        }
247    }
248
249    fn get(&mut self, key: &str) -> Option<T> {
250        // Check if entry exists and is not expired
251        let is_expired = self
252            .entries
253            .get(key)
254            .map_or(true, |entry| entry.is_expired());
255
256        if is_expired {
257            self.remove(key);
258            return None;
259        }
260
261        // Update access and return value
262        if let Some(entry) = self.entries.get_mut(key) {
263            entry.update_access();
264            let value = entry.value.clone();
265            // Update tracking after we're done with the mutable borrow
266            self.update_access_tracking(key);
267            Some(value)
268        } else {
269            None
270        }
271    }
272
273    fn put(&mut self, key: String, value: T, size_bytes: usize) -> Result<()> {
274        // Remove existing entry if present
275        if self.entries.contains_key(&key) {
276            self.remove(&key);
277        }
278
279        // Ensure space is available
280        self.ensure_space(size_bytes)?;
281
282        let entry = CacheEntry::new(value, self.config.ttl, size_bytes);
283        self.entries.insert(key.clone(), entry);
284        self.total_size += size_bytes;
285        self.update_access_tracking(&key);
286
287        debug!("Cache put: {} (size: {} bytes)", key, size_bytes);
288        Ok(())
289    }
290
291    fn remove(&mut self, key: &str) -> Option<T> {
292        match self.entries.remove(key) {
293            Some(entry) => {
294                self.total_size = self.total_size.saturating_sub(entry.size_bytes);
295                self.access_order.retain(|k| k != key);
296                self.frequency_map.remove(key);
297                debug!("Cache remove: {}", key);
298                Some(entry.value)
299            }
300            _ => None,
301        }
302    }
303
304    fn clear(&mut self) {
305        self.entries.clear();
306        self.access_order.clear();
307        self.frequency_map.clear();
308        self.total_size = 0;
309        info!("Cache cleared");
310    }
311
312    fn cleanup_expired(&mut self) -> usize {
313        let expired_keys: Vec<String> = self
314            .entries
315            .iter()
316            .filter(|(_, entry)| entry.is_expired())
317            .map(|(key, _)| key.clone())
318            .collect();
319
320        let count = expired_keys.len();
321        for key in expired_keys {
322            self.remove(&key);
323        }
324
325        if count > 0 {
326            debug!("Cleaned up {} expired cache entries", count);
327        }
328        count
329    }
330
331    fn ensure_space(&mut self, needed_bytes: usize) -> Result<()> {
332        // First, clean up expired entries
333        self.cleanup_expired();
334
335        // If still not enough space, evict according to policy
336        while self.total_size + needed_bytes > self.config.max_size * 1024
337            && !self.entries.is_empty()
338        {
339            match self.config.eviction_policy {
340                EvictionPolicy::LRU => self.evict_lru()?,
341                EvictionPolicy::LFU => self.evict_lfu()?,
342                EvictionPolicy::FIFO => self.evict_fifo()?,
343                EvictionPolicy::TTL => {
344                    // TTL-only policy - if no expired entries, fail
345                    return Err(anyhow!("Cache full and no expired entries to evict"));
346                }
347            }
348        }
349
350        Ok(())
351    }
352
353    fn evict_lru(&mut self) -> Result<()> {
354        if let Some(key) = self.access_order.front().cloned() {
355            self.remove(&key);
356            Ok(())
357        } else {
358            Err(anyhow!("No entries to evict"))
359        }
360    }
361
362    fn evict_lfu(&mut self) -> Result<()> {
363        if let Some((key, _)) = self.frequency_map.iter().min_by_key(|&(_, &count)| count) {
364            let key = key.clone();
365            self.remove(&key);
366            Ok(())
367        } else {
368            Err(anyhow!("No entries to evict"))
369        }
370    }
371
372    fn evict_fifo(&mut self) -> Result<()> {
373        if let Some((oldest_key, _)) = self
374            .entries
375            .iter()
376            .min_by_key(|(_, entry)| entry.created_at)
377        {
378            let key = oldest_key.clone();
379            self.remove(&key);
380            Ok(())
381        } else {
382            Err(anyhow!("No entries to evict"))
383        }
384    }
385
386    fn update_access_tracking(&mut self, key: &str) {
387        match self.config.eviction_policy {
388            EvictionPolicy::LRU => {
389                // Remove from current position and add to back
390                self.access_order.retain(|k| k != key);
391                self.access_order.push_back(key.to_string());
392            }
393            EvictionPolicy::LFU => {
394                *self.frequency_map.entry(key.to_string()).or_insert(0) += 1;
395            }
396            _ => {} // No tracking needed for other policies
397        }
398    }
399
400    #[allow(dead_code)]
401    fn size(&self) -> usize {
402        self.entries.len()
403    }
404
405    #[allow(dead_code)]
406    fn total_size_bytes(&self) -> usize {
407        self.total_size
408    }
409
410    fn get_stats(&self) -> CacheTierStats {
411        let mut expired_count = 0;
412        let mut avg_access_count = 0.0;
413        let mut total_age = Duration::ZERO;
414
415        for entry in self.entries.values() {
416            if entry.is_expired() {
417                expired_count += 1;
418            }
419            avg_access_count += entry.access_count as f64;
420            total_age += entry.age();
421        }
422
423        let entry_count = self.entries.len();
424        if entry_count > 0 {
425            avg_access_count /= entry_count as f64;
426        }
427
428        CacheTierStats {
429            entry_count,
430            total_size_bytes: self.total_size,
431            expired_count,
432            avg_access_count,
433            avg_age_seconds: if entry_count > 0 {
434                total_age.as_secs() / entry_count as u64
435            } else {
436                0
437            },
438        }
439    }
440}
441
442/// Statistics for a cache tier
443#[derive(Debug, Clone, Serialize, Deserialize)]
444pub struct CacheTierStats {
445    pub entry_count: usize,
446    pub total_size_bytes: usize,
447    pub expired_count: usize,
448    pub avg_access_count: f64,
449    pub avg_age_seconds: u64,
450}
451
452/// Main cache manager with multiple tiers
453pub struct AdvancedCacheManager {
454    config: CacheConfig,
455    response_cache: Arc<RwLock<CacheTier<CachedResponse>>>,
456    context_cache: Arc<RwLock<CacheTier<CachedContext>>>,
457    embedding_cache: Arc<RwLock<CacheTier<Vec<f32>>>>,
458    query_cache: Arc<RwLock<CacheTier<CachedQueryResult>>>,
459    hit_stats: Arc<RwLock<CacheStats>>,
460}
461
462/// Cached response data
463#[derive(Debug, Clone, Serialize, Deserialize)]
464pub struct CachedResponse {
465    pub content: String,
466    pub metadata: HashMap<String, serde_json::Value>,
467    pub quality_score: f32,
468    pub generation_method: String,
469}
470
471/// Cached context data
472#[derive(Debug, Clone, Serialize, Deserialize)]
473pub struct CachedContext {
474    pub context_text: String,
475    pub quality_score: f32,
476    pub coverage_score: f32,
477    pub entity_count: usize,
478    pub fact_count: usize,
479}
480
481/// Cached query result
482#[derive(Debug, Clone, Serialize, Deserialize)]
483pub struct CachedQueryResult {
484    pub sparql_query: String,
485    pub result_bindings: Vec<HashMap<String, String>>,
486    pub execution_time_ms: u64,
487}
488
489/// Cache statistics
490#[derive(Debug, Default, Clone, Serialize, Deserialize)]
491pub struct CacheStats {
492    pub total_requests: usize,
493    pub cache_hits: usize,
494    pub cache_misses: usize,
495    pub response_hits: usize,
496    pub context_hits: usize,
497    pub embedding_hits: usize,
498    pub query_hits: usize,
499    pub total_time_saved_ms: u64,
500    pub average_hit_time_ms: f64,
501}
502
503impl CacheStats {
504    pub fn hit_rate(&self) -> f64 {
505        if self.total_requests == 0 {
506            0.0
507        } else {
508            self.cache_hits as f64 / self.total_requests as f64
509        }
510    }
511
512    pub fn miss_rate(&self) -> f64 {
513        1.0 - self.hit_rate()
514    }
515
516    pub fn time_saved_per_hit(&self) -> f64 {
517        if self.cache_hits == 0 {
518            0.0
519        } else {
520            self.total_time_saved_ms as f64 / self.cache_hits as f64
521        }
522    }
523}
524
525impl AdvancedCacheManager {
526    pub fn new(config: CacheConfig) -> Self {
527        let response_cache = Arc::new(RwLock::new(CacheTier::new(config.response_cache.clone())));
528        let context_cache = Arc::new(RwLock::new(CacheTier::new(config.context_cache.clone())));
529        let embedding_cache = Arc::new(RwLock::new(CacheTier::new(config.embedding_cache.clone())));
530        let query_cache = Arc::new(RwLock::new(CacheTier::new(config.query_cache.clone())));
531        let hit_stats = Arc::new(RwLock::new(CacheStats::default()));
532
533        let manager = Self {
534            config: config.clone(),
535            response_cache,
536            context_cache,
537            embedding_cache,
538            query_cache,
539            hit_stats,
540        };
541
542        // Start background cleanup task
543        manager.start_cleanup_task();
544
545        // Start cache warming if enabled
546        if config.enable_warming {
547            manager.start_warming_task();
548        }
549
550        manager
551    }
552
553    /// Generate cache key from query and context
554    pub fn generate_cache_key(query: &str, context: Option<&str>) -> String {
555        let mut hasher = DefaultHasher::new();
556        query.hash(&mut hasher);
557        if let Some(ctx) = context {
558            ctx.hash(&mut hasher);
559        }
560        format!("key_{:x}", hasher.finish())
561    }
562
563    /// Cache a response
564    pub async fn cache_response(
565        &self,
566        key: String,
567        response: &LLMResponse,
568        quality_score: f32,
569    ) -> Result<()> {
570        let cached_response = CachedResponse {
571            content: response.content.clone(),
572            metadata: response.metadata.clone(),
573            quality_score,
574            generation_method: format!("{} ({})", response.provider_used, response.model_used),
575        };
576
577        let size = oxicode::serde::encode_to_vec(&cached_response, oxicode::config::standard())
578            .map_err(|e| anyhow!("Bincode encoding failed: {}", e))?
579            .len();
580        let mut cache = self.response_cache.write().await;
581        cache.put(key, cached_response, size)
582    }
583
584    /// Get cached response
585    pub async fn get_cached_response(&self, key: &str) -> Option<CachedResponse> {
586        let mut stats = self.hit_stats.write().await;
587        stats.total_requests += 1;
588
589        let mut cache = self.response_cache.write().await;
590        if let Some(response) = cache.get(key) {
591            stats.cache_hits += 1;
592            stats.response_hits += 1;
593            drop(stats);
594            debug!("Cache hit for response: {}", key);
595            Some(response)
596        } else {
597            stats.cache_misses += 1;
598            drop(stats);
599            debug!("Cache miss for response: {}", key);
600            None
601        }
602    }
603
604    /// Cache assembled context
605    pub async fn cache_context(&self, key: String, context: &AssembledContext) -> Result<()> {
606        let cached_context = CachedContext {
607            context_text: format!(
608                "{} semantic results, {} graph results",
609                context.semantic_results.len(),
610                context.graph_results.len()
611            ),
612            quality_score: context.context_score,
613            coverage_score: context.context_score,
614            entity_count: context.extracted_entities.len(),
615            fact_count: context
616                .retrieved_triples
617                .as_ref()
618                .map(|t| t.len())
619                .unwrap_or(0),
620        };
621
622        let size = oxicode::serde::encode_to_vec(&cached_context, oxicode::config::standard())
623            .map_err(|e| anyhow!("Bincode encoding failed: {}", e))?
624            .len();
625        let mut cache = self.context_cache.write().await;
626        cache.put(key, cached_context, size)
627    }
628
629    /// Get cached context
630    pub async fn get_cached_context(&self, key: &str) -> Option<CachedContext> {
631        let mut stats = self.hit_stats.write().await;
632        stats.total_requests += 1;
633
634        let mut cache = self.context_cache.write().await;
635        if let Some(context) = cache.get(key) {
636            stats.cache_hits += 1;
637            stats.context_hits += 1;
638            drop(stats);
639            debug!("Cache hit for context: {}", key);
640            Some(context)
641        } else {
642            stats.cache_misses += 1;
643            drop(stats);
644            debug!("Cache miss for context: {}", key);
645            None
646        }
647    }
648
649    /// Cache embedding vector
650    pub async fn cache_embedding(&self, key: String, embedding: Vec<f32>) -> Result<()> {
651        let size = embedding.len() * std::mem::size_of::<f32>();
652        let mut cache = self.embedding_cache.write().await;
653        cache.put(key, embedding, size)
654    }
655
656    /// Get cached embedding
657    pub async fn get_cached_embedding(&self, key: &str) -> Option<Vec<f32>> {
658        let mut stats = self.hit_stats.write().await;
659        stats.total_requests += 1;
660
661        let mut cache = self.embedding_cache.write().await;
662        if let Some(embedding) = cache.get(key) {
663            stats.cache_hits += 1;
664            stats.embedding_hits += 1;
665            drop(stats);
666            debug!("Cache hit for embedding: {}", key);
667            Some(embedding)
668        } else {
669            stats.cache_misses += 1;
670            drop(stats);
671            debug!("Cache miss for embedding: {}", key);
672            None
673        }
674    }
675
676    /// Cache SPARQL query result
677    pub async fn cache_query_result(
678        &self,
679        key: String,
680        sparql_query: String,
681        bindings: Vec<HashMap<String, String>>,
682        execution_time_ms: u64,
683    ) -> Result<()> {
684        let cached_result = CachedQueryResult {
685            sparql_query,
686            result_bindings: bindings,
687            execution_time_ms,
688        };
689
690        let size = oxicode::serde::encode_to_vec(&cached_result, oxicode::config::standard())
691            .map_err(|e| anyhow!("Bincode encoding failed: {}", e))?
692            .len();
693        let mut cache = self.query_cache.write().await;
694        cache.put(key, cached_result, size)
695    }
696
697    /// Get cached query result
698    pub async fn get_cached_query_result(&self, key: &str) -> Option<CachedQueryResult> {
699        let mut stats = self.hit_stats.write().await;
700        stats.total_requests += 1;
701
702        let mut cache = self.query_cache.write().await;
703        if let Some(result) = cache.get(key) {
704            stats.cache_hits += 1;
705            stats.query_hits += 1;
706            stats.total_time_saved_ms += result.execution_time_ms;
707            drop(stats);
708            debug!("Cache hit for query result: {}", key);
709            Some(result)
710        } else {
711            stats.cache_misses += 1;
712            drop(stats);
713            debug!("Cache miss for query result: {}", key);
714            None
715        }
716    }
717
718    /// Get comprehensive cache statistics
719    pub async fn get_cache_stats(&self) -> CacheStats {
720        self.hit_stats.read().await.clone()
721    }
722
723    /// Get detailed cache tier statistics
724    pub async fn get_detailed_stats(&self) -> HashMap<String, CacheTierStats> {
725        let mut stats = HashMap::new();
726
727        stats.insert(
728            "response".to_string(),
729            self.response_cache.read().await.get_stats(),
730        );
731        stats.insert(
732            "context".to_string(),
733            self.context_cache.read().await.get_stats(),
734        );
735        stats.insert(
736            "embedding".to_string(),
737            self.embedding_cache.read().await.get_stats(),
738        );
739        stats.insert(
740            "query".to_string(),
741            self.query_cache.read().await.get_stats(),
742        );
743
744        stats
745    }
746
747    /// Clear all caches
748    pub async fn clear_all(&self) {
749        let mut response_cache = self.response_cache.write().await;
750        let mut context_cache = self.context_cache.write().await;
751        let mut embedding_cache = self.embedding_cache.write().await;
752        let mut query_cache = self.query_cache.write().await;
753
754        response_cache.clear();
755        context_cache.clear();
756        embedding_cache.clear();
757        query_cache.clear();
758
759        let mut stats = self.hit_stats.write().await;
760        *stats = CacheStats::default();
761
762        info!("All caches cleared");
763    }
764
765    /// Start background cleanup task
766    fn start_cleanup_task(&self) {
767        let response_cache = Arc::clone(&self.response_cache);
768        let context_cache = Arc::clone(&self.context_cache);
769        let embedding_cache = Arc::clone(&self.embedding_cache);
770        let query_cache = Arc::clone(&self.query_cache);
771
772        tokio::spawn(async move {
773            let mut interval = tokio::time::interval(Duration::from_secs(300)); // Every 5 minutes
774
775            loop {
776                interval.tick().await;
777
778                let mut total_cleaned = 0;
779
780                // Cleanup expired entries in all tiers
781                {
782                    let mut cache = response_cache.write().await;
783                    total_cleaned += cache.cleanup_expired();
784                }
785                {
786                    let mut cache = context_cache.write().await;
787                    total_cleaned += cache.cleanup_expired();
788                }
789                {
790                    let mut cache = embedding_cache.write().await;
791                    total_cleaned += cache.cleanup_expired();
792                }
793                {
794                    let mut cache = query_cache.write().await;
795                    total_cleaned += cache.cleanup_expired();
796                }
797
798                if total_cleaned > 0 {
799                    info!("Cache cleanup: removed {} expired entries", total_cleaned);
800                }
801            }
802        });
803    }
804
805    /// Start cache warming task
806    fn start_warming_task(&self) {
807        let _response_cache = Arc::clone(&self.response_cache);
808        let _context_cache = Arc::clone(&self.context_cache);
809        let _embedding_cache = Arc::clone(&self.embedding_cache);
810        let _query_cache = Arc::clone(&self.query_cache);
811        let _hit_stats = Arc::clone(&self.hit_stats);
812        let strategies = self.config.warming_strategies.clone();
813
814        tokio::spawn(async move {
815            let mut interval = tokio::time::interval(Duration::from_secs(900)); // Every 15 minutes
816                                                                                // Create a temporary cache manager for warming
817            let cache_config = CacheConfig::default();
818            let cache_manager = Arc::new(AdvancedCacheManager::new(cache_config));
819            let warming_service = CacheWarmingService::new(cache_manager, strategies.clone());
820
821            loop {
822                interval.tick().await;
823
824                for strategy in &strategies {
825                    match strategy {
826                        WarmingStrategy::FrequentQueries => {
827                            // Use some sample frequent queries for warming
828                            let frequent_queries = vec!["sample query".to_string()];
829                            if let Err(e) = warming_service
830                                .warm_frequent_queries(frequent_queries)
831                                .await
832                            {
833                                warn!("Failed to warm frequent queries: {}", e);
834                            }
835                        }
836                        WarmingStrategy::RecentSessions => {
837                            // Stub implementation - in real implementation would analyze recent session patterns
838                            debug!("Warming recent sessions - not yet implemented");
839                        }
840                        WarmingStrategy::PopularEntities => {
841                            // Stub implementation - in real implementation would warm popular entity caches
842                            debug!("Warming popular entities - not yet implemented");
843                        }
844                        WarmingStrategy::PredictivePatterns => {
845                            // Stub implementation - in real implementation would use ML to predict access patterns
846                            debug!("Warming predictive patterns - not yet implemented");
847                        }
848                    }
849                }
850
851                info!("Cache warming cycle completed");
852            }
853        });
854
855        info!(
856            "Cache warming task started with strategies: {:?}",
857            self.config.warming_strategies
858        );
859    }
860
861    /// Optimize cache configuration based on usage patterns
862    pub async fn optimize_configuration(&self) -> Result<CacheConfig> {
863        let stats = self.get_cache_stats().await;
864        let detailed_stats = self.get_detailed_stats().await;
865
866        let mut optimized_config = self.config.clone();
867
868        // Adjust cache sizes based on hit rates
869        if let Some(_response_stats) = detailed_stats.get("response") {
870            if stats.response_hits > 0 && stats.hit_rate() > 0.8 {
871                // High hit rate - increase cache size
872                optimized_config.response_cache.max_size =
873                    (optimized_config.response_cache.max_size as f32 * 1.2) as usize;
874            } else if stats.hit_rate() < 0.3 {
875                // Low hit rate - decrease cache size
876                optimized_config.response_cache.max_size =
877                    (optimized_config.response_cache.max_size as f32 * 0.8) as usize;
878            }
879        }
880
881        // Adjust TTL based on access patterns
882        if stats.cache_hits > 100 && stats.average_hit_time_ms > 0.0 {
883            // If cache is being used effectively, extend TTL
884            optimized_config.response_cache.ttl = Duration::from_secs(
885                (optimized_config.response_cache.ttl.as_secs() as f32 * 1.1) as u64,
886            );
887        }
888
889        info!("Cache configuration optimized based on usage patterns");
890        Ok(optimized_config)
891    }
892}
893
894/// Cache warming service for proactive cache population
895pub struct CacheWarmingService {
896    cache_manager: Arc<AdvancedCacheManager>,
897    #[allow(dead_code)]
898    strategies: Vec<WarmingStrategy>,
899}
900
901impl CacheWarmingService {
902    pub fn new(cache_manager: Arc<AdvancedCacheManager>, strategies: Vec<WarmingStrategy>) -> Self {
903        Self {
904            cache_manager,
905            strategies,
906        }
907    }
908
909    /// Warm cache with frequent queries
910    pub async fn warm_frequent_queries(&self, queries: Vec<String>) -> Result<usize> {
911        let mut warmed_count = 0;
912
913        for query in queries {
914            // Generate embeddings and cache them
915            let embedding_key = format!(
916                "embedding_{}",
917                AdvancedCacheManager::generate_cache_key(&query, None)
918            );
919
920            // This would ideally generate actual embeddings
921            // For now, we'll create a placeholder
922            let dummy_embedding = vec![0.0f32; 768]; // Typical embedding size
923
924            if self
925                .cache_manager
926                .cache_embedding(embedding_key, dummy_embedding)
927                .await
928                .is_ok()
929            {
930                warmed_count += 1;
931            }
932        }
933
934        info!("Cache warming completed: {} entries warmed", warmed_count);
935        Ok(warmed_count)
936    }
937
938    /// Analyze usage patterns for smart warming
939    pub async fn analyze_and_warm(&self, recent_messages: &[Message]) -> Result<usize> {
940        let mut warmed_count = 0;
941
942        // Analyze patterns from recent messages
943        let patterns = self.analyze_message_patterns(recent_messages).await?;
944
945        // Generate predictions based on patterns
946        let predictions = self.generate_predictive_cache_keys(&patterns).await?;
947
948        // Warm cache with predicted items
949        for prediction in predictions {
950            match prediction.cache_type {
951                PredictiveCacheType::Response => {
952                    // Pre-generate likely responses
953                    if self
954                        .warm_response_cache(&prediction.key, &prediction.context)
955                        .await
956                        .is_ok()
957                    {
958                        warmed_count += 1;
959                    }
960                }
961                PredictiveCacheType::Context => {
962                    // Pre-build likely contexts
963                    if self
964                        .warm_context_cache(&prediction.key, &prediction.context)
965                        .await
966                        .is_ok()
967                    {
968                        warmed_count += 1;
969                    }
970                }
971                PredictiveCacheType::Embedding => {
972                    // Pre-compute embeddings for likely queries
973                    if self.warm_embedding_cache(&prediction.key).await.is_ok() {
974                        warmed_count += 1;
975                    }
976                }
977                PredictiveCacheType::Query => {
978                    // Pre-execute likely SPARQL queries
979                    if self
980                        .warm_query_cache(&prediction.key, &prediction.context)
981                        .await
982                        .is_ok()
983                    {
984                        warmed_count += 1;
985                    }
986                }
987            }
988        }
989
990        info!(
991            "Pattern-based cache warming completed: {} entries warmed",
992            warmed_count
993        );
994        Ok(warmed_count)
995    }
996
997    /// Analyze message patterns to identify trends and predict future needs
998    async fn analyze_message_patterns(&self, messages: &[Message]) -> Result<ConversationPatterns> {
999        let mut patterns = ConversationPatterns::new();
1000
1001        // Extract keywords and entities from recent messages
1002        for message in messages.iter().rev().take(50) {
1003            // Analyze last 50 messages
1004            let text = message.content.to_text();
1005
1006            // Extract entities (simple word frequency for now)
1007            let words: Vec<&str> = text
1008                .split_whitespace()
1009                .filter(|w| w.len() > 3) // Filter out short words
1010                .collect();
1011
1012            for word in words {
1013                let normalized = word.to_lowercase();
1014                *patterns.keyword_frequency.entry(normalized).or_insert(0) += 1;
1015            }
1016
1017            // Identify query patterns
1018            if text.contains('?')
1019                || text.to_lowercase().contains("what")
1020                || text.to_lowercase().contains("how")
1021                || text.to_lowercase().contains("when")
1022                || text.to_lowercase().contains("where")
1023                || text.to_lowercase().contains("why")
1024            {
1025                patterns.question_patterns += 1;
1026            }
1027
1028            // Identify domain-specific patterns
1029            if text.to_lowercase().contains("sparql") || text.to_lowercase().contains("query") {
1030                patterns.sparql_requests += 1;
1031            }
1032
1033            if text.to_lowercase().contains("graph") || text.to_lowercase().contains("triple") {
1034                patterns.graph_operations += 1;
1035            }
1036
1037            // Track temporal patterns
1038            let time_since_creation = message.timestamp.timestamp() % 86400; // Seconds in day
1039            let hour = (time_since_creation / 3600) as usize;
1040            if hour < 24 {
1041                patterns.hourly_activity[hour] += 1;
1042            }
1043        }
1044
1045        // Calculate trends and confidence scores
1046        patterns.calculate_confidence();
1047
1048        Ok(patterns)
1049    }
1050
1051    /// Generate predictive cache keys based on identified patterns
1052    async fn generate_predictive_cache_keys(
1053        &self,
1054        patterns: &ConversationPatterns,
1055    ) -> Result<Vec<CachePrediction>> {
1056        let mut predictions = Vec::new();
1057
1058        // Generate predictions based on frequent keywords
1059        for (keyword, frequency) in &patterns.keyword_frequency {
1060            if *frequency >= 3 {
1061                // Threshold for prediction
1062                // Predict similar queries
1063                predictions.push(CachePrediction {
1064                    key: format!("similar_to_{keyword}"),
1065                    cache_type: PredictiveCacheType::Query,
1066                    confidence: (*frequency as f64 / patterns.total_messages as f64).min(1.0),
1067                    context: format!("Predicted query related to: {keyword}"),
1068                });
1069
1070                // Predict related embeddings
1071                predictions.push(CachePrediction {
1072                    key: format!("embedding_{keyword}"),
1073                    cache_type: PredictiveCacheType::Embedding,
1074                    confidence: (*frequency as f64 / patterns.total_messages as f64).min(1.0),
1075                    context: keyword.clone(),
1076                });
1077            }
1078        }
1079
1080        // Generate predictions based on query patterns
1081        if patterns.question_patterns > 0 {
1082            predictions.push(CachePrediction {
1083                key: "common_question_contexts".to_string(),
1084                cache_type: PredictiveCacheType::Context,
1085                confidence: patterns.question_confidence,
1086                context: "Frequently asked question context".to_string(),
1087            });
1088        }
1089
1090        // Generate SPARQL-related predictions
1091        if patterns.sparql_requests > 0 {
1092            predictions.push(CachePrediction {
1093                key: "sparql_template_context".to_string(),
1094                cache_type: PredictiveCacheType::Context,
1095                confidence: patterns.sparql_confidence,
1096                context: "SPARQL query context".to_string(),
1097            });
1098        }
1099
1100        // Sort by confidence and take top predictions
1101        // Use unwrap_or to handle NaN values gracefully (treat as less than)
1102        predictions.sort_by(|a, b| {
1103            b.confidence
1104                .partial_cmp(&a.confidence)
1105                .unwrap_or(std::cmp::Ordering::Less)
1106        });
1107        predictions.truncate(20); // Limit to top 20 predictions
1108
1109        Ok(predictions)
1110    }
1111
1112    /// Warm response cache with predicted responses
1113    async fn warm_response_cache(&self, key: &str, context: &str) -> Result<()> {
1114        // Create a mock response for caching
1115        let mock_response = LLMResponse {
1116            content: format!("Cached response for: {context}"),
1117            model_used: "cache-warmer".to_string(),
1118            provider_used: "internal".to_string(),
1119            usage: crate::llm::Usage {
1120                prompt_tokens: 0,
1121                completion_tokens: 0,
1122                total_tokens: 0,
1123                cost: 0.0,
1124            },
1125            latency: Duration::from_millis(1),
1126            quality_score: Some(0.9),
1127            metadata: HashMap::new(),
1128        };
1129
1130        self.cache_manager
1131            .cache_response(key.to_string(), &mock_response, 0.9)
1132            .await?;
1133        Ok(())
1134    }
1135
1136    /// Warm context cache with predicted contexts
1137    async fn warm_context_cache(&self, key: &str, _context: &str) -> Result<()> {
1138        // Create a mock context for caching
1139        let mock_context = AssembledContext {
1140            retrieved_triples: None,
1141            semantic_results: Vec::new(),
1142            graph_results: Vec::new(),
1143            quantum_results: None,
1144            consciousness_insights: None,
1145            extracted_entities: Vec::new(),
1146            extracted_relationships: Vec::new(),
1147            query_constraints: Vec::new(),
1148            reasoning_results: None,
1149            extracted_knowledge: None,
1150            context_score: 0.8,
1151            assembly_time: Duration::from_millis(100),
1152        };
1153
1154        self.cache_manager
1155            .cache_context(key.to_string(), &mock_context)
1156            .await?;
1157        Ok(())
1158    }
1159
1160    /// Warm embedding cache with predicted embeddings
1161    async fn warm_embedding_cache(&self, key: &str) -> Result<()> {
1162        // Create a mock embedding for caching
1163        let mock_embedding = vec![0.1f32; 384]; // Standard embedding dimension
1164
1165        self.cache_manager
1166            .cache_embedding(key.to_string(), mock_embedding)
1167            .await?;
1168        Ok(())
1169    }
1170
1171    /// Warm query cache with predicted query results
1172    async fn warm_query_cache(&self, key: &str, context: &str) -> Result<()> {
1173        // Create mock SPARQL query results for caching
1174        let mock_bindings = vec![HashMap::new()]; // Empty binding set
1175
1176        self.cache_manager
1177            .cache_query_result(
1178                key.to_string(),
1179                format!("SELECT * WHERE {{ # Predicted query for: {context} }}"),
1180                mock_bindings,
1181                100, // Mock execution time
1182            )
1183            .await?;
1184        Ok(())
1185    }
1186}