Coverage for /Users/les/Projects/crackerjack/crackerjack/core/performance_monitor.py: 0%

164 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1""" 

2Performance monitoring and metrics collection for async operations. 

3 

4This module provides comprehensive monitoring of async operations, 

5timeout tracking, and performance analysis capabilities. 

6""" 

7 

8import json 

9import logging 

10import time 

11import typing as t 

12from collections import defaultdict, deque 

13from dataclasses import dataclass, field 

14from pathlib import Path 

15from threading import Lock 

16 

17from rich.console import Console 

18from rich.table import Table 

19 

20logger = logging.getLogger("crackerjack.performance_monitor") 

21 

22 

23@dataclass 

24class OperationMetrics: 

25 """Metrics for a specific operation.""" 

26 

27 operation_name: str 

28 total_calls: int = 0 

29 successful_calls: int = 0 

30 failed_calls: int = 0 

31 timeout_calls: int = 0 

32 total_time: float = 0.0 

33 min_time: float = float("inf") 

34 max_time: float = 0.0 

35 recent_times: deque = field(default_factory=lambda: deque(maxlen=100)) 

36 

37 @property 

38 def success_rate(self) -> float: 

39 """Calculate success rate as percentage.""" 

40 if self.total_calls == 0: 

41 return 0.0 

42 return (self.successful_calls / self.total_calls) * 100 

43 

44 @property 

45 def average_time(self) -> float: 

46 """Calculate average execution time.""" 

47 if self.successful_calls == 0: 

48 return 0.0 

49 return self.total_time / self.successful_calls 

50 

51 @property 

52 def recent_average_time(self) -> float: 

53 """Calculate recent average execution time.""" 

54 if not self.recent_times: 

55 return 0.0 

56 return sum(self.recent_times) / len(self.recent_times) 

57 

58 

59@dataclass 

60class TimeoutEvent: 

61 """Record of a timeout event.""" 

62 

63 operation: str 

64 expected_timeout: float 

65 actual_duration: float 

66 timestamp: float 

67 error_message: str = "" 

68 

69 

70class AsyncPerformanceMonitor: 

71 """Monitor and track performance of async operations.""" 

72 

73 def __init__(self, max_timeout_events: int = 1000) -> None: 

74 self.metrics: dict[str, OperationMetrics] = {} 

75 self.timeout_events: deque[TimeoutEvent] = deque(maxlen=max_timeout_events) 

76 self._lock = Lock() 

77 self.start_time = time.time() 

78 

79 # Circuit breaker tracking 

80 self.circuit_breaker_events: dict[str, list[float]] = defaultdict(list) 

81 

82 # Performance thresholds 

83 self.performance_thresholds: dict[str, dict[str, float]] = { 

84 "default": { 

85 "warning_time": 30.0, 

86 "critical_time": 60.0, 

87 "min_success_rate": 80.0, 

88 }, 

89 "fast_hooks": { 

90 "warning_time": 30.0, 

91 "critical_time": 90.0, 

92 "min_success_rate": 95.0, 

93 }, 

94 "comprehensive_hooks": { 

95 "warning_time": 120.0, 

96 "critical_time": 300.0, 

97 "min_success_rate": 90.0, 

98 }, 

99 "test_execution": { 

100 "warning_time": 300.0, 

101 "critical_time": 600.0, 

102 "min_success_rate": 85.0, 

103 }, 

104 "ai_agent_processing": { 

105 "warning_time": 60.0, 

106 "critical_time": 180.0, 

107 "min_success_rate": 75.0, 

108 }, 

109 "network_operations": { 

110 "warning_time": 5.0, 

111 "critical_time": 15.0, 

112 "min_success_rate": 95.0, 

113 }, 

114 "file_operations": { 

115 "warning_time": 3.0, 

116 "critical_time": 10.0, 

117 "min_success_rate": 98.0, 

118 }, 

119 } 

120 

121 def record_operation_start(self, operation: str) -> float: 

122 """Record the start of an operation.""" 

123 return time.time() 

124 

125 def record_operation_success(self, operation: str, start_time: float) -> None: 

126 """Record successful completion of an operation.""" 

127 duration = time.time() - start_time 

128 

129 with self._lock: 

130 if operation not in self.metrics: 

131 self.metrics[operation] = OperationMetrics(operation) 

132 

133 metrics = self.metrics[operation] 

134 metrics.total_calls += 1 

135 metrics.successful_calls += 1 

136 metrics.total_time += duration 

137 metrics.min_time = min(metrics.min_time, duration) 

138 metrics.max_time = max(metrics.max_time, duration) 

139 metrics.recent_times.append(duration) 

140 

141 def record_operation_failure(self, operation: str, start_time: float) -> None: 

142 """Record failed completion of an operation.""" 

143 time.time() - start_time 

144 

145 with self._lock: 

146 if operation not in self.metrics: 

147 self.metrics[operation] = OperationMetrics(operation) 

148 

149 metrics = self.metrics[operation] 

150 metrics.total_calls += 1 

151 metrics.failed_calls += 1 

152 

153 def record_operation_timeout( 

154 self, 

155 operation: str, 

156 start_time: float, 

157 expected_timeout: float, 

158 error_message: str = "", 

159 ) -> None: 

160 """Record timeout of an operation.""" 

161 duration = time.time() - start_time 

162 

163 with self._lock: 

164 if operation not in self.metrics: 

165 self.metrics[operation] = OperationMetrics(operation) 

166 

167 metrics = self.metrics[operation] 

168 metrics.total_calls += 1 

169 metrics.timeout_calls += 1 

170 

171 # Record timeout event 

172 timeout_event = TimeoutEvent( 

173 operation=operation, 

174 expected_timeout=expected_timeout, 

175 actual_duration=duration, 

176 timestamp=time.time(), 

177 error_message=error_message, 

178 ) 

179 self.timeout_events.append(timeout_event) 

180 

181 def record_circuit_breaker_event(self, operation: str, opened: bool) -> None: 

182 """Record circuit breaker state change.""" 

183 with self._lock: 

184 if opened: 

185 self.circuit_breaker_events[operation].append(time.time()) 

186 

187 def get_operation_metrics(self, operation: str) -> OperationMetrics | None: 

188 """Get metrics for a specific operation.""" 

189 with self._lock: 

190 return self.metrics.get(operation) 

191 

192 def get_all_metrics(self) -> dict[str, OperationMetrics]: 

193 """Get all operation metrics.""" 

194 with self._lock: 

195 return self.metrics.copy() 

196 

197 def get_recent_timeout_events(self, limit: int = 10) -> list[TimeoutEvent]: 

198 """Get recent timeout events.""" 

199 with self._lock: 

200 return list(self.timeout_events)[-limit:] 

201 

202 def get_performance_alerts(self) -> list[dict[str, t.Any]]: 

203 """Get current performance alerts.""" 

204 alerts = [] 

205 

206 with self._lock: 

207 for operation, metrics in self.metrics.items(): 

208 thresholds = self.performance_thresholds.get( 

209 operation, self.performance_thresholds["default"] 

210 ) 

211 

212 # Check success rate 

213 if metrics.success_rate < thresholds["min_success_rate"]: 

214 alerts.append( 

215 { 

216 "type": "success_rate", 

217 "operation": operation, 

218 "current_value": metrics.success_rate, 

219 "threshold": thresholds["min_success_rate"], 

220 "severity": "critical" 

221 if metrics.success_rate < 50 

222 else "warning", 

223 } 

224 ) 

225 

226 # Check average response time 

227 avg_time = metrics.recent_average_time 

228 if avg_time > thresholds["critical_time"]: 

229 alerts.append( 

230 { 

231 "type": "response_time", 

232 "operation": operation, 

233 "current_value": avg_time, 

234 "threshold": thresholds["critical_time"], 

235 "severity": "critical", 

236 } 

237 ) 

238 elif avg_time > thresholds["warning_time"]: 

239 alerts.append( 

240 { 

241 "type": "response_time", 

242 "operation": operation, 

243 "current_value": avg_time, 

244 "threshold": thresholds["warning_time"], 

245 "severity": "warning", 

246 } 

247 ) 

248 

249 return alerts 

250 

251 def get_summary_stats(self) -> dict[str, t.Any]: 

252 """Get summary statistics.""" 

253 with self._lock: 

254 total_calls = sum(m.total_calls for m in self.metrics.values()) 

255 total_successes = sum(m.successful_calls for m in self.metrics.values()) 

256 total_timeouts = sum(m.timeout_calls for m in self.metrics.values()) 

257 total_failures = sum(m.failed_calls for m in self.metrics.values()) 

258 

259 uptime = time.time() - self.start_time 

260 

261 return { 

262 "uptime_seconds": uptime, 

263 "total_operations": total_calls, 

264 "total_successes": total_successes, 

265 "total_timeouts": total_timeouts, 

266 "total_failures": total_failures, 

267 "overall_success_rate": (total_successes / total_calls * 100) 

268 if total_calls > 0 

269 else 0.0, 

270 "timeout_rate": (total_timeouts / total_calls * 100) 

271 if total_calls > 0 

272 else 0.0, 

273 "operations_per_minute": (total_calls / (uptime / 60)) 

274 if uptime > 0 

275 else 0.0, 

276 "unique_operations": len(self.metrics), 

277 "circuit_breaker_trips": len(self.circuit_breaker_events), 

278 } 

279 

280 def export_metrics_json(self, filepath: Path) -> None: 

281 """Export metrics to JSON file.""" 

282 with self._lock: 

283 data = { 

284 "summary": self.get_summary_stats(), 

285 "operations": { 

286 name: { 

287 "total_calls": m.total_calls, 

288 "successful_calls": m.successful_calls, 

289 "failed_calls": m.failed_calls, 

290 "timeout_calls": m.timeout_calls, 

291 "success_rate": m.success_rate, 

292 "average_time": m.average_time, 

293 "recent_average_time": m.recent_average_time, 

294 "min_time": m.min_time if m.min_time != float("inf") else 0, 

295 "max_time": m.max_time, 

296 } 

297 for name, m in self.metrics.items() 

298 }, 

299 "recent_timeout_events": [ 

300 { 

301 "operation": event.operation, 

302 "expected_timeout": event.expected_timeout, 

303 "actual_duration": event.actual_duration, 

304 "timestamp": event.timestamp, 

305 "error_message": event.error_message, 

306 } 

307 for event in list(self.timeout_events)[-50:] 

308 ], 

309 "performance_alerts": self.get_performance_alerts(), 

310 } 

311 

312 filepath.write_text(json.dumps(data, indent=2)) 

313 

314 def print_performance_report(self, console: Console | None = None) -> None: 

315 """Print a formatted performance report.""" 

316 if console is None: 

317 console = Console() 

318 

319 console.print("\n[bold blue]🔍 Async Performance Monitor Report[/bold blue]") 

320 console.print("=" * 60) 

321 

322 # Summary stats 

323 summary = self.get_summary_stats() 

324 console.print(f"⏱️ Uptime: {summary['uptime_seconds']:.1f}s") 

325 console.print(f"📊 Total Operations: {summary['total_operations']}") 

326 console.print(f"✅ Success Rate: {summary['overall_success_rate']:.1f}%") 

327 console.print(f"⏰ Timeout Rate: {summary['timeout_rate']:.1f}%") 

328 console.print(f"🚀 Operations/min: {summary['operations_per_minute']:.1f}") 

329 

330 # Operation metrics table 

331 if self.metrics: 

332 console.print("\n[bold]Operation Metrics:[/bold]") 

333 table = Table() 

334 table.add_column("Operation") 

335 table.add_column("Calls") 

336 table.add_column("Success %") 

337 table.add_column("Avg Time") 

338 table.add_column("Recent Avg") 

339 table.add_column("Timeouts") 

340 

341 with self._lock: 

342 for name, metrics in sorted(self.metrics.items()): 

343 table.add_row( 

344 name, 

345 str(metrics.total_calls), 

346 f"{metrics.success_rate:.1f}%", 

347 f"{metrics.average_time:.2f}s", 

348 f"{metrics.recent_average_time:.2f}s", 

349 str(metrics.timeout_calls), 

350 ) 

351 

352 console.print(table) 

353 

354 # Performance alerts 

355 alerts = self.get_performance_alerts() 

356 if alerts: 

357 console.print("\n[bold red]⚠️ Performance Alerts:[/bold red]") 

358 for alert in alerts: 

359 severity_emoji = "🔴" if alert["severity"] == "critical" else "🟡" 

360 console.print( 

361 f"{severity_emoji} {alert['operation']}: {alert['type']} " 

362 f"{alert['current_value']:.1f} (threshold: {alert['threshold']:.1f})" 

363 ) 

364 

365 # Recent timeouts 

366 recent_timeouts = self.get_recent_timeout_events(5) 

367 if recent_timeouts: 

368 console.print("\n[bold yellow]⏰ Recent Timeouts:[/bold yellow]") 

369 for timeout in recent_timeouts: 

370 console.print( 

371 f" • {timeout.operation}: {timeout.actual_duration:.1f}s " 

372 f"(expected: {timeout.expected_timeout:.1f}s)" 

373 ) 

374 

375 

376# Global performance monitor instance 

377_global_performance_monitor: AsyncPerformanceMonitor | None = None 

378 

379 

380def get_performance_monitor() -> AsyncPerformanceMonitor: 

381 """Get the global performance monitor instance.""" 

382 global _global_performance_monitor 

383 if _global_performance_monitor is None: 

384 _global_performance_monitor = AsyncPerformanceMonitor() 

385 return _global_performance_monitor 

386 

387 

388def reset_performance_monitor() -> None: 

389 """Reset the global performance monitor.""" 

390 global _global_performance_monitor 

391 _global_performance_monitor = AsyncPerformanceMonitor()