""" Memory management system for large dataset processing. Provides memory monitoring, chunked processing, and memory optimization. """ import asyncio import logging import gc import os import psutil import tempfile import pickle import mmap from typing import Any, Dict, List, Optional, Iterator, Callable, Union, Tuple from dataclasses import dataclass from datetime import datetime from pathlib import Path import pandas as pd import numpy as np from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import threading import weakref from contextlib import contextmanager from .config import settings from .monitoring import monitoring_system logger = logging.getLogger(__name__) @dataclass class MemoryStats: """Memory usage statistics.""" total_mb: float available_mb: float used_mb: float percent_used: float process_memory_mb: float swap_used_mb: float memory_pressure: str # 'low', 'medium', 'high', 'critical' def to_dict(self) -> Dict[str, Any]: return { 'total_mb': self.total_mb, 'available_mb': self.available_mb, 'used_mb': self.used_mb, 'percent_used': self.percent_used, 'process_memory_mb': self.process_memory_mb, 'swap_used_mb': self.swap_used_mb, 'memory_pressure': self.memory_pressure } @dataclass class DatasetChunk: """Represents a chunk of a dataset.""" chunk_id: int start_row: int end_row: int data: Optional[pd.DataFrame] file_path: Optional[str] size_bytes: int def __post_init__(self): if self.data is not None and self.size_bytes == 0: self.size_bytes = self.data.memory_usage(deep=True).sum() class MemoryMonitor: """Monitors system and process memory usage.""" def __init__(self): self._monitoring = False self._monitor_task: Optional[asyncio.Task] = None self._callbacks: List[Callable[[MemoryStats], None]] = [] self._thresholds = { 'medium': 70.0, # 70% memory usage 'high': 85.0, # 85% memory usage 'critical': 95.0 # 95% memory usage } async def start_monitoring(self, interval_seconds: int = 30): """Start memory monitoring.""" if self._monitoring: return self._monitoring = True self._monitor_task = asyncio.create_task(self._monitor_loop(interval_seconds)) logger.info("Memory monitoring started") async def stop_monitoring(self): """Stop memory monitoring.""" self._monitoring = False if self._monitor_task: self._monitor_task.cancel() try: await self._monitor_task except asyncio.CancelledError: pass logger.info("Memory monitoring stopped") async def _monitor_loop(self, interval_seconds: int): """Memory monitoring loop.""" while self._monitoring: try: stats = self.get_memory_stats() # Record metrics monitoring_system.metrics_collector.record_metric( "memory.usage_percent", stats.percent_used ) monitoring_system.metrics_collector.record_metric( "memory.available_mb", stats.available_mb ) monitoring_system.metrics_collector.record_metric( "memory.process_mb", stats.process_memory_mb ) # Notify callbacks for callback in self._callbacks: try: callback(stats) except Exception as e: logger.error(f"Memory monitor callback failed: {e}") await asyncio.sleep(interval_seconds) except asyncio.CancelledError: break except Exception as e: logger.error(f"Memory monitoring error: {e}") await asyncio.sleep(interval_seconds) def get_memory_stats(self) -> MemoryStats: """Get current memory statistics.""" try: # System memory memory = psutil.virtual_memory() swap = psutil.swap_memory() # Process memory process = psutil.Process() process_memory = process.memory_info() # Determine memory pressure pressure = 'low' if memory.percent >= self._thresholds['critical']: pressure = 'critical' elif memory.percent >= self._thresholds['high']: pressure = 'high' elif memory.percent >= self._thresholds['medium']: pressure = 'medium' return MemoryStats( total_mb=memory.total / (1024 * 1024), available_mb=memory.available / (1024 * 1024), used_mb=memory.used / (1024 * 1024), percent_used=memory.percent, process_memory_mb=process_memory.rss / (1024 * 1024), swap_used_mb=swap.used / (1024 * 1024), memory_pressure=pressure ) except Exception as e: logger.error(f"Failed to get memory stats: {e}") return MemoryStats(0, 0, 0, 0, 0, 0, 'unknown') def add_callback(self, callback: Callable[[MemoryStats], None]): """Add memory monitoring callback.""" self._callbacks.append(callback) def remove_callback(self, callback: Callable[[MemoryStats], None]): """Remove memory monitoring callback.""" if callback in self._callbacks: self._callbacks.remove(callback) class ChunkedDataProcessor: """Processes large datasets in chunks to manage memory usage.""" def __init__(self, chunk_size: int = 10000, max_memory_mb: float = 500): self.chunk_size = chunk_size self.max_memory_mb = max_memory_mb self.temp_dir = Path(tempfile.gettempdir()) / "mcp_data_chunks" self.temp_dir.mkdir(exist_ok=True) self._chunk_cache: Dict[str, DatasetChunk] = {} self._cache_lock = threading.Lock() def chunk_dataframe(self, df: pd.DataFrame, chunk_id_prefix: str = "chunk") -> List[DatasetChunk]: """Split DataFrame into chunks.""" chunks = [] total_rows = len(df) for i in range(0, total_rows, self.chunk_size): start_row = i end_row = min(i + self.chunk_size, total_rows) chunk_data = df.iloc[start_row:end_row].copy() chunk = DatasetChunk( chunk_id=len(chunks), start_row=start_row, end_row=end_row, data=chunk_data, file_path=None, size_bytes=chunk_data.memory_usage(deep=True).sum() ) chunks.append(chunk) logger.info(f"Split DataFrame into {len(chunks)} chunks") return chunks async def process_chunks_async( self, chunks: List[DatasetChunk], processor_func: Callable[[pd.DataFrame], pd.DataFrame], max_concurrent: int = 3 ) -> List[pd.DataFrame]: """Process chunks asynchronously with memory management.""" semaphore = asyncio.Semaphore(max_concurrent) results = [] async def process_chunk(chunk: DatasetChunk) -> pd.DataFrame: async with semaphore: # Check memory before processing memory_stats = memory_monitor.get_memory_stats() if memory_stats.memory_pressure in ['high', 'critical']: logger.warning(f"High memory pressure ({memory_stats.percent_used}%), waiting...") await asyncio.sleep(1) gc.collect() # Process chunk in thread pool loop = asyncio.get_event_loop() result = await loop.run_in_executor( None, processor_func, chunk.data ) return result # Process all chunks tasks = [process_chunk(chunk) for chunk in chunks] results = await asyncio.gather(*tasks) return results def save_chunk_to_disk(self, chunk: DatasetChunk, chunk_id: str) -> str: """Save chunk to disk and return file path.""" file_path = self.temp_dir / f"{chunk_id}.parquet" try: chunk.data.to_parquet(file_path, compression='snappy') chunk.file_path = str(file_path) chunk.data = None # Free memory with self._cache_lock: self._chunk_cache[chunk_id] = chunk logger.debug(f"Saved chunk {chunk_id} to disk: {file_path}") return str(file_path) except Exception as e: logger.error(f"Failed to save chunk to disk: {e}") raise def load_chunk_from_disk(self, chunk_id: str) -> Optional[DatasetChunk]: """Load chunk from disk.""" with self._cache_lock: if chunk_id not in self._chunk_cache: return None chunk = self._chunk_cache[chunk_id] if chunk.data is None and chunk.file_path: try: chunk.data = pd.read_parquet(chunk.file_path) logger.debug(f"Loaded chunk {chunk_id} from disk") except Exception as e: logger.error(f"Failed to load chunk from disk: {e}") return None return chunk def cleanup_chunks(self, chunk_ids: List[str] = None): """Clean up chunk files and cache.""" with self._cache_lock: if chunk_ids is None: chunk_ids = list(self._chunk_cache.keys()) for chunk_id in chunk_ids: if chunk_id in self._chunk_cache: chunk = self._chunk_cache[chunk_id] # Delete file if exists if chunk.file_path and os.path.exists(chunk.file_path): try: os.remove(chunk.file_path) logger.debug(f"Deleted chunk file: {chunk.file_path}") except Exception as e: logger.error(f"Failed to delete chunk file: {e}") # Remove from cache del self._chunk_cache[chunk_id] # Force garbage collection gc.collect() class MemoryEfficientDataLoader: """Loads large datasets efficiently with memory management.""" def __init__(self, memory_limit_mb: float = 1000): self.memory_limit_mb = memory_limit_mb self.chunk_processor = ChunkedDataProcessor() async def load_large_dataset( self, file_path: str, file_format: str = 'auto', chunk_size: int = 10000 ) -> Iterator[pd.DataFrame]: """Load large dataset in chunks.""" if file_format == 'auto': file_format = Path(file_path).suffix.lower().lstrip('.') try: if file_format == 'csv': chunk_iter = pd.read_csv(file_path, chunksize=chunk_size) elif file_format in ['xlsx', 'xls']: # Excel files need to be loaded entirely first, then chunked df = pd.read_excel(file_path) chunks = self.chunk_processor.chunk_dataframe(df) chunk_iter = (chunk.data for chunk in chunks) elif file_format == 'parquet': # Parquet supports native chunking parquet_file = pd.read_parquet(file_path) chunks = self.chunk_processor.chunk_dataframe(parquet_file) chunk_iter = (chunk.data for chunk in chunks) else: raise ValueError(f"Unsupported file format: {file_format}") chunk_count = 0 for chunk in chunk_iter: # Monitor memory before yielding chunk memory_stats = memory_monitor.get_memory_stats() if memory_stats.memory_pressure == 'critical': logger.warning("Critical memory pressure, forcing garbage collection") gc.collect() await asyncio.sleep(0.1) # Allow other tasks to run chunk_count += 1 logger.debug(f"Loaded chunk {chunk_count}, shape: {chunk.shape}") yield chunk except Exception as e: logger.error(f"Failed to load dataset: {e}") raise async def process_large_dataset( self, file_path: str, processor_func: Callable[[pd.DataFrame], pd.DataFrame], output_path: Optional[str] = None, chunk_size: int = 10000 ) -> Optional[str]: """Process large dataset with memory management.""" processed_chunks = [] chunk_count = 0 async for chunk in self.load_large_dataset(file_path, chunk_size=chunk_size): # Process chunk try: processed_chunk = processor_func(chunk) processed_chunks.append(processed_chunk) chunk_count += 1 # Check memory usage memory_stats = memory_monitor.get_memory_stats() if memory_stats.memory_pressure in ['high', 'critical']: logger.info(f"High memory pressure, saving intermediate results") # Save intermediate results and clear memory if output_path: temp_path = f"{output_path}.temp_{chunk_count}" combined = pd.concat(processed_chunks, ignore_index=True) combined.to_parquet(temp_path) processed_chunks = [] gc.collect() except Exception as e: logger.error(f"Failed to process chunk {chunk_count}: {e}") raise # Combine all processed chunks if processed_chunks: result_df = pd.concat(processed_chunks, ignore_index=True) if output_path: result_df.to_parquet(output_path) logger.info(f"Saved processed dataset to: {output_path}") return output_path else: return result_df return None class MemoryOptimizer: """Optimizes memory usage for DataFrames and other objects.""" @staticmethod def optimize_dataframe_memory(df: pd.DataFrame) -> pd.DataFrame: """Optimize DataFrame memory usage by downcasting numeric types.""" original_memory = df.memory_usage(deep=True).sum() # Optimize numeric columns for col in df.select_dtypes(include=['int64']).columns: df[col] = pd.to_numeric(df[col], downcast='integer') for col in df.select_dtypes(include=['float64']).columns: df[col] = pd.to_numeric(df[col], downcast='float') # Optimize object columns (strings) for col in df.select_dtypes(include=['object']).columns: if df[col].dtype == 'object': try: # Try to convert to category if it has few unique values unique_ratio = df[col].nunique() / len(df) if unique_ratio < 0.5: # Less than 50% unique values df[col] = df[col].astype('category') except: pass optimized_memory = df.memory_usage(deep=True).sum() reduction = (original_memory - optimized_memory) / original_memory * 100 logger.info(f"Memory optimization: {reduction:.1f}% reduction " f"({original_memory / 1024**2:.1f}MB -> {optimized_memory / 1024**2:.1f}MB)") return df @staticmethod def get_object_size(obj: Any) -> int: """Get approximate size of Python object in bytes.""" try: return len(pickle.dumps(obj)) except: # Fallback for non-picklable objects return len(str(obj).encode('utf-8')) class MemoryManager: """Main memory management coordinator.""" def __init__(self): self.monitor = MemoryMonitor() self.chunk_processor = ChunkedDataProcessor() self.data_loader = MemoryEfficientDataLoader() self.optimizer = MemoryOptimizer() self._memory_callbacks: List[Callable] = [] self._cleanup_threshold = 85.0 # Trigger cleanup at 85% memory usage async def start(self): """Start memory management system.""" await self.monitor.start_monitoring() # Add memory pressure callback self.monitor.add_callback(self._handle_memory_pressure) logger.info("Memory manager started") async def stop(self): """Stop memory management system.""" await self.monitor.stop_monitoring() self.chunk_processor.cleanup_chunks() logger.info("Memory manager stopped") def _handle_memory_pressure(self, stats: MemoryStats): """Handle memory pressure situations.""" if stats.percent_used >= self._cleanup_threshold: logger.warning(f"Memory pressure detected ({stats.percent_used}%), triggering cleanup") # Force garbage collection gc.collect() # Notify callbacks for callback in self._memory_callbacks: try: callback(stats) except Exception as e: logger.error(f"Memory pressure callback failed: {e}") def add_memory_callback(self, callback: Callable[[MemoryStats], None]): """Add callback for memory pressure events.""" self._memory_callbacks.append(callback) @contextmanager def memory_context(self, operation_name: str = "operation"): """Context manager for monitoring memory usage during operations.""" start_stats = self.monitor.get_memory_stats() start_time = datetime.utcnow() logger.info(f"Starting {operation_name} - Memory: {start_stats.percent_used:.1f}%") try: yield finally: end_stats = self.monitor.get_memory_stats() end_time = datetime.utcnow() duration = (end_time - start_time).total_seconds() memory_change = end_stats.process_memory_mb - start_stats.process_memory_mb logger.info(f"Completed {operation_name} in {duration:.1f}s - " f"Memory: {end_stats.percent_used:.1f}% " f"(change: {memory_change:+.1f}MB)") async def process_large_dataset_safely( self, file_path: str, processor_func: Callable[[pd.DataFrame], pd.DataFrame], output_path: Optional[str] = None ) -> Any: """Process large dataset with comprehensive memory management.""" with self.memory_context(f"processing {Path(file_path).name}"): # Check available memory stats = self.monitor.get_memory_stats() if stats.memory_pressure == 'critical': raise MemoryError("Insufficient memory to process dataset") # Determine optimal chunk size based on available memory available_mb = stats.available_mb chunk_size = min(50000, max(1000, int(available_mb * 100))) # Heuristic logger.info(f"Processing with chunk size: {chunk_size}") return await self.data_loader.process_large_dataset( file_path, processor_func, output_path, chunk_size ) def get_memory_report(self) -> Dict[str, Any]: """Get comprehensive memory usage report.""" stats = self.monitor.get_memory_stats() chunk_stats = self.chunk_processor.get_stats() if hasattr(self.chunk_processor, 'get_stats') else {} return { 'timestamp': datetime.utcnow().isoformat(), 'system_memory': stats.to_dict(), 'chunk_processor': chunk_stats, 'recommendations': self._get_memory_recommendations(stats) } def _get_memory_recommendations(self, stats: MemoryStats) -> List[str]: """Get memory optimization recommendations.""" recommendations = [] if stats.memory_pressure == 'critical': recommendations.append("Critical memory usage - consider reducing dataset size or increasing system memory") recommendations.append("Enable aggressive garbage collection and memory cleanup") recommendations.append("Consider processing data in smaller chunks") elif stats.memory_pressure == 'high': recommendations.append("High memory usage - enable aggressive chunking and caching") recommendations.append("Consider offloading data to disk storage") if stats.swap_used_mb > 100: recommendations.append("Swap usage detected - consider increasing RAM or optimizing memory usage") recommendations.append("Review memory-intensive operations and optimize algorithms") if stats.process_memory_mb > 1000: recommendations.append("High process memory usage - consider memory optimization techniques") recommendations.append("Review DataFrame memory usage and apply optimizations") if stats.available_mb < 500: recommendations.append("Low available memory - consider freeing unused resources") return recommendations async def trigger_memory_cleanup(self, aggressive: bool = False): """Trigger memory cleanup operations.""" logger.info(f"Triggering {'aggressive' if aggressive else 'standard'} memory cleanup") # Clear chunk processor cache self.chunk_processor.cleanup_chunks() # Clear data loader cache if available if hasattr(self.data_loader, 'clear_cache'): self.data_loader.clear_cache() # Force garbage collection if aggressive: # Multiple GC passes for aggressive cleanup for _ in range(3): gc.collect() await asyncio.sleep(0.1) else: gc.collect() # Log memory stats after cleanup stats = self.monitor.get_memory_stats() logger.info(f"Memory cleanup completed - Usage: {stats.percent_used:.1f}%") async def optimize_for_large_dataset(self, estimated_size_mb: float) -> Dict[str, Any]: """Optimize system settings for large dataset processing.""" current_stats = self.monitor.get_memory_stats() # Calculate optimal settings available_memory = current_stats.available_mb recommended_chunk_size = min(50000, max(1000, int(available_memory * 50))) # 50 rows per MB available # Adjust chunk processor settings self.chunk_processor.chunk_size = recommended_chunk_size self.chunk_processor.max_memory_mb = min(available_memory * 0.7, 1000) # Use 70% of available memory # Adjust data loader settings self.data_loader.memory_limit_mb = min(available_memory * 0.8, 2000) # Use 80% of available memory optimization_settings = { 'estimated_dataset_size_mb': estimated_size_mb, 'available_memory_mb': available_memory, 'recommended_chunk_size': recommended_chunk_size, 'chunk_processor_memory_limit_mb': self.chunk_processor.max_memory_mb, 'data_loader_memory_limit_mb': self.data_loader.memory_limit_mb, 'memory_pressure': current_stats.memory_pressure } logger.info(f"Optimized settings for {estimated_size_mb}MB dataset: {optimization_settings}") return optimization_settings # Global memory manager instance memory_monitor = MemoryMonitor() memory_manager = MemoryManager()