Spaces:
Paused
Paused
Download shared/performance_monitor.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 26.2 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/performance_monitor.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/shared/performance_monitor.py
-
curl -L -o performance_monitor.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/performance_monitor.py
26.2 kB
| """ | |
| Comprehensive performance monitoring system for MCP AI Data Scientist. | |
| Provides real-time performance metrics, alerts, and optimization recommendations. | |
| """ | |
| import asyncio | |
| import logging | |
| import time | |
| import json | |
| from typing import Dict, List, Any, Optional, Callable | |
| from dataclasses import dataclass, asdict | |
| from datetime import datetime, timedelta | |
| from collections import defaultdict, deque | |
| import threading | |
| import psutil | |
| import gc | |
| from .caching import cache_manager | |
| from .connection_pool import resource_manager | |
| from .memory_manager import memory_manager | |
| from .query_optimizer import supabase_optimizer | |
| from .parallel_processor import parallel_processor | |
| from .monitoring import monitoring_system | |
| logger = logging.getLogger(__name__) | |
| class PerformanceMetrics: | |
| """Comprehensive performance metrics.""" | |
| timestamp: datetime | |
| system_metrics: Dict[str, Any] | |
| cache_metrics: Dict[str, Any] | |
| connection_metrics: Dict[str, Any] | |
| memory_metrics: Dict[str, Any] | |
| query_metrics: Dict[str, Any] | |
| parallel_metrics: Dict[str, Any] | |
| overall_health_score: float | |
| def to_dict(self) -> Dict[str, Any]: | |
| return { | |
| 'timestamp': self.timestamp.isoformat(), | |
| 'system_metrics': self.system_metrics, | |
| 'cache_metrics': self.cache_metrics, | |
| 'connection_metrics': self.connection_metrics, | |
| 'memory_metrics': self.memory_metrics, | |
| 'query_metrics': self.query_metrics, | |
| 'parallel_metrics': self.parallel_metrics, | |
| 'overall_health_score': self.overall_health_score | |
| } | |
| class PerformanceAlert: | |
| """Performance alert.""" | |
| alert_id: str | |
| severity: str # 'low', 'medium', 'high', 'critical' | |
| category: str # 'memory', 'cache', 'query', 'connection', 'parallel' | |
| message: str | |
| details: Dict[str, Any] | |
| timestamp: datetime | |
| resolved: bool = False | |
| def to_dict(self) -> Dict[str, Any]: | |
| return asdict(self) | |
| class PerformanceThresholds: | |
| """Performance monitoring thresholds.""" | |
| def __init__(self): | |
| # Memory thresholds | |
| self.memory_warning = 75.0 # % usage | |
| self.memory_critical = 90.0 # % usage | |
| # Cache thresholds | |
| self.cache_hit_rate_warning = 0.6 # 60% | |
| self.cache_hit_rate_critical = 0.4 # 40% | |
| # Query thresholds | |
| self.query_duration_warning = 1000 # ms | |
| self.query_duration_critical = 5000 # ms | |
| # Connection thresholds | |
| self.connection_utilization_warning = 0.8 # 80% | |
| self.connection_utilization_critical = 0.95 # 95% | |
| # Parallel processing thresholds | |
| self.task_failure_rate_warning = 0.1 # 10% | |
| self.task_failure_rate_critical = 0.2 # 20% | |
| # Queue thresholds | |
| self.queue_backlog_warning = 50 | |
| self.queue_backlog_critical = 200 | |
| class PerformanceMonitor: | |
| """Main performance monitoring system.""" | |
| def __init__(self): | |
| self.thresholds = PerformanceThresholds() | |
| self._monitoring = False | |
| self._monitor_task: Optional[asyncio.Task] = None | |
| self._metrics_history: deque = deque(maxlen=1000) # Keep last 1000 metrics | |
| self._active_alerts: Dict[str, PerformanceAlert] = {} | |
| self._alert_callbacks: List[Callable[[PerformanceAlert], None]] = [] | |
| self._performance_trends: Dict[str, deque] = defaultdict(lambda: deque(maxlen=100)) | |
| async def start(self, monitoring_interval: int = 30): | |
| """Start performance monitoring.""" | |
| if self._monitoring: | |
| return | |
| self._monitoring = True | |
| self._monitor_task = asyncio.create_task(self._monitoring_loop(monitoring_interval)) | |
| logger.info("Performance monitoring started") | |
| async def stop(self): | |
| """Stop performance monitoring.""" | |
| self._monitoring = False | |
| if self._monitor_task: | |
| self._monitor_task.cancel() | |
| try: | |
| await self._monitor_task | |
| except asyncio.CancelledError: | |
| pass | |
| logger.info("Performance monitoring stopped") | |
| async def _monitoring_loop(self, interval: int): | |
| """Main monitoring loop.""" | |
| while self._monitoring: | |
| try: | |
| # Collect comprehensive metrics | |
| metrics = await self._collect_metrics() | |
| # Store metrics | |
| self._metrics_history.append(metrics) | |
| # Update performance trends | |
| self._update_trends(metrics) | |
| # Check for alerts | |
| await self._check_alerts(metrics) | |
| # Record metrics to monitoring system | |
| await self._record_metrics(metrics) | |
| await asyncio.sleep(interval) | |
| except asyncio.CancelledError: | |
| break | |
| except Exception as e: | |
| logger.error(f"Performance monitoring error: {e}") | |
| await asyncio.sleep(interval) | |
| async def _collect_metrics(self) -> PerformanceMetrics: | |
| """Collect comprehensive performance metrics.""" | |
| timestamp = datetime.utcnow() | |
| # System metrics | |
| system_metrics = self._collect_system_metrics() | |
| # Cache metrics | |
| cache_metrics = cache_manager.get_comprehensive_stats() | |
| # Connection metrics | |
| connection_metrics = resource_manager.get_all_stats() | |
| # Memory metrics | |
| memory_metrics = memory_manager.get_memory_report() | |
| # Query metrics | |
| query_metrics = await supabase_optimizer.get_query_statistics() | |
| # Parallel processing metrics | |
| parallel_metrics = parallel_processor.get_system_stats() | |
| # Calculate overall health score | |
| health_score = self._calculate_health_score( | |
| system_metrics, cache_metrics, connection_metrics, | |
| memory_metrics, query_metrics, parallel_metrics | |
| ) | |
| return PerformanceMetrics( | |
| timestamp=timestamp, | |
| system_metrics=system_metrics, | |
| cache_metrics=cache_metrics, | |
| connection_metrics=connection_metrics, | |
| memory_metrics=memory_metrics, | |
| query_metrics=query_metrics, | |
| parallel_metrics=parallel_metrics, | |
| overall_health_score=health_score | |
| ) | |
| def _collect_system_metrics(self) -> Dict[str, Any]: | |
| """Collect system-level metrics.""" | |
| try: | |
| # CPU metrics | |
| cpu_percent = psutil.cpu_percent(interval=1) | |
| cpu_count = psutil.cpu_count() | |
| # Memory metrics | |
| memory = psutil.virtual_memory() | |
| swap = psutil.swap_memory() | |
| # Disk metrics | |
| disk = psutil.disk_usage('/') | |
| # Network metrics (if available) | |
| try: | |
| network = psutil.net_io_counters() | |
| network_metrics = { | |
| 'bytes_sent': network.bytes_sent, | |
| 'bytes_recv': network.bytes_recv, | |
| 'packets_sent': network.packets_sent, | |
| 'packets_recv': network.packets_recv | |
| } | |
| except: | |
| network_metrics = {} | |
| # Process metrics | |
| process = psutil.Process() | |
| process_metrics = { | |
| 'cpu_percent': process.cpu_percent(), | |
| 'memory_mb': process.memory_info().rss / 1024 / 1024, | |
| 'num_threads': process.num_threads(), | |
| 'num_fds': process.num_fds() if hasattr(process, 'num_fds') else 0 | |
| } | |
| return { | |
| 'cpu': { | |
| 'percent': cpu_percent, | |
| 'count': cpu_count, | |
| 'load_avg': psutil.getloadavg() if hasattr(psutil, 'getloadavg') else [0, 0, 0] | |
| }, | |
| 'memory': { | |
| 'total_mb': memory.total / 1024 / 1024, | |
| 'available_mb': memory.available / 1024 / 1024, | |
| 'percent': memory.percent, | |
| 'swap_percent': swap.percent | |
| }, | |
| 'disk': { | |
| 'total_gb': disk.total / 1024 / 1024 / 1024, | |
| 'free_gb': disk.free / 1024 / 1024 / 1024, | |
| 'percent': (disk.used / disk.total) * 100 | |
| }, | |
| 'network': network_metrics, | |
| 'process': process_metrics | |
| } | |
| except Exception as e: | |
| logger.error(f"Failed to collect system metrics: {e}") | |
| return {'error': str(e)} | |
| def _calculate_health_score(self, *metric_groups) -> float: | |
| """Calculate overall system health score (0-100).""" | |
| scores = [] | |
| try: | |
| # System health (25% weight) | |
| system_metrics = metric_groups[0] | |
| if 'cpu' in system_metrics and 'memory' in system_metrics: | |
| cpu_score = max(0, 100 - system_metrics['cpu']['percent']) | |
| memory_score = max(0, 100 - system_metrics['memory']['percent']) | |
| system_score = (cpu_score + memory_score) / 2 | |
| scores.append(('system', system_score, 0.25)) | |
| # Cache health (20% weight) | |
| cache_metrics = metric_groups[1] | |
| if 'general_cache' in cache_metrics: | |
| hit_rate = cache_metrics['general_cache'].get('hit_rate', 0) | |
| cache_score = hit_rate * 100 | |
| scores.append(('cache', cache_score, 0.20)) | |
| # Connection health (15% weight) | |
| connection_metrics = metric_groups[2] | |
| if connection_metrics: | |
| # Average utilization across all pools | |
| utilizations = [] | |
| for pool_stats in connection_metrics.values(): | |
| if isinstance(pool_stats, dict) and 'active_connections' in pool_stats: | |
| util = pool_stats['active_connections'] / max(pool_stats.get('max_connections', 1), 1) | |
| utilizations.append(min(100, max(0, 100 - (util * 100)))) | |
| if utilizations: | |
| connection_score = sum(utilizations) / len(utilizations) | |
| scores.append(('connections', connection_score, 0.15)) | |
| # Memory health (20% weight) | |
| memory_metrics = metric_groups[3] | |
| if 'system_memory' in memory_metrics: | |
| memory_pressure = memory_metrics['system_memory'].get('memory_pressure', 'unknown') | |
| pressure_scores = {'low': 100, 'medium': 75, 'high': 50, 'critical': 25, 'unknown': 50} | |
| memory_score = pressure_scores.get(memory_pressure, 50) | |
| scores.append(('memory', memory_score, 0.20)) | |
| # Parallel processing health (20% weight) | |
| parallel_metrics = metric_groups[5] | |
| if 'performance' in parallel_metrics: | |
| success_rate = parallel_metrics['performance'].get('success_rate', 0) | |
| parallel_score = success_rate * 100 | |
| scores.append(('parallel', parallel_score, 0.20)) | |
| # Calculate weighted average | |
| if scores: | |
| weighted_sum = sum(score * weight for _, score, weight in scores) | |
| total_weight = sum(weight for _, _, weight in scores) | |
| return weighted_sum / total_weight if total_weight > 0 else 50 | |
| except Exception as e: | |
| logger.error(f"Failed to calculate health score: {e}") | |
| return 50 # Default neutral score | |
| def _update_trends(self, metrics: PerformanceMetrics): | |
| """Update performance trends.""" | |
| # System trends | |
| if 'cpu' in metrics.system_metrics: | |
| self._performance_trends['cpu_percent'].append(metrics.system_metrics['cpu']['percent']) | |
| if 'memory' in metrics.system_metrics: | |
| self._performance_trends['memory_percent'].append(metrics.system_metrics['memory']['percent']) | |
| # Cache trends | |
| if 'general_cache' in metrics.cache_metrics: | |
| hit_rate = metrics.cache_metrics['general_cache'].get('hit_rate', 0) | |
| self._performance_trends['cache_hit_rate'].append(hit_rate) | |
| # Health score trend | |
| self._performance_trends['health_score'].append(metrics.overall_health_score) | |
| async def _check_alerts(self, metrics: PerformanceMetrics): | |
| """Check for performance alerts.""" | |
| current_alerts = set() | |
| # Memory alerts | |
| if 'memory' in metrics.system_metrics: | |
| memory_percent = metrics.system_metrics['memory']['percent'] | |
| if memory_percent >= self.thresholds.memory_critical: | |
| alert = await self._create_alert( | |
| 'memory_critical', | |
| 'critical', | |
| 'memory', | |
| f"Critical memory usage: {memory_percent:.1f}%", | |
| {'memory_percent': memory_percent, 'threshold': self.thresholds.memory_critical} | |
| ) | |
| current_alerts.add(alert.alert_id) | |
| elif memory_percent >= self.thresholds.memory_warning: | |
| alert = await self._create_alert( | |
| 'memory_warning', | |
| 'high', | |
| 'memory', | |
| f"High memory usage: {memory_percent:.1f}%", | |
| {'memory_percent': memory_percent, 'threshold': self.thresholds.memory_warning} | |
| ) | |
| current_alerts.add(alert.alert_id) | |
| # Cache alerts | |
| if 'general_cache' in metrics.cache_metrics: | |
| hit_rate = metrics.cache_metrics['general_cache'].get('hit_rate', 1) | |
| if hit_rate <= self.thresholds.cache_hit_rate_critical: | |
| alert = await self._create_alert( | |
| 'cache_hit_rate_critical', | |
| 'critical', | |
| 'cache', | |
| f"Critical cache hit rate: {hit_rate*100:.1f}%", | |
| {'hit_rate': hit_rate, 'threshold': self.thresholds.cache_hit_rate_critical} | |
| ) | |
| current_alerts.add(alert.alert_id) | |
| elif hit_rate <= self.thresholds.cache_hit_rate_warning: | |
| alert = await self._create_alert( | |
| 'cache_hit_rate_warning', | |
| 'medium', | |
| 'cache', | |
| f"Low cache hit rate: {hit_rate*100:.1f}%", | |
| {'hit_rate': hit_rate, 'threshold': self.thresholds.cache_hit_rate_warning} | |
| ) | |
| current_alerts.add(alert.alert_id) | |
| # Query performance alerts | |
| if 'slow_queries' in metrics.query_metrics: | |
| slow_query_count = len(metrics.query_metrics['slow_queries']) | |
| if slow_query_count > 10: | |
| alert = await self._create_alert( | |
| 'slow_queries', | |
| 'medium', | |
| 'query', | |
| f"High number of slow queries: {slow_query_count}", | |
| {'slow_query_count': slow_query_count} | |
| ) | |
| current_alerts.add(alert.alert_id) | |
| # Connection pool alerts | |
| for pool_name, pool_stats in metrics.connection_metrics.items(): | |
| if isinstance(pool_stats, dict) and 'active_connections' in pool_stats: | |
| utilization = pool_stats['active_connections'] / max(pool_stats.get('max_connections', 1), 1) | |
| if utilization >= self.thresholds.connection_utilization_critical: | |
| alert = await self._create_alert( | |
| f'connection_pool_{pool_name}_critical', | |
| 'critical', | |
| 'connection', | |
| f"Critical connection pool utilization for {pool_name}: {utilization*100:.1f}%", | |
| {'pool_name': pool_name, 'utilization': utilization} | |
| ) | |
| current_alerts.add(alert.alert_id) | |
| # Parallel processing alerts | |
| if 'performance' in metrics.parallel_metrics: | |
| success_rate = metrics.parallel_metrics['performance'].get('success_rate', 1) | |
| if success_rate <= (1 - self.thresholds.task_failure_rate_critical): | |
| alert = await self._create_alert( | |
| 'task_failure_rate_critical', | |
| 'critical', | |
| 'parallel', | |
| f"High task failure rate: {(1-success_rate)*100:.1f}%", | |
| {'success_rate': success_rate, 'failure_rate': 1-success_rate} | |
| ) | |
| current_alerts.add(alert.alert_id) | |
| # Resolve alerts that are no longer active | |
| for alert_id in list(self._active_alerts.keys()): | |
| if alert_id not in current_alerts: | |
| await self._resolve_alert(alert_id) | |
| async def _create_alert(self, alert_id: str, severity: str, category: str, message: str, details: Dict[str, Any]) -> PerformanceAlert: | |
| """Create or update a performance alert.""" | |
| if alert_id in self._active_alerts: | |
| # Update existing alert | |
| alert = self._active_alerts[alert_id] | |
| alert.timestamp = datetime.utcnow() | |
| alert.details.update(details) | |
| else: | |
| # Create new alert | |
| alert = PerformanceAlert( | |
| alert_id=alert_id, | |
| severity=severity, | |
| category=category, | |
| message=message, | |
| details=details, | |
| timestamp=datetime.utcnow() | |
| ) | |
| self._active_alerts[alert_id] = alert | |
| # Notify callbacks | |
| for callback in self._alert_callbacks: | |
| try: | |
| callback(alert) | |
| except Exception as e: | |
| logger.error(f"Alert callback failed: {e}") | |
| logger.warning(f"Performance alert: {alert.message}") | |
| return alert | |
| async def _resolve_alert(self, alert_id: str): | |
| """Resolve a performance alert.""" | |
| if alert_id in self._active_alerts: | |
| alert = self._active_alerts[alert_id] | |
| alert.resolved = True | |
| del self._active_alerts[alert_id] | |
| logger.info(f"Performance alert resolved: {alert.message}") | |
| async def _record_metrics(self, metrics: PerformanceMetrics): | |
| """Record metrics to monitoring system.""" | |
| try: | |
| # Record key metrics | |
| monitoring_system.metrics_collector.record_metric( | |
| "performance.health_score", metrics.overall_health_score | |
| ) | |
| if 'cpu' in metrics.system_metrics: | |
| monitoring_system.metrics_collector.record_metric( | |
| "performance.cpu_percent", metrics.system_metrics['cpu']['percent'] | |
| ) | |
| if 'memory' in metrics.system_metrics: | |
| monitoring_system.metrics_collector.record_metric( | |
| "performance.memory_percent", metrics.system_metrics['memory']['percent'] | |
| ) | |
| if 'general_cache' in metrics.cache_metrics: | |
| hit_rate = metrics.cache_metrics['general_cache'].get('hit_rate', 0) | |
| monitoring_system.metrics_collector.record_metric( | |
| "performance.cache_hit_rate", hit_rate | |
| ) | |
| except Exception as e: | |
| logger.error(f"Failed to record performance metrics: {e}") | |
| def add_alert_callback(self, callback: Callable[[PerformanceAlert], None]): | |
| """Add callback for performance alerts.""" | |
| self._alert_callbacks.append(callback) | |
| def remove_alert_callback(self, callback: Callable[[PerformanceAlert], None]): | |
| """Remove alert callback.""" | |
| if callback in self._alert_callbacks: | |
| self._alert_callbacks.remove(callback) | |
| def get_current_metrics(self) -> Optional[PerformanceMetrics]: | |
| """Get the most recent performance metrics.""" | |
| return self._metrics_history[-1] if self._metrics_history else None | |
| def get_metrics_history(self, hours: int = 24) -> List[PerformanceMetrics]: | |
| """Get performance metrics history.""" | |
| cutoff_time = datetime.utcnow() - timedelta(hours=hours) | |
| return [m for m in self._metrics_history if m.timestamp >= cutoff_time] | |
| def get_active_alerts(self) -> List[PerformanceAlert]: | |
| """Get all active performance alerts.""" | |
| return list(self._active_alerts.values()) | |
| def get_performance_trends(self) -> Dict[str, List[float]]: | |
| """Get performance trends.""" | |
| return {key: list(values) for key, values in self._performance_trends.items()} | |
| def get_performance_summary(self) -> Dict[str, Any]: | |
| """Get comprehensive performance summary.""" | |
| current_metrics = self.get_current_metrics() | |
| if not current_metrics: | |
| return {'error': 'No metrics available'} | |
| trends = self.get_performance_trends() | |
| alerts = self.get_active_alerts() | |
| # Calculate trend directions | |
| trend_analysis = {} | |
| for metric_name, values in trends.items(): | |
| if len(values) >= 2: | |
| recent_avg = sum(values[-5:]) / min(5, len(values)) | |
| older_avg = sum(values[-10:-5]) / min(5, len(values[-10:-5])) if len(values) >= 10 else recent_avg | |
| if recent_avg > older_avg * 1.05: | |
| trend_analysis[metric_name] = 'increasing' | |
| elif recent_avg < older_avg * 0.95: | |
| trend_analysis[metric_name] = 'decreasing' | |
| else: | |
| trend_analysis[metric_name] = 'stable' | |
| return { | |
| 'timestamp': datetime.utcnow().isoformat(), | |
| 'current_metrics': current_metrics.to_dict(), | |
| 'health_score': current_metrics.overall_health_score, | |
| 'active_alerts': [alert.to_dict() for alert in alerts], | |
| 'alert_summary': { | |
| 'total': len(alerts), | |
| 'critical': len([a for a in alerts if a.severity == 'critical']), | |
| 'high': len([a for a in alerts if a.severity == 'high']), | |
| 'medium': len([a for a in alerts if a.severity == 'medium']), | |
| 'low': len([a for a in alerts if a.severity == 'low']) | |
| }, | |
| 'trends': trend_analysis, | |
| 'recommendations': self._generate_recommendations(current_metrics, alerts) | |
| } | |
| def _generate_recommendations(self, metrics: PerformanceMetrics, alerts: List[PerformanceAlert]) -> List[str]: | |
| """Generate performance recommendations.""" | |
| recommendations = [] | |
| # Memory recommendations | |
| if 'memory' in metrics.system_metrics: | |
| memory_percent = metrics.system_metrics['memory']['percent'] | |
| if memory_percent > 80: | |
| recommendations.append("Consider increasing system memory or optimizing memory usage") | |
| recommendations.append("Enable aggressive memory cleanup and garbage collection") | |
| # Cache recommendations | |
| if 'general_cache' in metrics.cache_metrics: | |
| hit_rate = metrics.cache_metrics['general_cache'].get('hit_rate', 1) | |
| if hit_rate < 0.7: | |
| recommendations.append("Review caching strategy and increase cache TTL for frequently accessed data") | |
| recommendations.append("Consider increasing cache size limits") | |
| # Query recommendations | |
| if 'slow_queries' in metrics.query_metrics and len(metrics.query_metrics['slow_queries']) > 5: | |
| recommendations.append("Optimize slow queries and consider adding database indexes") | |
| recommendations.append("Review query patterns and implement query result caching") | |
| # Connection pool recommendations | |
| for pool_name, pool_stats in metrics.connection_metrics.items(): | |
| if isinstance(pool_stats, dict) and 'active_connections' in pool_stats: | |
| utilization = pool_stats['active_connections'] / max(pool_stats.get('max_connections', 1), 1) | |
| if utilization > 0.8: | |
| recommendations.append(f"Consider increasing max_connections for pool '{pool_name}'") | |
| # Parallel processing recommendations | |
| if 'performance' in metrics.parallel_metrics: | |
| success_rate = metrics.parallel_metrics['performance'].get('success_rate', 1) | |
| if success_rate < 0.9: | |
| recommendations.append("Investigate task failures and improve error handling") | |
| recommendations.append("Consider adjusting task timeout and retry settings") | |
| # Alert-based recommendations | |
| critical_alerts = [a for a in alerts if a.severity == 'critical'] | |
| if critical_alerts: | |
| recommendations.append("Address critical performance alerts immediately") | |
| return recommendations | |
| # Global performance monitor instance | |
| performance_monitor = PerformanceMonitor() |