Skip to main content

oxirs_chat/cache/
semantic.rs

1//! Semantic Caching System
2//!
3//! Caches query results based on semantic similarity rather than exact matching.
4
5use anyhow::Result;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::sync::Arc;
9use std::time::{Duration, Instant};
10use tokio::sync::RwLock;
11use tracing::{debug, info};
12
13use scirs2_core::ndarray_ext::Array1;
14// Note: cosine_similarity implementation available in crate::utils::stats if needed
15
16/// Semantic cache entry
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct CacheEntry {
19    /// Original query
20    pub query: String,
21    /// Query embedding
22    #[serde(skip)]
23    pub embedding: Option<Array1<f32>>,
24    /// Cached result
25    pub result: CachedResult,
26    /// Cache timestamp
27    #[serde(skip)]
28    #[serde(default = "Instant::now")]
29    pub timestamp: Instant,
30    /// Hit count
31    pub hit_count: usize,
32    /// Last access time
33    #[serde(skip)]
34    #[serde(default = "Instant::now")]
35    pub last_access: Instant,
36    /// TTL (time-to-live)
37    #[serde(skip)]
38    #[serde(default = "default_ttl")]
39    pub ttl: Duration,
40}
41
42fn default_ttl() -> Duration {
43    Duration::from_secs(3600)
44}
45
46/// Cached result
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct CachedResult {
49    /// Result data (JSON-serialized)
50    pub data: String,
51    /// Result metadata
52    pub metadata: HashMap<String, String>,
53    /// Computation time in milliseconds (for cache efficiency metrics)
54    pub computation_time_ms: u64,
55}
56
57/// Semantic cache configuration
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct SemanticCacheConfig {
60    /// Similarity threshold for cache hits (0.0 - 1.0)
61    pub similarity_threshold: f32,
62    /// Maximum cache size (number of entries)
63    pub max_size: usize,
64    /// Default TTL for cache entries
65    pub default_ttl: Duration,
66    /// Enable embedding-based similarity
67    pub use_embeddings: bool,
68    /// Eviction strategy
69    pub eviction_strategy: EvictionStrategy,
70    /// Enable statistics tracking
71    pub track_statistics: bool,
72}
73
74impl Default for SemanticCacheConfig {
75    fn default() -> Self {
76        Self {
77            similarity_threshold: 0.85,
78            max_size: 1000,
79            default_ttl: Duration::from_secs(3600), // 1 hour
80            use_embeddings: true,
81            eviction_strategy: EvictionStrategy::LRU,
82            track_statistics: true,
83        }
84    }
85}
86
87/// Cache eviction strategy
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89pub enum EvictionStrategy {
90    /// Least Recently Used
91    LRU,
92    /// Least Frequently Used
93    LFU,
94    /// Time To Live
95    TTL,
96    /// First In First Out
97    FIFO,
98}
99
100/// Cache statistics
101#[derive(Debug, Clone, Default, Serialize, Deserialize)]
102pub struct CacheStatistics {
103    /// Total cache hits
104    pub hits: usize,
105    /// Total cache misses
106    pub misses: usize,
107    /// Total queries processed
108    pub total_queries: usize,
109    /// Cache hit rate
110    pub hit_rate: f64,
111    /// Average similarity score for hits
112    pub avg_similarity: f32,
113    /// Total time saved by caching
114    pub time_saved: Duration,
115    /// Current cache size
116    pub current_size: usize,
117    /// Eviction count
118    pub evictions: usize,
119}
120
121/// Semantic cache
122pub struct SemanticCache {
123    config: SemanticCacheConfig,
124    entries: Arc<RwLock<HashMap<String, CacheEntry>>>,
125    statistics: Arc<RwLock<CacheStatistics>>,
126}
127
128impl SemanticCache {
129    /// Create a new semantic cache
130    pub fn new(config: SemanticCacheConfig) -> Self {
131        info!(
132            "Initialized semantic cache with similarity threshold: {}",
133            config.similarity_threshold
134        );
135
136        Self {
137            config,
138            entries: Arc::new(RwLock::new(HashMap::new())),
139            statistics: Arc::new(RwLock::new(CacheStatistics::default())),
140        }
141    }
142
143    /// Get cached result for a query
144    pub async fn get(&self, query: &str) -> Result<Option<CachedResult>> {
145        debug!("Checking semantic cache for query: {}", query);
146
147        let entries = self.entries.read().await;
148
149        // Check for exact match first (fast path)
150        if let Some(entry) = entries.get(query) {
151            if !self.is_expired(entry) {
152                self.record_hit(entry).await;
153                return Ok(Some(entry.result.clone()));
154            }
155        }
156
157        // Semantic similarity search (if embeddings enabled)
158        if self.config.use_embeddings {
159            let query_embedding = self.compute_embedding(query)?;
160
161            for entry in entries.values() {
162                if self.is_expired(entry) {
163                    continue;
164                }
165
166                if let Some(ref entry_embedding) = entry.embedding {
167                    let similarity = self.compute_similarity(&query_embedding, entry_embedding)?;
168
169                    if similarity >= self.config.similarity_threshold {
170                        debug!("Semantic cache hit with similarity: {:.3}", similarity);
171                        self.record_hit_with_similarity(entry, similarity).await;
172                        return Ok(Some(entry.result.clone()));
173                    }
174                }
175            }
176        }
177
178        // Cache miss
179        self.record_miss().await;
180        Ok(None)
181    }
182
183    /// Put result in cache
184    pub async fn put(
185        &self,
186        query: String,
187        result: CachedResult,
188        embedding: Option<Array1<f32>>,
189    ) -> Result<()> {
190        let mut entries = self.entries.write().await;
191
192        // Evict if at capacity
193        if entries.len() >= self.config.max_size {
194            self.evict(&mut entries).await?;
195        }
196
197        let entry = CacheEntry {
198            query: query.clone(),
199            embedding,
200            result,
201            timestamp: Instant::now(),
202            hit_count: 0,
203            last_access: Instant::now(),
204            ttl: self.config.default_ttl,
205        };
206
207        entries.insert(query, entry);
208        self.update_size(entries.len()).await;
209
210        Ok(())
211    }
212
213    /// Invalidate cache entry
214    pub async fn invalidate(&self, query: &str) -> Result<bool> {
215        let mut entries = self.entries.write().await;
216        let removed = entries.remove(query).is_some();
217        self.update_size(entries.len()).await;
218        Ok(removed)
219    }
220
221    /// Clear all cache entries
222    pub async fn clear(&self) -> Result<()> {
223        let mut entries = self.entries.write().await;
224        entries.clear();
225        self.update_size(0).await;
226        Ok(())
227    }
228
229    /// Clean expired entries
230    pub async fn cleanup_expired(&self) -> Result<usize> {
231        let mut entries = self.entries.write().await;
232        let initial_size = entries.len();
233
234        entries.retain(|_, entry| !self.is_expired(entry));
235
236        let removed = initial_size - entries.len();
237        self.update_size(entries.len()).await;
238
239        if removed > 0 {
240            info!("Cleaned up {} expired cache entries", removed);
241        }
242
243        Ok(removed)
244    }
245
246    /// Get cache statistics
247    pub async fn statistics(&self) -> CacheStatistics {
248        self.statistics.read().await.clone()
249    }
250
251    /// Reset statistics
252    pub async fn reset_statistics(&self) -> Result<()> {
253        let mut stats = self.statistics.write().await;
254        *stats = CacheStatistics::default();
255        Ok(())
256    }
257
258    // Helper methods
259
260    fn is_expired(&self, entry: &CacheEntry) -> bool {
261        entry.timestamp.elapsed() > entry.ttl
262    }
263
264    async fn record_hit(&self, entry: &CacheEntry) {
265        if !self.config.track_statistics {
266            return;
267        }
268
269        let mut stats = self.statistics.write().await;
270        stats.hits += 1;
271        stats.total_queries += 1;
272        stats.hit_rate = stats.hits as f64 / stats.total_queries as f64;
273        stats.time_saved += Duration::from_millis(entry.result.computation_time_ms);
274    }
275
276    async fn record_hit_with_similarity(&self, entry: &CacheEntry, similarity: f32) {
277        if !self.config.track_statistics {
278            return;
279        }
280
281        let mut stats = self.statistics.write().await;
282        stats.hits += 1;
283        stats.total_queries += 1;
284        stats.hit_rate = stats.hits as f64 / stats.total_queries as f64;
285        stats.time_saved += Duration::from_millis(entry.result.computation_time_ms);
286
287        // Update average similarity
288        let total_similarity = stats.avg_similarity * (stats.hits - 1) as f32 + similarity;
289        stats.avg_similarity = total_similarity / stats.hits as f32;
290    }
291
292    async fn record_miss(&self) {
293        if !self.config.track_statistics {
294            return;
295        }
296
297        let mut stats = self.statistics.write().await;
298        stats.misses += 1;
299        stats.total_queries += 1;
300        stats.hit_rate = stats.hits as f64 / stats.total_queries as f64;
301    }
302
303    async fn update_size(&self, size: usize) {
304        if !self.config.track_statistics {
305            return;
306        }
307
308        let mut stats = self.statistics.write().await;
309        stats.current_size = size;
310    }
311
312    fn compute_embedding(&self, _query: &str) -> Result<Array1<f32>> {
313        // Simplified - would use actual embedding model
314        // For now, return a dummy embedding
315        Ok(Array1::zeros(384))
316    }
317
318    fn compute_similarity(&self, emb1: &Array1<f32>, emb2: &Array1<f32>) -> Result<f32> {
319        // Use cosine similarity
320        let dot_product: f32 = emb1.iter().zip(emb2.iter()).map(|(a, b)| a * b).sum();
321        let norm1: f32 = emb1.iter().map(|a| a * a).sum::<f32>().sqrt();
322        let norm2: f32 = emb2.iter().map(|a| a * a).sum::<f32>().sqrt();
323
324        if norm1 == 0.0 || norm2 == 0.0 {
325            return Ok(0.0);
326        }
327
328        Ok(dot_product / (norm1 * norm2))
329    }
330
331    async fn evict(&self, entries: &mut HashMap<String, CacheEntry>) -> Result<()> {
332        if entries.is_empty() {
333            return Ok(());
334        }
335
336        let key_to_remove = match self.config.eviction_strategy {
337            EvictionStrategy::LRU => {
338                // Remove least recently used
339                entries
340                    .iter()
341                    .min_by_key(|(_, entry)| entry.last_access)
342                    .map(|(key, _)| key.clone())
343            }
344            EvictionStrategy::LFU => {
345                // Remove least frequently used
346                entries
347                    .iter()
348                    .min_by_key(|(_, entry)| entry.hit_count)
349                    .map(|(key, _)| key.clone())
350            }
351            EvictionStrategy::TTL => {
352                // Remove oldest entry
353                entries
354                    .iter()
355                    .min_by_key(|(_, entry)| entry.timestamp)
356                    .map(|(key, _)| key.clone())
357            }
358            EvictionStrategy::FIFO => {
359                // Remove first inserted (oldest timestamp)
360                entries
361                    .iter()
362                    .min_by_key(|(_, entry)| entry.timestamp)
363                    .map(|(key, _)| key.clone())
364            }
365        };
366
367        if let Some(key) = key_to_remove {
368            entries.remove(&key);
369
370            if self.config.track_statistics {
371                let mut stats = self.statistics.write().await;
372                stats.evictions += 1;
373            }
374        }
375
376        Ok(())
377    }
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383
384    #[tokio::test]
385    async fn test_exact_match_cache() {
386        let cache = SemanticCache::new(SemanticCacheConfig::default());
387
388        let result = CachedResult {
389            data: "test data".to_string(),
390            metadata: HashMap::new(),
391            computation_time_ms: 100,
392        };
393
394        cache
395            .put("test query".to_string(), result.clone(), None)
396            .await
397            .expect("should succeed");
398
399        let cached = cache.get("test query").await.expect("should succeed");
400        assert!(cached.is_some());
401        assert_eq!(cached.expect("should succeed").data, "test data");
402    }
403
404    #[tokio::test]
405    async fn test_cache_miss() {
406        let cache = SemanticCache::new(SemanticCacheConfig::default());
407
408        let cached = cache
409            .get("nonexistent query")
410            .await
411            .expect("should succeed");
412        assert!(cached.is_none());
413    }
414
415    #[tokio::test]
416    async fn test_cache_invalidation() {
417        let cache = SemanticCache::new(SemanticCacheConfig::default());
418
419        let result = CachedResult {
420            data: "test data".to_string(),
421            metadata: HashMap::new(),
422            computation_time_ms: 100,
423        };
424
425        cache
426            .put("test query".to_string(), result, None)
427            .await
428            .expect("should succeed");
429        assert!(cache
430            .get("test query")
431            .await
432            .expect("should succeed")
433            .is_some());
434
435        cache
436            .invalidate("test query")
437            .await
438            .expect("should succeed");
439        assert!(cache
440            .get("test query")
441            .await
442            .expect("should succeed")
443            .is_none());
444    }
445
446    #[tokio::test]
447    async fn test_cache_statistics() {
448        let cache = SemanticCache::new(SemanticCacheConfig::default());
449
450        let result = CachedResult {
451            data: "test data".to_string(),
452            metadata: HashMap::new(),
453            computation_time_ms: 100,
454        };
455
456        cache
457            .put("test query".to_string(), result, None)
458            .await
459            .expect("should succeed");
460        cache.get("test query").await.expect("should succeed"); // Hit
461        cache.get("other query").await.expect("should succeed"); // Miss
462
463        let stats = cache.statistics().await;
464        assert_eq!(stats.hits, 1);
465        assert_eq!(stats.misses, 1);
466        assert_eq!(stats.total_queries, 2);
467        assert_eq!(stats.hit_rate, 0.5);
468    }
469
470    #[tokio::test]
471    async fn test_cache_eviction() {
472        let config = SemanticCacheConfig {
473            max_size: 2,
474            ..Default::default()
475        };
476
477        let cache = SemanticCache::new(config);
478
479        let result = CachedResult {
480            data: "test".to_string(),
481            metadata: HashMap::new(),
482            computation_time_ms: 100,
483        };
484
485        cache
486            .put("query1".to_string(), result.clone(), None)
487            .await
488            .expect("should succeed");
489        cache
490            .put("query2".to_string(), result.clone(), None)
491            .await
492            .expect("should succeed");
493        cache
494            .put("query3".to_string(), result.clone(), None)
495            .await
496            .expect("should succeed"); // Should evict one
497
498        let stats = cache.statistics().await;
499        assert_eq!(stats.current_size, 2);
500        assert_eq!(stats.evictions, 1);
501    }
502}