Spaces:
Paused
Paused
File size: 26,182 Bytes
56c063a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 | """
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__)
@dataclass
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
}
@dataclass
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() |