Skip to main content

oxirs_chat/llm/
cache.rs

1//! Response Cache for LLM Requests
2//!
3//! Provides LRU caching for LLM responses to reduce API costs and improve latency.
4
5use anyhow::Result;
6use std::{
7    collections::HashMap,
8    sync::{
9        atomic::{AtomicU64, Ordering},
10        Arc,
11    },
12    time::{Duration, SystemTime},
13};
14use tokio::sync::RwLock;
15
16use super::types::{LLMRequest, LLMResponse};
17
18/// Hash key for request caching
19type RequestHash = u64;
20
21/// Cached response with metadata
22#[derive(Debug, Clone)]
23pub struct CachedResponse {
24    pub response: LLMResponse,
25    pub provider_id: String,
26    pub timestamp: SystemTime,
27    pub ttl: Duration,
28    pub access_count: u32,
29}
30
31impl CachedResponse {
32    pub fn is_expired(&self) -> bool {
33        SystemTime::now()
34            .duration_since(self.timestamp)
35            .map(|elapsed| elapsed > self.ttl)
36            .unwrap_or(true)
37    }
38}
39
40/// Cache configuration
41#[derive(Debug, Clone)]
42pub struct CacheConfig {
43    pub max_size: usize,
44    pub ttl_seconds: u64,
45    pub enable_metrics: bool,
46}
47
48impl Default for CacheConfig {
49    fn default() -> Self {
50        Self {
51            max_size: 1000,
52            ttl_seconds: 3600, // 1 hour
53            enable_metrics: true,
54        }
55    }
56}
57
58/// Cache metrics for monitoring
59#[derive(Debug, Clone, Default)]
60pub struct CacheMetrics {
61    pub hits: u64,
62    pub misses: u64,
63    pub evictions: u64,
64    pub total_requests: u64,
65}
66
67impl CacheMetrics {
68    pub fn hit_rate(&self) -> f64 {
69        if self.total_requests == 0 {
70            0.0
71        } else {
72            self.hits as f64 / self.total_requests as f64
73        }
74    }
75}
76
77/// LRU Cache entry for ordering
78#[derive(Debug, Clone)]
79struct LruEntry {
80    cached_response: CachedResponse,
81    /// Monotonic access rank used for LRU ordering.
82    ///
83    /// Deliberately a monotonic counter rather than `SystemTime`: the wall
84    /// clock is non-monotonic and too coarse to order operations that occur
85    /// within the same tick, which would make eviction pick a non-deterministic
86    /// victim under fast/parallel access.
87    last_accessed: u64,
88}
89
90/// Response cache with LRU eviction
91pub struct ResponseCache {
92    cache: Arc<RwLock<HashMap<RequestHash, LruEntry>>>,
93    config: CacheConfig,
94    metrics: Arc<RwLock<CacheMetrics>>,
95    /// Monotonically increasing access clock feeding `LruEntry::last_accessed`.
96    access_tick: Arc<AtomicU64>,
97}
98
99impl ResponseCache {
100    pub fn new(config: CacheConfig) -> Self {
101        Self {
102            cache: Arc::new(RwLock::new(HashMap::new())),
103            config,
104            metrics: Arc::new(RwLock::new(CacheMetrics::default())),
105            access_tick: Arc::new(AtomicU64::new(0)),
106        }
107    }
108
109    /// Return the next strictly-increasing access rank for LRU ordering.
110    fn next_tick(&self) -> u64 {
111        self.access_tick.fetch_add(1, Ordering::Relaxed)
112    }
113
114    /// Generate hash for request
115    fn hash_request(request: &LLMRequest) -> RequestHash {
116        use std::collections::hash_map::DefaultHasher;
117        use std::hash::{Hash, Hasher};
118
119        let mut hasher = DefaultHasher::new();
120
121        // Hash messages
122        for msg in &request.messages {
123            msg.role.hash(&mut hasher);
124            msg.content.hash(&mut hasher);
125        }
126
127        // Hash system prompt
128        if let Some(ref prompt) = request.system_prompt {
129            prompt.hash(&mut hasher);
130        }
131
132        // Hash temperature (convert to bits for consistent hashing)
133        ((request.temperature * 1000.0) as u64).hash(&mut hasher);
134
135        // Hash max_tokens
136        request.max_tokens.hash(&mut hasher);
137
138        hasher.finish()
139    }
140
141    /// Get cached response if available
142    pub async fn get(&self, request: &LLMRequest) -> Option<LLMResponse> {
143        let hash = Self::hash_request(request);
144        let mut cache = self.cache.write().await;
145
146        if let Some(entry) = cache.get_mut(&hash) {
147            // Check if expired
148            if entry.cached_response.is_expired() {
149                cache.remove(&hash);
150                self.record_miss().await;
151                return None;
152            }
153
154            // Update access rank and count
155            entry.last_accessed = self.next_tick();
156            entry.cached_response.access_count += 1;
157
158            self.record_hit().await;
159            Some(entry.cached_response.response.clone())
160        } else {
161            self.record_miss().await;
162            None
163        }
164    }
165
166    /// Store response in cache
167    pub async fn put(&self, request: &LLMRequest, response: LLMResponse, provider_id: String) {
168        let hash = Self::hash_request(request);
169        let mut cache = self.cache.write().await;
170
171        // Check if we need to evict
172        if cache.len() >= self.config.max_size && !cache.contains_key(&hash) {
173            self.evict_lru(&mut cache).await;
174        }
175
176        let cached_response = CachedResponse {
177            response,
178            provider_id,
179            timestamp: SystemTime::now(),
180            ttl: Duration::from_secs(self.config.ttl_seconds),
181            access_count: 1,
182        };
183
184        let entry = LruEntry {
185            cached_response,
186            last_accessed: self.next_tick(),
187        };
188
189        cache.insert(hash, entry);
190    }
191
192    /// Evict least recently used entry
193    async fn evict_lru(&self, cache: &mut HashMap<RequestHash, LruEntry>) {
194        if cache.is_empty() {
195            return;
196        }
197
198        // Find LRU entry
199        let lru_key = cache
200            .iter()
201            .min_by_key(|(_, entry)| entry.last_accessed)
202            .map(|(k, _)| *k);
203
204        if let Some(key) = lru_key {
205            cache.remove(&key);
206
207            // Record eviction
208            if self.config.enable_metrics {
209                let mut metrics = self.metrics.write().await;
210                metrics.evictions += 1;
211            }
212        }
213    }
214
215    /// Remove expired entries
216    pub async fn invalidate_expired(&self) -> Result<usize> {
217        let mut cache = self.cache.write().await;
218        let now = SystemTime::now();
219
220        let expired_keys: Vec<RequestHash> = cache
221            .iter()
222            .filter(|(_, entry)| {
223                now.duration_since(entry.cached_response.timestamp)
224                    .map(|elapsed| elapsed > entry.cached_response.ttl)
225                    .unwrap_or(true)
226            })
227            .map(|(k, _)| *k)
228            .collect();
229
230        let count = expired_keys.len();
231        for key in expired_keys {
232            cache.remove(&key);
233        }
234
235        Ok(count)
236    }
237
238    /// Clear all cached entries
239    pub async fn clear(&self) -> Result<()> {
240        let mut cache = self.cache.write().await;
241        cache.clear();
242        Ok(())
243    }
244
245    /// Get current cache size
246    pub async fn size(&self) -> usize {
247        let cache = self.cache.read().await;
248        cache.len()
249    }
250
251    /// Get cache metrics
252    pub async fn get_metrics(&self) -> CacheMetrics {
253        let metrics = self.metrics.read().await;
254        metrics.clone()
255    }
256
257    /// Calculate hit rate
258    pub async fn hit_rate(&self) -> f64 {
259        let metrics = self.metrics.read().await;
260        metrics.hit_rate()
261    }
262
263    async fn record_hit(&self) {
264        if self.config.enable_metrics {
265            let mut metrics = self.metrics.write().await;
266            metrics.hits += 1;
267            metrics.total_requests += 1;
268        }
269    }
270
271    async fn record_miss(&self) {
272        if self.config.enable_metrics {
273            let mut metrics = self.metrics.write().await;
274            metrics.misses += 1;
275            metrics.total_requests += 1;
276        }
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283    use crate::llm::types::{ChatMessage, ChatRole, Priority, Usage, UseCase};
284
285    fn create_test_request(content: &str) -> LLMRequest {
286        LLMRequest {
287            messages: vec![ChatMessage {
288                role: ChatRole::User,
289                content: content.to_string(),
290                metadata: None,
291            }],
292            system_prompt: Some("Test prompt".to_string()),
293            temperature: 0.7,
294            max_tokens: Some(100),
295            use_case: UseCase::Conversation,
296            priority: Priority::Normal,
297            timeout: None,
298        }
299    }
300
301    fn create_test_response(content: &str) -> LLMResponse {
302        LLMResponse {
303            content: content.to_string(),
304            model_used: "test-model".to_string(),
305            provider_used: "test-provider".to_string(),
306            usage: Usage {
307                prompt_tokens: 10,
308                completion_tokens: 20,
309                total_tokens: 30,
310                cost: 0.001,
311            },
312            latency: Duration::from_millis(100),
313            quality_score: Some(0.9),
314            metadata: std::collections::HashMap::new(),
315        }
316    }
317
318    #[tokio::test]
319    async fn test_cache_hit() {
320        let cache = ResponseCache::new(CacheConfig::default());
321        let request = create_test_request("test query");
322        let response = create_test_response("test response");
323
324        // Store response
325        cache
326            .put(&request, response.clone(), "test-provider".to_string())
327            .await;
328
329        // Retrieve response
330        let cached = cache.get(&request).await;
331        assert!(cached.is_some());
332        assert_eq!(
333            cached.as_ref().expect("should succeed").content,
334            response.content
335        );
336
337        // Check metrics
338        let metrics = cache.get_metrics().await;
339        assert_eq!(metrics.hits, 1);
340        assert_eq!(metrics.misses, 0);
341    }
342
343    #[tokio::test]
344    async fn test_cache_miss() {
345        let cache = ResponseCache::new(CacheConfig::default());
346        let request = create_test_request("test query");
347
348        // Try to retrieve non-existent response
349        let cached = cache.get(&request).await;
350        assert!(cached.is_none());
351
352        // Check metrics
353        let metrics = cache.get_metrics().await;
354        assert_eq!(metrics.hits, 0);
355        assert_eq!(metrics.misses, 1);
356    }
357
358    #[tokio::test]
359    async fn test_cache_expiration() {
360        let config = CacheConfig {
361            ttl_seconds: 1, // 1 second TTL
362            ..Default::default()
363        };
364
365        let cache = ResponseCache::new(config);
366        let request = create_test_request("test query");
367        let response = create_test_response("test response");
368
369        // Store response
370        cache
371            .put(&request, response.clone(), "test-provider".to_string())
372            .await;
373
374        // Wait for expiration
375        tokio::time::sleep(Duration::from_secs(2)).await;
376
377        // Try to retrieve expired response
378        let cached = cache.get(&request).await;
379        assert!(cached.is_none());
380    }
381
382    #[tokio::test]
383    async fn test_lru_eviction() {
384        let config = CacheConfig {
385            max_size: 2,
386            ..Default::default()
387        };
388
389        let cache = ResponseCache::new(config);
390
391        // Fill cache
392        let req1 = create_test_request("query 1");
393        let req2 = create_test_request("query 2");
394        let req3 = create_test_request("query 3");
395
396        cache
397            .put(
398                &req1,
399                create_test_response("response 1"),
400                "provider1".to_string(),
401            )
402            .await;
403        cache
404            .put(
405                &req2,
406                create_test_response("response 2"),
407                "provider2".to_string(),
408            )
409            .await;
410
411        // Access req1 to make it more recent
412        let _ = cache.get(&req1).await;
413
414        // Add req3, should evict req2 (least recently used)
415        cache
416            .put(
417                &req3,
418                create_test_response("response 3"),
419                "provider3".to_string(),
420            )
421            .await;
422
423        // req1 and req3 should exist, req2 should be evicted
424        assert!(cache.get(&req1).await.is_some());
425        assert!(cache.get(&req2).await.is_none());
426        assert!(cache.get(&req3).await.is_some());
427    }
428
429    #[tokio::test]
430    async fn test_hit_rate_calculation() {
431        let cache = ResponseCache::new(CacheConfig::default());
432        let request = create_test_request("test query");
433        let response = create_test_response("test response");
434
435        // Store response
436        cache
437            .put(&request, response.clone(), "test-provider".to_string())
438            .await;
439
440        // 3 hits, 2 misses = 60% hit rate
441        let _ = cache.get(&request).await; // hit
442        let _ = cache.get(&request).await; // hit
443        let _ = cache.get(&request).await; // hit
444        let _ = cache.get(&create_test_request("other query")).await; // miss
445        let _ = cache.get(&create_test_request("another query")).await; // miss
446
447        let hit_rate = cache.hit_rate().await;
448        assert!((hit_rate - 0.6).abs() < 0.01); // 3/5 = 0.6
449    }
450}