Spaces:
Paused
Paused
Download shared/caching.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 20.6 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/caching.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/shared/caching.py
-
curl -L -o caching.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/caching.py
20.6 kB
| """ | |
| Advanced caching system for MCP AI Data Scientist. | |
| Provides multi-level caching with Redis-like interface, memory management, and cache optimization. | |
| """ | |
| import asyncio | |
| import logging | |
| import json | |
| import pickle | |
| import hashlib | |
| import time | |
| from typing import Any, Dict, List, Optional, Union, Callable, Tuple | |
| from datetime import datetime, timedelta | |
| from dataclasses import dataclass, asdict | |
| from pathlib import Path | |
| from collections import OrderedDict | |
| import threading | |
| from concurrent.futures import ThreadPoolExecutor | |
| import weakref | |
| import gc | |
| from .config import settings | |
| from .models import UserContext | |
| logger = logging.getLogger(__name__) | |
| class CacheEntry: | |
| """Cache entry with metadata.""" | |
| key: str | |
| value: Any | |
| created_at: datetime | |
| last_accessed: datetime | |
| access_count: int | |
| ttl_seconds: Optional[int] | |
| size_bytes: int | |
| tags: List[str] | |
| def is_expired(self) -> bool: | |
| """Check if cache entry is expired.""" | |
| if self.ttl_seconds is None: | |
| return False | |
| return (datetime.utcnow() - self.created_at).total_seconds() > self.ttl_seconds | |
| def touch(self): | |
| """Update last accessed time and increment access count.""" | |
| self.last_accessed = datetime.utcnow() | |
| self.access_count += 1 | |
| class CacheStats: | |
| """Cache statistics.""" | |
| total_entries: int | |
| total_size_bytes: int | |
| hit_count: int | |
| miss_count: int | |
| eviction_count: int | |
| memory_usage_mb: float | |
| hit_rate: float | |
| def to_dict(self) -> Dict[str, Any]: | |
| return asdict(self) | |
| class LRUCache: | |
| """Thread-safe LRU cache with TTL support.""" | |
| def __init__(self, max_size: int = 1000, default_ttl: Optional[int] = None): | |
| self.max_size = max_size | |
| self.default_ttl = default_ttl | |
| self._cache: OrderedDict[str, CacheEntry] = OrderedDict() | |
| self._lock = threading.RLock() | |
| self._stats = { | |
| 'hits': 0, | |
| 'misses': 0, | |
| 'evictions': 0 | |
| } | |
| def get(self, key: str) -> Optional[Any]: | |
| """Get value from cache.""" | |
| with self._lock: | |
| if key not in self._cache: | |
| self._stats['misses'] += 1 | |
| return None | |
| entry = self._cache[key] | |
| # Check if expired | |
| if entry.is_expired(): | |
| del self._cache[key] | |
| self._stats['misses'] += 1 | |
| return None | |
| # Move to end (most recently used) | |
| self._cache.move_to_end(key) | |
| entry.touch() | |
| self._stats['hits'] += 1 | |
| return entry.value | |
| def set(self, key: str, value: Any, ttl: Optional[int] = None, tags: Optional[List[str]] = None) -> None: | |
| """Set value in cache.""" | |
| with self._lock: | |
| # Calculate size | |
| try: | |
| size_bytes = len(pickle.dumps(value)) | |
| except: | |
| size_bytes = len(str(value).encode('utf-8')) | |
| # Create entry | |
| entry = CacheEntry( | |
| key=key, | |
| value=value, | |
| created_at=datetime.utcnow(), | |
| last_accessed=datetime.utcnow(), | |
| access_count=1, | |
| ttl_seconds=ttl or self.default_ttl, | |
| size_bytes=size_bytes, | |
| tags=tags or [] | |
| ) | |
| # Remove existing entry if present | |
| if key in self._cache: | |
| del self._cache[key] | |
| # Add new entry | |
| self._cache[key] = entry | |
| # Evict if necessary | |
| while len(self._cache) > self.max_size: | |
| oldest_key = next(iter(self._cache)) | |
| del self._cache[oldest_key] | |
| self._stats['evictions'] += 1 | |
| def delete(self, key: str) -> bool: | |
| """Delete key from cache.""" | |
| with self._lock: | |
| if key in self._cache: | |
| del self._cache[key] | |
| return True | |
| return False | |
| def clear(self) -> None: | |
| """Clear all cache entries.""" | |
| with self._lock: | |
| self._cache.clear() | |
| def get_stats(self) -> Dict[str, Any]: | |
| """Get cache statistics.""" | |
| with self._lock: | |
| total_hits = self._stats['hits'] | |
| total_requests = total_hits + self._stats['misses'] | |
| hit_rate = total_hits / total_requests if total_requests > 0 else 0 | |
| total_size = sum(entry.size_bytes for entry in self._cache.values()) | |
| return { | |
| 'entries': len(self._cache), | |
| 'size_bytes': total_size, | |
| 'size_mb': total_size / (1024 * 1024), | |
| 'hits': self._stats['hits'], | |
| 'misses': self._stats['misses'], | |
| 'evictions': self._stats['evictions'], | |
| 'hit_rate': hit_rate | |
| } | |
| class DatasetCache: | |
| """Specialized cache for dataset operations.""" | |
| def __init__(self, max_datasets: int = 50, max_size_mb: int = 500): | |
| self.max_datasets = max_datasets | |
| self.max_size_bytes = max_size_mb * 1024 * 1024 | |
| self._cache: Dict[str, Dict[str, Any]] = {} | |
| self._metadata: Dict[str, Dict[str, Any]] = {} | |
| self._lock = threading.RLock() | |
| self._access_times: Dict[str, datetime] = {} | |
| def _generate_key(self, user_id: str, dataset_id: str, operation: str, params: Dict[str, Any] = None) -> str: | |
| """Generate cache key for dataset operation.""" | |
| key_data = { | |
| 'user_id': user_id, | |
| 'dataset_id': dataset_id, | |
| 'operation': operation, | |
| 'params': params or {} | |
| } | |
| key_str = json.dumps(key_data, sort_keys=True) | |
| return hashlib.md5(key_str.encode()).hexdigest() | |
| def get_dataset_result(self, user_id: str, dataset_id: str, operation: str, params: Dict[str, Any] = None) -> Optional[Any]: | |
| """Get cached dataset operation result.""" | |
| key = self._generate_key(user_id, dataset_id, operation, params) | |
| with self._lock: | |
| if key not in self._cache: | |
| return None | |
| # Update access time | |
| self._access_times[key] = datetime.utcnow() | |
| return self._cache[key]['result'] | |
| def set_dataset_result(self, user_id: str, dataset_id: str, operation: str, result: Any, params: Dict[str, Any] = None) -> None: | |
| """Cache dataset operation result.""" | |
| key = self._generate_key(user_id, dataset_id, operation, params) | |
| with self._lock: | |
| # Calculate size | |
| try: | |
| size_bytes = len(pickle.dumps(result)) | |
| except: | |
| size_bytes = len(str(result).encode('utf-8')) | |
| # Check if we need to evict | |
| self._evict_if_needed(size_bytes) | |
| # Store result | |
| self._cache[key] = { | |
| 'result': result, | |
| 'created_at': datetime.utcnow(), | |
| 'size_bytes': size_bytes | |
| } | |
| self._metadata[key] = { | |
| 'user_id': user_id, | |
| 'dataset_id': dataset_id, | |
| 'operation': operation, | |
| 'params': params or {} | |
| } | |
| self._access_times[key] = datetime.utcnow() | |
| def _evict_if_needed(self, new_size: int) -> None: | |
| """Evict entries if needed to make space.""" | |
| current_size = sum(entry['size_bytes'] for entry in self._cache.values()) | |
| # Evict by count | |
| while len(self._cache) >= self.max_datasets: | |
| self._evict_lru() | |
| # Evict by size | |
| while current_size + new_size > self.max_size_bytes and self._cache: | |
| evicted_size = self._evict_lru() | |
| current_size -= evicted_size | |
| def _evict_lru(self) -> int: | |
| """Evict least recently used entry.""" | |
| if not self._access_times: | |
| return 0 | |
| # Find LRU key | |
| lru_key = min(self._access_times.keys(), key=lambda k: self._access_times[k]) | |
| # Get size before deletion | |
| size_bytes = self._cache[lru_key]['size_bytes'] | |
| # Remove from all structures | |
| del self._cache[lru_key] | |
| del self._metadata[lru_key] | |
| del self._access_times[lru_key] | |
| return size_bytes | |
| def invalidate_dataset(self, user_id: str, dataset_id: str) -> int: | |
| """Invalidate all cached results for a dataset.""" | |
| with self._lock: | |
| keys_to_remove = [] | |
| for key, metadata in self._metadata.items(): | |
| if metadata['user_id'] == user_id and metadata['dataset_id'] == dataset_id: | |
| keys_to_remove.append(key) | |
| for key in keys_to_remove: | |
| del self._cache[key] | |
| del self._metadata[key] | |
| del self._access_times[key] | |
| return len(keys_to_remove) | |
| def get_stats(self) -> Dict[str, Any]: | |
| """Get cache statistics.""" | |
| with self._lock: | |
| total_size = sum(entry['size_bytes'] for entry in self._cache.values()) | |
| return { | |
| 'entries': len(self._cache), | |
| 'size_bytes': total_size, | |
| 'size_mb': total_size / (1024 * 1024), | |
| 'max_datasets': self.max_datasets, | |
| 'max_size_mb': self.max_size_bytes / (1024 * 1024) | |
| } | |
| class QueryResultCache: | |
| """Cache for database query results.""" | |
| def __init__(self, max_entries: int = 1000, default_ttl: int = 300): | |
| self.cache = LRUCache(max_entries, default_ttl) | |
| def _generate_query_key(self, query: str, params: Tuple = None, user_id: str = None) -> str: | |
| """Generate cache key for query.""" | |
| key_data = { | |
| 'query': query.strip(), | |
| 'params': params or (), | |
| 'user_id': user_id | |
| } | |
| key_str = json.dumps(key_data, sort_keys=True, default=str) | |
| return f"query:{hashlib.md5(key_str.encode()).hexdigest()}" | |
| def get_query_result(self, query: str, params: Tuple = None, user_id: str = None) -> Optional[Any]: | |
| """Get cached query result.""" | |
| key = self._generate_query_key(query, params, user_id) | |
| return self.cache.get(key) | |
| def set_query_result(self, query: str, result: Any, params: Tuple = None, user_id: str = None, ttl: int = None) -> None: | |
| """Cache query result.""" | |
| key = self._generate_query_key(query, params, user_id) | |
| self.cache.set(key, result, ttl, tags=['query']) | |
| def invalidate_user_queries(self, user_id: str) -> None: | |
| """Invalidate all cached queries for a user.""" | |
| # This is a simplified implementation | |
| # In a full implementation, we'd track user-specific keys | |
| pass | |
| class CacheManager: | |
| """Main cache manager coordinating all cache types.""" | |
| def __init__(self): | |
| self.general_cache = LRUCache(max_size=2000, default_ttl=3600) # 1 hour default | |
| self.dataset_cache = DatasetCache(max_datasets=100, max_size_mb=1000) # 1GB max | |
| self.query_cache = QueryResultCache(max_entries=1000, default_ttl=300) # 5 minutes | |
| self.model_cache = LRUCache(max_size=50, default_ttl=7200) # 2 hours for models | |
| self._cleanup_task: Optional[asyncio.Task] = None | |
| self._executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="cache") | |
| async def start(self): | |
| """Start cache manager and cleanup tasks.""" | |
| self._cleanup_task = asyncio.create_task(self._cleanup_loop()) | |
| logger.info("Cache manager started") | |
| async def stop(self): | |
| """Stop cache manager and cleanup tasks.""" | |
| if self._cleanup_task: | |
| self._cleanup_task.cancel() | |
| try: | |
| await self._cleanup_task | |
| except asyncio.CancelledError: | |
| pass | |
| self._executor.shutdown(wait=True) | |
| logger.info("Cache manager stopped") | |
| async def _cleanup_loop(self): | |
| """Periodic cleanup of expired entries.""" | |
| while True: | |
| try: | |
| await asyncio.sleep(300) # Run every 5 minutes | |
| await self._cleanup_expired() | |
| await self._memory_pressure_cleanup() | |
| except asyncio.CancelledError: | |
| break | |
| except Exception as e: | |
| logger.error(f"Cache cleanup error: {e}") | |
| async def _cleanup_expired(self): | |
| """Remove expired entries from all caches.""" | |
| def cleanup_cache(cache: LRUCache): | |
| with cache._lock: | |
| expired_keys = [] | |
| for key, entry in cache._cache.items(): | |
| if entry.is_expired(): | |
| expired_keys.append(key) | |
| for key in expired_keys: | |
| del cache._cache[key] | |
| return len(expired_keys) | |
| # Run cleanup in thread pool to avoid blocking | |
| expired_counts = await asyncio.gather( | |
| asyncio.get_event_loop().run_in_executor(self._executor, cleanup_cache, self.general_cache), | |
| asyncio.get_event_loop().run_in_executor(self._executor, cleanup_cache, self.model_cache), | |
| return_exceptions=True | |
| ) | |
| total_expired = sum(count for count in expired_counts if isinstance(count, int)) | |
| if total_expired > 0: | |
| logger.debug(f"Cleaned up {total_expired} expired cache entries") | |
| async def _memory_pressure_cleanup(self): | |
| """Cleanup caches under memory pressure.""" | |
| import psutil | |
| try: | |
| memory_percent = psutil.virtual_memory().percent | |
| if memory_percent > 85: # High memory usage | |
| logger.warning(f"High memory usage ({memory_percent}%), performing aggressive cache cleanup") | |
| # Clear half of general cache | |
| with self.general_cache._lock: | |
| keys_to_remove = list(self.general_cache._cache.keys())[:len(self.general_cache._cache) // 2] | |
| for key in keys_to_remove: | |
| del self.general_cache._cache[key] | |
| # Force garbage collection | |
| gc.collect() | |
| except Exception as e: | |
| logger.error(f"Memory pressure cleanup failed: {e}") | |
| # General cache methods | |
| def get(self, key: str) -> Optional[Any]: | |
| """Get value from general cache.""" | |
| return self.general_cache.get(key) | |
| def set(self, key: str, value: Any, ttl: Optional[int] = None, tags: Optional[List[str]] = None) -> None: | |
| """Set value in general cache.""" | |
| self.general_cache.set(key, value, ttl, tags) | |
| def delete(self, key: str) -> bool: | |
| """Delete key from general cache.""" | |
| return self.general_cache.delete(key) | |
| # Dataset cache methods | |
| def get_dataset_result(self, user_id: str, dataset_id: str, operation: str, params: Dict[str, Any] = None) -> Optional[Any]: | |
| """Get cached dataset operation result.""" | |
| return self.dataset_cache.get_dataset_result(user_id, dataset_id, operation, params) | |
| def set_dataset_result(self, user_id: str, dataset_id: str, operation: str, result: Any, params: Dict[str, Any] = None) -> None: | |
| """Cache dataset operation result.""" | |
| self.dataset_cache.set_dataset_result(user_id, dataset_id, operation, result, params) | |
| def invalidate_dataset(self, user_id: str, dataset_id: str) -> int: | |
| """Invalidate all cached results for a dataset.""" | |
| return self.dataset_cache.invalidate_dataset(user_id, dataset_id) | |
| # Query cache methods | |
| def get_query_result(self, query: str, params: Tuple = None, user_id: str = None) -> Optional[Any]: | |
| """Get cached query result.""" | |
| return self.query_cache.get_query_result(query, params, user_id) | |
| def set_query_result(self, query: str, result: Any, params: Tuple = None, user_id: str = None, ttl: int = None) -> None: | |
| """Cache query result.""" | |
| self.query_cache.set_query_result(query, result, params, user_id, ttl) | |
| # Model cache methods | |
| def get_model(self, model_key: str) -> Optional[Any]: | |
| """Get cached model.""" | |
| return self.model_cache.get(model_key) | |
| def set_model(self, model_key: str, model: Any, ttl: int = 7200) -> None: | |
| """Cache model.""" | |
| self.model_cache.set(model_key, model, ttl, tags=['model']) | |
| def get_comprehensive_stats(self) -> Dict[str, Any]: | |
| """Get comprehensive cache statistics.""" | |
| return { | |
| 'general_cache': self.general_cache.get_stats(), | |
| 'dataset_cache': self.dataset_cache.get_stats(), | |
| 'query_cache': self.query_cache.cache.get_stats(), | |
| 'model_cache': self.model_cache.get_stats(), | |
| 'memory_info': self._get_memory_info() | |
| } | |
| def _get_memory_info(self) -> Dict[str, Any]: | |
| """Get memory usage information.""" | |
| try: | |
| import psutil | |
| memory = psutil.virtual_memory() | |
| return { | |
| 'total_mb': memory.total / (1024 * 1024), | |
| 'available_mb': memory.available / (1024 * 1024), | |
| 'percent_used': memory.percent, | |
| 'cache_pressure': memory.percent > 80 | |
| } | |
| except: | |
| return {'error': 'Memory info not available'} | |
| # Global cache manager instance | |
| cache_manager = CacheManager() | |
| # Decorator for caching function results | |
| def cached(ttl: int = 3600, key_prefix: str = "", use_args: bool = True): | |
| """Decorator for caching function results.""" | |
| def decorator(func: Callable): | |
| async def async_wrapper(*args, **kwargs): | |
| # Generate cache key | |
| if use_args: | |
| key_data = { | |
| 'func': func.__name__, | |
| 'args': args, | |
| 'kwargs': kwargs | |
| } | |
| key_str = json.dumps(key_data, sort_keys=True, default=str) | |
| cache_key = f"{key_prefix}:{hashlib.md5(key_str.encode()).hexdigest()}" | |
| else: | |
| cache_key = f"{key_prefix}:{func.__name__}" | |
| # Try to get from cache | |
| result = cache_manager.get(cache_key) | |
| if result is not None: | |
| return result | |
| # Execute function and cache result | |
| result = await func(*args, **kwargs) | |
| cache_manager.set(cache_key, result, ttl) | |
| return result | |
| def sync_wrapper(*args, **kwargs): | |
| # Generate cache key | |
| if use_args: | |
| key_data = { | |
| 'func': func.__name__, | |
| 'args': args, | |
| 'kwargs': kwargs | |
| } | |
| key_str = json.dumps(key_data, sort_keys=True, default=str) | |
| cache_key = f"{key_prefix}:{hashlib.md5(key_str.encode()).hexdigest()}" | |
| else: | |
| cache_key = f"{key_prefix}:{func.__name__}" | |
| # Try to get from cache | |
| result = cache_manager.get(cache_key) | |
| if result is not None: | |
| return result | |
| # Execute function and cache result | |
| result = func(*args, **kwargs) | |
| cache_manager.set(cache_key, result, ttl) | |
| return result | |
| if asyncio.iscoroutinefunction(func): | |
| return async_wrapper | |
| else: | |
| return sync_wrapper | |
| return decorator |