""" Cache Manager implementation for the voice control optimization system. This module provides intelligent caching of transcription results using audio fingerprinting to avoid redundant API calls and improve response times. """ import asyncio import hashlib import logging import time from collections import OrderedDict from typing import Dict, Optional, Any, Set, List, Callable from datetime import datetime, timedelta from dataclasses import dataclass, field from .interfaces import CacheManagerInterface from .models import TranscriptionResult, CacheStats from .exceptions import CacheError logger = logging.getLogger(__name__) @dataclass class CacheEntry: """Represents a cached transcription result with metadata.""" result: TranscriptionResult created_at: float last_accessed: float ttl: int access_count: int = 0 size_bytes: int = 0 def __post_init__(self): """Calculate entry size after initialization.""" if self.size_bytes == 0: self.size_bytes = self._calculate_size() def _calculate_size(self) -> int: """Calculate approximate memory size of the cache entry.""" # Base size for the entry object size = 200 # Approximate overhead # Size of transcription result size += len(self.result.text.encode('utf-8')) size += len(self.result.provider.encode('utf-8')) size += len(self.result.language.encode('utf-8')) # Size of alternatives for alt in self.result.alternatives: size += len(alt.encode('utf-8')) # Size of word timestamps if present if self.result.word_timestamps: for word_ts in self.result.word_timestamps: size += len(word_ts.word.encode('utf-8')) + 32 # word + timestamps return size @property def is_expired(self) -> bool: """Check if the cache entry has expired.""" return time.time() - self.created_at > self.ttl def touch(self) -> None: """Update last accessed time and increment access count.""" self.last_accessed = time.time() self.access_count += 1 class CacheManager(CacheManagerInterface): """ Manages caching of transcription results with LRU eviction and TTL expiration. Features: - Audio fingerprint-based cache keys - LRU (Least Recently Used) eviction policy - TTL (Time To Live) based expiration - Configurable size limits - Cache statistics tracking """ def __init__( self, max_size_mb: int = 100, default_ttl: int = 3600, cleanup_interval: int = 600, enable_stats: bool = True ): """ Initialize the cache manager. Args: max_size_mb: Maximum cache size in megabytes default_ttl: Default time-to-live in seconds cleanup_interval: Interval for cleanup tasks in seconds enable_stats: Whether to track cache statistics """ self.max_size_bytes = max_size_mb * 1024 * 1024 self.default_ttl = default_ttl self.cleanup_interval = cleanup_interval self.enable_stats = enable_stats # Cache storage using OrderedDict for LRU behavior self._cache: OrderedDict[str, CacheEntry] = OrderedDict() # Cache statistics self._stats = { "total_requests": 0, "cache_hits": 0, "cache_misses": 0, "evictions": 0, "expirations": 0, "current_size_bytes": 0, "entry_count": 0, # Cache hit optimization metrics "cache_hit_times": [], # Track cache hit response times "cache_miss_times": [], # Track cache miss response times "sequential_hits": 0, # Track consecutive cache hits "sequential_misses": 0, # Track consecutive cache misses "hot_entries": {}, # Track frequently accessed entries "last_operation": None, # Track last operation type ('hit' or 'miss') } # Cleanup task self._cleanup_task: Optional[asyncio.Task] = None self._running = False # Lock for thread safety self._lock = asyncio.Lock() logger.info(f"CacheManager initialized with max_size={max_size_mb}MB, ttl={default_ttl}s") async def start(self) -> None: """Start the cache manager and background cleanup task.""" if self._running: return self._running = True self._cleanup_task = asyncio.create_task(self._cleanup_loop()) logger.info("CacheManager started") async def stop(self) -> None: """Stop the cache manager and cleanup task.""" if not self._running: return self._running = False if self._cleanup_task: self._cleanup_task.cancel() try: await self._cleanup_task except asyncio.CancelledError: pass logger.info("CacheManager stopped") async def get_cached_transcription( self, audio_fingerprint: str ) -> Optional[TranscriptionResult]: """ Retrieve cached transcription result with optimized lookup. This method implements cache hit optimization by: 1. Fast lookup without API calls for cached results 2. Tracking cache hit performance metrics 3. Optimizing frequently accessed entries 4. Monitoring cache hit patterns Args: audio_fingerprint: Unique fingerprint of audio data Returns: Cached TranscriptionResult or None if not found """ start_time = time.time() async with self._lock: if self.enable_stats: self._stats["total_requests"] += 1 entry = self._cache.get(audio_fingerprint) if entry is None: # Cache miss - track timing and patterns miss_time = time.time() - start_time if self.enable_stats: self._stats["cache_misses"] += 1 self._stats["cache_miss_times"].append(miss_time) # Keep only last 100 measurements for efficiency if len(self._stats["cache_miss_times"]) > 100: self._stats["cache_miss_times"] = self._stats["cache_miss_times"][-100:] # Track sequential misses if self._stats["last_operation"] == "miss": self._stats["sequential_misses"] += 1 else: self._stats["sequential_misses"] = 1 self._stats["last_operation"] = "miss" logger.debug(f"Cache miss for fingerprint: {audio_fingerprint[:16]}... " f"(lookup time: {miss_time*1000:.2f}ms)") return None # Check if entry has expired if entry.is_expired: miss_time = time.time() - start_time logger.debug(f"Cache entry expired for fingerprint: {audio_fingerprint[:16]}... " f"(lookup time: {miss_time*1000:.2f}ms)") await self._remove_entry(audio_fingerprint) if self.enable_stats: self._stats["cache_misses"] += 1 self._stats["expirations"] += 1 self._stats["cache_miss_times"].append(miss_time) if len(self._stats["cache_miss_times"]) > 100: self._stats["cache_miss_times"] = self._stats["cache_miss_times"][-100:] # Track sequential misses if self._stats["last_operation"] == "miss": self._stats["sequential_misses"] += 1 else: self._stats["sequential_misses"] = 1 self._stats["last_operation"] = "miss" return None # Cache hit - optimize and track performance hit_time = time.time() - start_time # Update access information and move to end (most recently used) entry.touch() self._cache.move_to_end(audio_fingerprint) if self.enable_stats: self._stats["cache_hits"] += 1 self._stats["cache_hit_times"].append(hit_time) # Keep only last 100 measurements for efficiency if len(self._stats["cache_hit_times"]) > 100: self._stats["cache_hit_times"] = self._stats["cache_hit_times"][-100:] # Track hot entries (frequently accessed) if audio_fingerprint not in self._stats["hot_entries"]: self._stats["hot_entries"][audio_fingerprint] = 0 self._stats["hot_entries"][audio_fingerprint] += 1 # Keep only top 50 hot entries to prevent memory growth if len(self._stats["hot_entries"]) > 50: # Keep only the most frequently accessed entries sorted_entries = sorted( self._stats["hot_entries"].items(), key=lambda x: x[1], reverse=True ) self._stats["hot_entries"] = dict(sorted_entries[:50]) # Track sequential hits if self._stats["last_operation"] == "hit": self._stats["sequential_hits"] += 1 else: self._stats["sequential_hits"] = 1 self._stats["last_operation"] = "hit" logger.debug(f"Cache hit for fingerprint: {audio_fingerprint[:16]}... " f"(access count: {entry.access_count}, lookup time: {hit_time*1000:.2f}ms)") return entry.result async def get_cached_transcription_batch( self, audio_fingerprints: List[str] ) -> Dict[str, Optional[TranscriptionResult]]: """ Retrieve multiple cached transcription results in a single operation. Args: audio_fingerprints: List of unique fingerprints of audio data Returns: Dictionary mapping fingerprints to cached results (None if not found) """ results = {} async with self._lock: for fingerprint in audio_fingerprints: if self.enable_stats: self._stats["total_requests"] += 1 entry = self._cache.get(fingerprint) if entry is None: if self.enable_stats: self._stats["cache_misses"] += 1 results[fingerprint] = None continue # Check if entry has expired if entry.is_expired: await self._remove_entry(fingerprint) if self.enable_stats: self._stats["cache_misses"] += 1 self._stats["expirations"] += 1 results[fingerprint] = None continue # Update access information and move to end (most recently used) entry.touch() self._cache.move_to_end(fingerprint) if self.enable_stats: self._stats["cache_hits"] += 1 results[fingerprint] = entry.result hit_count = sum(1 for result in results.values() if result is not None) logger.debug(f"Batch cache lookup: {hit_count}/{len(audio_fingerprints)} hits") return results async def cache_transcription( self, audio_fingerprint: str, result: TranscriptionResult, ttl: Optional[int] = None ) -> bool: """ Cache a transcription result. Args: audio_fingerprint: Unique fingerprint of audio data result: TranscriptionResult to cache ttl: Time to live in seconds (uses default if None) Returns: True if caching was successful, False otherwise """ if ttl is None: ttl = self.default_ttl try: async with self._lock: # Create cache entry entry = CacheEntry( result=result, created_at=time.time(), last_accessed=time.time(), ttl=ttl ) # Check if we need to make space await self._ensure_space(entry.size_bytes) # Add to cache self._cache[audio_fingerprint] = entry self._stats["current_size_bytes"] += entry.size_bytes self._stats["entry_count"] += 1 logger.debug(f"Cached transcription for fingerprint: {audio_fingerprint[:16]}... " f"(size: {entry.size_bytes} bytes, ttl: {ttl}s)") return True except Exception as e: logger.error(f"Failed to cache transcription: {e}") return False async def generate_audio_fingerprint(self, audio_data: bytes) -> str: """ Generate a unique fingerprint for audio data. Uses SHA-256 hashing of the audio content to create a consistent fingerprint that will be identical for the same audio data. Args: audio_data: Raw audio bytes Returns: Unique fingerprint string """ try: # Use SHA-256 for consistent, collision-resistant hashing hasher = hashlib.sha256() # Hash the audio data in chunks to handle large files efficiently chunk_size = 8192 for i in range(0, len(audio_data), chunk_size): chunk = audio_data[i:i + chunk_size] hasher.update(chunk) # Generate hexadecimal fingerprint fingerprint = hasher.hexdigest() logger.debug(f"Generated audio fingerprint: {fingerprint[:16]}... " f"(audio size: {len(audio_data)} bytes)") return fingerprint except Exception as e: logger.error(f"Failed to generate audio fingerprint: {e}") raise CacheError("fingerprint_generation", f"Failed to generate fingerprint: {e}") async def get_cache_stats(self) -> CacheStats: """ Get cache performance statistics with hit optimization metrics. Returns: CacheStats with hit rates and usage information """ async with self._lock: return CacheStats( total_requests=self._stats["total_requests"], cache_hits=self._stats["cache_hits"], cache_misses=self._stats["cache_misses"], hit_rate=0.0, # Will be calculated in __post_init__ total_size_bytes=self._stats["current_size_bytes"], entry_count=self._stats["entry_count"], evictions=self._stats["evictions"] ) async def get_detailed_cache_stats(self) -> Dict[str, Any]: """ Get detailed cache performance statistics for optimization analysis. Returns: Dictionary with comprehensive cache metrics including hit optimization data """ async with self._lock: stats = await self.get_cache_stats() # Calculate additional optimization metrics avg_entry_size = ( stats.total_size_bytes / stats.entry_count if stats.entry_count > 0 else 0 ) cache_efficiency = ( stats.hit_rate * (1 - (stats.evictions / max(stats.total_requests, 1))) if stats.total_requests > 0 else 0.0 ) # Calculate cache hit optimization metrics hit_optimization_stats = self._calculate_hit_optimization_metrics() # Analyze access patterns access_pattern_stats = self._analyze_access_patterns() return { "basic_stats": { "total_requests": stats.total_requests, "cache_hits": stats.cache_hits, "cache_misses": stats.cache_misses, "hit_rate": stats.hit_rate, "miss_rate": stats.miss_rate, "evictions": stats.evictions }, "size_stats": { "total_size_bytes": stats.total_size_bytes, "total_size_mb": stats.total_size_bytes / (1024 * 1024), "entry_count": stats.entry_count, "avg_entry_size_bytes": avg_entry_size, "max_size_bytes": self.max_size_bytes, "utilization_rate": stats.total_size_bytes / self.max_size_bytes }, "performance_stats": { "cache_efficiency": cache_efficiency, "eviction_rate": stats.evictions / max(stats.total_requests, 1), "access_patterns": access_pattern_stats }, "hit_optimization_stats": hit_optimization_stats, "optimization_recommendations": self._get_optimization_recommendations(stats) } def _calculate_hit_optimization_metrics(self) -> Dict[str, Any]: """ Calculate cache hit optimization metrics. Returns: Dictionary with hit optimization statistics """ hit_times = self._stats.get("cache_hit_times", []) miss_times = self._stats.get("cache_miss_times", []) # Calculate timing statistics avg_hit_time = sum(hit_times) / len(hit_times) if hit_times else 0.0 avg_miss_time = sum(miss_times) / len(miss_times) if miss_times else 0.0 # Calculate hit time improvement (how much faster hits are than misses) hit_time_improvement = ( ((avg_miss_time - avg_hit_time) / avg_miss_time * 100) if avg_miss_time > 0 else 0.0 ) # Calculate sequential operation patterns sequential_hits = self._stats.get("sequential_hits", 0) sequential_misses = self._stats.get("sequential_misses", 0) # Calculate hot entry statistics hot_entries = self._stats.get("hot_entries", {}) hot_entry_count = len(hot_entries) total_hot_accesses = sum(hot_entries.values()) if hot_entries else 0 avg_hot_entry_accesses = ( total_hot_accesses / hot_entry_count if hot_entry_count > 0 else 0.0 ) # Calculate cache hit efficiency score (0-100) hit_rate = ( self._stats["cache_hits"] / max(self._stats["total_requests"], 1) if self._stats["total_requests"] > 0 else 0.0 ) timing_efficiency = min(hit_time_improvement / 50.0, 1.0) if hit_time_improvement > 0 else 0.0 pattern_efficiency = min(sequential_hits / max(sequential_hits + sequential_misses, 1), 1.0) overall_efficiency = (hit_rate * 0.5 + timing_efficiency * 0.3 + pattern_efficiency * 0.2) * 100 return { "timing_metrics": { "avg_hit_time_ms": avg_hit_time * 1000, "avg_miss_time_ms": avg_miss_time * 1000, "hit_time_improvement_percent": hit_time_improvement, "hit_samples": len(hit_times), "miss_samples": len(miss_times) }, "pattern_metrics": { "sequential_hits": sequential_hits, "sequential_misses": sequential_misses, "hit_streak_ratio": sequential_hits / max(sequential_hits + sequential_misses, 1) }, "hot_entry_metrics": { "hot_entry_count": hot_entry_count, "total_hot_accesses": total_hot_accesses, "avg_accesses_per_hot_entry": avg_hot_entry_accesses, "hot_entry_hit_contribution": ( total_hot_accesses / max(self._stats["cache_hits"], 1) * 100 if self._stats["cache_hits"] > 0 else 0.0 ) }, "efficiency_score": { "overall_efficiency_percent": overall_efficiency, "hit_rate_component": hit_rate * 50, # 50% weight "timing_component": timing_efficiency * 30, # 30% weight "pattern_component": pattern_efficiency * 20 # 20% weight } } def _analyze_access_patterns(self) -> Dict[str, Any]: """ Analyze cache access patterns for optimization insights. Returns: Dictionary with access pattern analysis """ if not self._cache: return { "most_accessed_entries": 0, "least_accessed_entries": 0, "avg_access_count": 0.0, "access_distribution": "empty" } access_counts = [entry.access_count for entry in self._cache.values()] return { "most_accessed_entries": max(access_counts) if access_counts else 0, "least_accessed_entries": min(access_counts) if access_counts else 0, "avg_access_count": sum(access_counts) / len(access_counts) if access_counts else 0.0, "access_distribution": "varied" if len(set(access_counts)) > 1 else "uniform" } def _get_optimization_recommendations(self, stats: CacheStats) -> List[str]: """ Generate optimization recommendations based on cache statistics. Args: stats: Current cache statistics Returns: List of optimization recommendations """ recommendations = [] # Hit rate optimization if stats.hit_rate < 0.5: recommendations.append("Consider increasing cache size - low hit rate detected") elif stats.hit_rate < 0.7: recommendations.append("Cache hit rate could be improved - consider TTL optimization") # Eviction optimization if stats.evictions > stats.cache_hits * 0.1: recommendations.append("High eviction rate - consider increasing cache size") # Size optimization utilization = stats.total_size_bytes / self.max_size_bytes if utilization > 0.9: recommendations.append("Cache near capacity - consider size increase or TTL reduction") elif utilization < 0.3: recommendations.append("Cache underutilized - consider size reduction for memory efficiency") # Performance optimization if stats.entry_count > 1000 and stats.hit_rate > 0.8: recommendations.append("High performance cache - consider implementing cache warming") # Cache hit optimization specific recommendations hit_times = self._stats.get("cache_hit_times", []) miss_times = self._stats.get("cache_miss_times", []) if hit_times and miss_times: avg_hit_time = sum(hit_times) / len(hit_times) avg_miss_time = sum(miss_times) / len(miss_times) if avg_hit_time > 0.001: # 1ms threshold recommendations.append("Cache hit times are high - consider cache structure optimization") if avg_hit_time > avg_miss_time * 0.5: recommendations.append("Cache hits not significantly faster than misses - investigate cache overhead") # Sequential pattern optimization sequential_hits = self._stats.get("sequential_hits", 0) sequential_misses = self._stats.get("sequential_misses", 0) if sequential_misses > sequential_hits * 2: recommendations.append("High sequential miss pattern - consider cache warming or preloading") # Hot entry optimization hot_entries = self._stats.get("hot_entries", {}) if len(hot_entries) > 0: total_hot_accesses = sum(hot_entries.values()) if total_hot_accesses > stats.cache_hits * 0.8: recommendations.append("High hot entry concentration - consider dedicated hot cache tier") if not recommendations: recommendations.append("Cache performance is optimal") return recommendations async def warm_cache( self, audio_fingerprints: List[str], transcription_callback: Optional[Callable] = None ) -> Dict[str, bool]: """ Warm the cache by preloading frequently accessed transcriptions. Args: audio_fingerprints: List of audio fingerprints to warm transcription_callback: Optional callback to generate transcriptions Returns: Dictionary mapping fingerprints to success status """ results = {} for fingerprint in audio_fingerprints: try: # Check if already cached cached_result = await self.get_cached_transcription(fingerprint) if cached_result is not None: results[fingerprint] = True continue # If callback provided, generate and cache transcription if transcription_callback: try: result = await transcription_callback(fingerprint) if result: success = await self.cache_transcription(fingerprint, result) results[fingerprint] = success else: results[fingerprint] = False except Exception as e: logger.warning(f"Failed to generate transcription for warming: {e}") results[fingerprint] = False else: results[fingerprint] = False except Exception as e: logger.error(f"Error warming cache for fingerprint {fingerprint[:16]}...: {e}") results[fingerprint] = False warmed_count = sum(1 for success in results.values() if success) logger.info(f"Cache warming completed: {warmed_count}/{len(audio_fingerprints)} entries warmed") return results async def get_cache_hit_optimization_stats(self) -> Dict[str, Any]: """ Get specialized cache hit optimization statistics. This method provides detailed metrics specifically for cache hit optimization, including timing analysis, pattern recognition, and performance recommendations. Returns: Dictionary with cache hit optimization metrics """ async with self._lock: hit_optimization_stats = self._calculate_hit_optimization_metrics() basic_stats = await self.get_cache_stats() # Calculate additional hit-specific metrics cache_effectiveness = { "api_calls_avoided": basic_stats.cache_hits, "api_call_reduction_percent": ( basic_stats.cache_hits / max(basic_stats.total_requests, 1) * 100 if basic_stats.total_requests > 0 else 0.0 ), "estimated_time_saved_ms": ( len(self._stats.get("cache_hit_times", [])) * (sum(self._stats.get("cache_miss_times", [0])) / max(len(self._stats.get("cache_miss_times", [1])), 1) - sum(self._stats.get("cache_hit_times", [0])) / max(len(self._stats.get("cache_hit_times", [1])), 1)) * 1000 if self._stats.get("cache_hit_times") and self._stats.get("cache_miss_times") else 0.0 ) } # Identify optimization opportunities optimization_opportunities = [] if basic_stats.hit_rate < 0.8: optimization_opportunities.append({ "type": "hit_rate_improvement", "description": f"Hit rate is {basic_stats.hit_rate:.1%}, target is 80%+", "potential_improvement": f"{(0.8 - basic_stats.hit_rate) * 100:.1f}% hit rate increase possible" }) hit_times = self._stats.get("cache_hit_times", []) if hit_times and sum(hit_times) / len(hit_times) > 0.001: # 1ms threshold optimization_opportunities.append({ "type": "lookup_speed_improvement", "description": f"Average hit time is {sum(hit_times) / len(hit_times) * 1000:.2f}ms", "potential_improvement": "Consider cache structure optimization for faster lookups" }) hot_entries = self._stats.get("hot_entries", {}) if len(hot_entries) > 10: optimization_opportunities.append({ "type": "hot_entry_optimization", "description": f"{len(hot_entries)} frequently accessed entries identified", "potential_improvement": "Consider implementing a dedicated hot cache tier" }) return { "cache_effectiveness": cache_effectiveness, "hit_optimization_metrics": hit_optimization_stats, "optimization_opportunities": optimization_opportunities, "performance_summary": { "total_requests": basic_stats.total_requests, "cache_hits": basic_stats.cache_hits, "hit_rate": basic_stats.hit_rate, "api_calls_avoided": basic_stats.cache_hits, "efficiency_score": hit_optimization_stats.get("efficiency_score", {}).get("overall_efficiency_percent", 0.0) } } async def optimize_cache_performance(self) -> Dict[str, Any]: """ Perform cache performance optimization operations with hit optimization focus. Returns: Dictionary with optimization results """ async with self._lock: initial_stats = await self.get_cache_stats() initial_hit_stats = self._calculate_hit_optimization_metrics() # Remove expired entries expired_count = await self.evict_expired() # Analyze and optimize entry access patterns optimization_results = { "initial_stats": { "entry_count": initial_stats.entry_count, "hit_rate": initial_stats.hit_rate, "size_bytes": initial_stats.total_size_bytes, "efficiency_score": initial_hit_stats.get("efficiency_score", {}).get("overall_efficiency_percent", 0.0) }, "expired_evicted": expired_count, "optimizations_applied": [] } # Promote frequently accessed entries (move to end for LRU) frequent_entries = [] hot_entries = self._stats.get("hot_entries", {}) # Promote hot entries to the end of the cache (most recently used) for key, access_count in hot_entries.items(): if key in self._cache and access_count > 5: # Threshold for frequent access frequent_entries.append(key) self._cache.move_to_end(key) if frequent_entries: optimization_results["optimizations_applied"].append( f"Promoted {len(frequent_entries)} frequently accessed entries to improve hit rates" ) # Optimize cache structure for better hit performance if len(self._cache) > 100: # Reorganize cache to put most accessed items at the end (LRU optimization) sorted_entries = [] for key, entry in self._cache.items(): access_weight = hot_entries.get(key, 0) + entry.access_count sorted_entries.append((key, entry, access_weight)) # Sort by access weight and reorganize sorted_entries.sort(key=lambda x: x[2]) # Clear and rebuild cache in optimized order temp_cache = self._cache.copy() self._cache.clear() for key, entry, _ in sorted_entries: self._cache[key] = entry optimization_results["optimizations_applied"].append( "Reorganized cache structure for optimal hit performance" ) # Clean up old timing data to prevent memory growth if len(self._stats.get("cache_hit_times", [])) > 100: self._stats["cache_hit_times"] = self._stats["cache_hit_times"][-100:] optimization_results["optimizations_applied"].append("Cleaned up old hit timing data") if len(self._stats.get("cache_miss_times", [])) > 100: self._stats["cache_miss_times"] = self._stats["cache_miss_times"][-100:] optimization_results["optimizations_applied"].append("Cleaned up old miss timing data") # Compact cache if fragmented (remove and re-add entries to optimize memory) if initial_stats.entry_count > 100 and expired_count > initial_stats.entry_count * 0.1: # Cache is fragmented, perform compaction entries_to_compact = list(self._cache.items()) self._cache.clear() self._stats["current_size_bytes"] = 0 self._stats["entry_count"] = 0 # Re-add entries in access order (most recent first) for key, entry in reversed(entries_to_compact): self._cache[key] = entry self._stats["current_size_bytes"] += entry.size_bytes self._stats["entry_count"] += 1 optimization_results["optimizations_applied"].append("Performed cache compaction for better memory efficiency") final_stats = await self.get_cache_stats() final_hit_stats = self._calculate_hit_optimization_metrics() optimization_results["final_stats"] = { "entry_count": final_stats.entry_count, "hit_rate": final_stats.hit_rate, "size_bytes": final_stats.total_size_bytes, "efficiency_score": final_hit_stats.get("efficiency_score", {}).get("overall_efficiency_percent", 0.0) } # Calculate optimization impact efficiency_improvement = ( optimization_results["final_stats"]["efficiency_score"] - optimization_results["initial_stats"]["efficiency_score"] ) optimization_results["optimization_impact"] = { "efficiency_improvement_percent": efficiency_improvement, "hit_rate_change": final_stats.hit_rate - initial_stats.hit_rate, "size_reduction_bytes": initial_stats.total_size_bytes - final_stats.total_size_bytes } logger.info(f"Cache optimization completed: {optimization_results}") return optimization_results async def clear_cache(self) -> None: """Clear all cached entries.""" async with self._lock: self._cache.clear() self._stats["current_size_bytes"] = 0 self._stats["entry_count"] = 0 logger.info("Cache cleared") async def evict_expired(self) -> int: """ Remove expired cache entries. Returns: Number of entries evicted """ async with self._lock: expired_keys = [] current_time = time.time() for key, entry in self._cache.items(): if current_time - entry.created_at > entry.ttl: expired_keys.append(key) evicted_count = 0 for key in expired_keys: await self._remove_entry(key) evicted_count += 1 if self.enable_stats: self._stats["expirations"] += 1 if evicted_count > 0: logger.debug(f"Evicted {evicted_count} expired cache entries") return evicted_count async def _ensure_space(self, required_bytes: int) -> None: """ Ensure there's enough space in the cache for a new entry. Args: required_bytes: Number of bytes needed """ # Check if we have enough space if self._stats["current_size_bytes"] + required_bytes <= self.max_size_bytes: return # Need to evict entries using LRU policy bytes_to_free = (self._stats["current_size_bytes"] + required_bytes) - self.max_size_bytes bytes_freed = 0 evicted_count = 0 # Evict least recently used entries until we have enough space while bytes_freed < bytes_to_free and self._cache: # Get least recently used entry (first in OrderedDict) key = next(iter(self._cache)) entry = self._cache[key] bytes_freed += entry.size_bytes await self._remove_entry(key) evicted_count += 1 if self.enable_stats: self._stats["evictions"] += 1 logger.debug(f"Evicted {evicted_count} entries to free {bytes_freed} bytes") async def _remove_entry(self, key: str) -> None: """ Remove a cache entry and update statistics. Args: key: Cache key to remove """ entry = self._cache.pop(key, None) if entry: self._stats["current_size_bytes"] -= entry.size_bytes self._stats["entry_count"] -= 1 async def _cleanup_loop(self) -> None: """Background task for periodic cache cleanup.""" while self._running: try: await asyncio.sleep(self.cleanup_interval) if not self._running: break # Remove expired entries expired_count = await self.evict_expired() # Log cache statistics periodically stats = await self.get_cache_stats() logger.debug(f"Cache stats: {stats.entry_count} entries, " f"{stats.total_size_bytes / 1024 / 1024:.1f}MB, " f"hit rate: {stats.hit_rate:.2%}") except asyncio.CancelledError: break except Exception as e: logger.error(f"Error in cache cleanup loop: {e}") def get_cache_info(self) -> Dict[str, Any]: """ Get detailed cache information for debugging. Returns: Dictionary with cache details """ return { "max_size_bytes": self.max_size_bytes, "current_size_bytes": self._stats["current_size_bytes"], "entry_count": self._stats["entry_count"], "default_ttl": self.default_ttl, "cleanup_interval": self.cleanup_interval, "running": self._running, "stats": self._stats.copy() } async def __aenter__(self): """Async context manager entry.""" await self.start() return self async def __aexit__(self, exc_type, exc_val, exc_tb): """Async context manager exit.""" await self.stop() class RedisCacheManager(CacheManagerInterface): """ Redis-based cache manager for distributed caching. This implementation uses Redis for persistent, distributed caching across multiple application instances. """ def __init__( self, redis_url: str, key_prefix: str = "voice_control:cache:", default_ttl: int = 3600, max_connections: int = 10 ): """ Initialize Redis cache manager. Args: redis_url: Redis connection URL key_prefix: Prefix for cache keys default_ttl: Default time-to-live in seconds max_connections: Maximum Redis connections """ self.redis_url = redis_url self.key_prefix = key_prefix self.default_ttl = default_ttl self.max_connections = max_connections self._redis = None self._stats_key = f"{key_prefix}stats" logger.info(f"RedisCacheManager initialized with URL: {redis_url}") async def start(self) -> None: """Initialize Redis connection.""" try: import redis.asyncio as redis self._redis = redis.from_url( self.redis_url, max_connections=self.max_connections, decode_responses=False # We handle bytes directly ) # Test connection await self._redis.ping() logger.info("Redis cache manager connected") except ImportError: raise CacheError("redis_import", "redis package not installed") except Exception as e: raise CacheError("redis_connection", f"Failed to connect to Redis: {e}") async def stop(self) -> None: """Close Redis connection.""" if self._redis: await self._redis.close() logger.info("Redis cache manager disconnected") async def get_cached_transcription( self, audio_fingerprint: str ) -> Optional[TranscriptionResult]: """ Retrieve cached transcription result from Redis. Args: audio_fingerprint: Unique fingerprint of audio data Returns: Cached TranscriptionResult or None if not found """ if not self._redis: raise CacheError("redis_not_connected", "Redis not connected") try: key = f"{self.key_prefix}{audio_fingerprint}" # Get cached data cached_data = await self._redis.get(key) if cached_data is None: await self._increment_stat("cache_misses") return None # Deserialize transcription result import pickle result = pickle.loads(cached_data) await self._increment_stat("cache_hits") logger.debug(f"Redis cache hit for fingerprint: {audio_fingerprint[:16]}...") return result except Exception as e: logger.error(f"Failed to get cached transcription from Redis: {e}") await self._increment_stat("cache_misses") return None async def cache_transcription( self, audio_fingerprint: str, result: TranscriptionResult, ttl: Optional[int] = None ) -> bool: """ Cache a transcription result in Redis. Args: audio_fingerprint: Unique fingerprint of audio data result: TranscriptionResult to cache ttl: Time to live in seconds (uses default if None) Returns: True if caching was successful, False otherwise """ if not self._redis: raise CacheError("redis_not_connected", "Redis not connected") if ttl is None: ttl = self.default_ttl try: key = f"{self.key_prefix}{audio_fingerprint}" # Serialize transcription result import pickle cached_data = pickle.dumps(result) # Store in Redis with TTL await self._redis.setex(key, ttl, cached_data) logger.debug(f"Cached transcription in Redis for fingerprint: {audio_fingerprint[:16]}... " f"(ttl: {ttl}s)") return True except Exception as e: logger.error(f"Failed to cache transcription in Redis: {e}") return False async def generate_audio_fingerprint(self, audio_data: bytes) -> str: """ Generate a unique fingerprint for audio data. Args: audio_data: Raw audio bytes Returns: Unique fingerprint string """ # Use the same implementation as in-memory cache cache_manager = CacheManager() return await cache_manager.generate_audio_fingerprint(audio_data) async def get_cache_stats(self) -> CacheStats: """ Get cache performance statistics from Redis. Returns: CacheStats with hit rates and usage information """ if not self._redis: raise CacheError("redis_not_connected", "Redis not connected") try: # Get stats from Redis hash stats_data = await self._redis.hgetall(self._stats_key) # Convert bytes to integers stats = {} for key, value in stats_data.items(): if isinstance(key, bytes): key = key.decode('utf-8') if isinstance(value, bytes): value = int(value.decode('utf-8')) stats[key] = value # Get cache size info cache_keys = await self._redis.keys(f"{self.key_prefix}*") entry_count = len([k for k in cache_keys if not k.decode('utf-8').endswith(':stats')]) return CacheStats( total_requests=stats.get("total_requests", 0), cache_hits=stats.get("cache_hits", 0), cache_misses=stats.get("cache_misses", 0), hit_rate=0.0, # Will be calculated in __post_init__ total_size_bytes=0, # Not easily calculable in Redis entry_count=entry_count, evictions=stats.get("evictions", 0) ) except Exception as e: logger.error(f"Failed to get cache stats from Redis: {e}") return CacheStats(0, 0, 0, 0.0, 0, 0, 0) async def clear_cache(self) -> None: """Clear all cached entries from Redis.""" if not self._redis: raise CacheError("redis_not_connected", "Redis not connected") try: # Get all cache keys cache_keys = await self._redis.keys(f"{self.key_prefix}*") if cache_keys: await self._redis.delete(*cache_keys) logger.info(f"Cleared {len(cache_keys)} entries from Redis cache") except Exception as e: logger.error(f"Failed to clear Redis cache: {e}") async def evict_expired(self) -> int: """ Remove expired cache entries from Redis. Redis handles TTL expiration automatically, so this is a no-op. Returns: Number of entries evicted (always 0 for Redis) """ # Redis handles TTL expiration automatically return 0 async def _increment_stat(self, stat_name: str) -> None: """Increment a statistic counter in Redis.""" try: await self._redis.hincrby(self._stats_key, stat_name, 1) except Exception as e: logger.error(f"Failed to increment stat {stat_name}: {e}") async def __aenter__(self): """Async context manager entry.""" await self.start() return self async def __aexit__(self, exc_type, exc_val, exc_tb): """Async context manager exit.""" await self.stop() def create_cache_manager( cache_config: Dict[str, Any] ) -> CacheManagerInterface: """ Factory function to create appropriate cache manager based on configuration. Args: cache_config: Cache configuration dictionary Returns: CacheManagerInterface implementation """ redis_url = cache_config.get("redis_url") if redis_url: return RedisCacheManager( redis_url=redis_url, default_ttl=cache_config.get("default_ttl", 3600), max_connections=cache_config.get("max_connections", 10) ) else: return CacheManager( max_size_mb=cache_config.get("max_size_mb", 100), default_ttl=cache_config.get("default_ttl", 3600), cleanup_interval=cache_config.get("cleanup_interval", 600) )