Coverage for /Users/les/Projects/crackerjack/crackerjack/services/performance_benchmarks.py: 0%

308 statements  

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

1import json 

2import statistics 

3import subprocess 

4import time 

5import typing as t 

6from contextlib import suppress 

7from dataclasses import dataclass, field 

8from pathlib import Path 

9from typing import Any 

10 

11from rich.console import Console 

12from rich.table import Table 

13 

14from crackerjack.models.protocols import FileSystemInterface 

15 

16 

17@dataclass 

18class BenchmarkResult: 

19 name: str 

20 duration_seconds: float 

21 memory_usage_mb: float = 0.0 

22 cpu_percent: float = 0.0 

23 iterations: int = 1 

24 metadata: dict[str, Any] = field(default_factory=dict) 

25 

26 

27@dataclass 

28class PerformanceReport: 

29 total_duration: float 

30 workflow_benchmarks: list[BenchmarkResult] = field(default_factory=list) 

31 test_benchmarks: dict[str, Any] = field(default_factory=dict) 

32 hook_performance: dict[str, float] = field(default_factory=dict) 

33 file_operation_stats: dict[str, float] = field(default_factory=dict) 

34 recommendations: list[str] = field(default_factory=list) 

35 baseline_comparison: dict[str, float] = field(default_factory=dict) 

36 

37 

38class PerformanceBenchmarkService: 

39 def __init__( 

40 self, 

41 filesystem: FileSystemInterface, 

42 console: Console | None = None, 

43 ) -> None: 

44 self.filesystem = filesystem 

45 self.console = console or Console() 

46 self.project_root = Path.cwd() 

47 self.benchmarks_dir = self.project_root / ".benchmarks" 

48 self.history_file = self.benchmarks_dir / "performance_history.json" 

49 

50 self.benchmarks_dir.mkdir(exist_ok=True) 

51 

52 def run_comprehensive_benchmark( 

53 self, 

54 run_tests: bool = True, 

55 run_hooks: bool = True, 

56 iterations: int = 1, 

57 ) -> PerformanceReport: 

58 self.console.print( 

59 "[cyan]🚀 Starting comprehensive performance benchmark...[/ cyan]", 

60 ) 

61 

62 start_time = time.time() 

63 report = self._initialize_performance_report() 

64 

65 self._run_requested_benchmarks(report, run_tests, run_hooks, iterations) 

66 self._finalize_performance_report(report, start_time) 

67 

68 return report 

69 

70 def _initialize_performance_report(self) -> PerformanceReport: 

71 return PerformanceReport(total_duration=0.0) 

72 

73 def _run_requested_benchmarks( 

74 self, 

75 report: PerformanceReport, 

76 run_tests: bool, 

77 run_hooks: bool, 

78 iterations: int, 

79 ) -> None: 

80 if run_tests: 

81 report.test_benchmarks = self._benchmark_test_suite(iterations) 

82 

83 if run_hooks: 

84 report.hook_performance = self._benchmark_hooks(iterations) 

85 

86 report.workflow_benchmarks = self._benchmark_workflow_components(iterations) 

87 report.file_operation_stats = self._benchmark_file_operations() 

88 

89 def _finalize_performance_report( 

90 self, 

91 report: PerformanceReport, 

92 start_time: float, 

93 ) -> None: 

94 report.total_duration = time.time() - start_time 

95 report.recommendations = self._generate_performance_recommendations(report) 

96 report.baseline_comparison = self._compare_with_baseline(report) 

97 self._save_performance_history(report) 

98 

99 def _benchmark_test_suite(self, iterations: int = 1) -> dict[str, Any]: 

100 self.console.print("[dim]📊 Benchmarking test suite...[/ dim]") 

101 

102 benchmark_results = {} 

103 

104 try: 

105 for i in range(iterations): 

106 start_time = time.time() 

107 

108 result = subprocess.run( 

109 [ 

110 "uv", 

111 "run", 

112 "pytest", 

113 "- - benchmark-only", 

114 "- - benchmark-json =.benchmarks / test_benchmark.json", 

115 "--tb=no", 

116 "- q", 

117 ], 

118 check=False, 

119 capture_output=True, 

120 text=True, 

121 timeout=300, 

122 ) 

123 

124 duration = time.time() - start_time 

125 

126 benchmark_file = self.benchmarks_dir / "test_benchmark.json" 

127 if benchmark_file.exists(): 

128 with benchmark_file.open() as f: 

129 benchmark_data = json.load(f) 

130 

131 benchmark_results[f"iteration_{i + 1}"] = { 

132 "total_duration": duration, 

133 "benchmark_data": benchmark_data, 

134 "success": result.returncode == 0, 

135 } 

136 else: 

137 benchmark_results[f"iteration_{i + 1}"] = { 

138 "total_duration": duration, 

139 "success": result.returncode == 0, 

140 "note": "No benchmark tests found", 

141 } 

142 

143 except subprocess.TimeoutExpired: 

144 benchmark_results["error"] = "Test benchmarking timed out" 

145 except Exception as e: 

146 benchmark_results["error"] = f"Test benchmarking failed: {e}" 

147 

148 return benchmark_results 

149 

150 def _benchmark_hooks(self, iterations: int = 1) -> dict[str, float]: 

151 self.console.print("[dim]🔧 Benchmarking hooks performance...[/ dim]") 

152 

153 hook_performance = {} 

154 

155 hooks_to_test = [ 

156 "trailing-whitespace", 

157 "end-of-file-fixer", 

158 "ruff-format", 

159 "ruff-check", 

160 "gitleaks", 

161 "pyright", 

162 "bandit", 

163 "vulture", 

164 ] 

165 

166 for hook_name in hooks_to_test: 

167 durations: list[float] = [] 

168 

169 for _i in range(iterations): 

170 try: 

171 start_time = time.time() 

172 subprocess.run( 

173 [ 

174 "uv", 

175 "run", 

176 "pre-commit", 

177 "run", 

178 hook_name, 

179 "- - all-files", 

180 ], 

181 check=False, 

182 capture_output=True, 

183 text=True, 

184 timeout=120, 

185 ) 

186 duration = time.time() - start_time 

187 durations.append(duration) 

188 except subprocess.TimeoutExpired: 

189 durations.append(120.0) 

190 except Exception: 

191 durations.append(float("inf")) 

192 

193 if durations and all(d != float("inf") for d in durations): 

194 hook_performance[hook_name] = { 

195 "mean_duration": statistics.mean(durations), 

196 "min_duration": min(durations), 

197 "max_duration": max(durations), 

198 } 

199 

200 return hook_performance 

201 

202 def _benchmark_workflow_components( 

203 self, 

204 iterations: int = 1, 

205 ) -> list[BenchmarkResult]: 

206 self.console.print("[dim]⚙️ Benchmarking workflow components...[/ dim]") 

207 

208 results = [] 

209 

210 start_time = time.time() 

211 python_files = list(self.project_root.rglob("*.py")) 

212 file_discovery_duration = time.time() - start_time 

213 

214 results.append( 

215 BenchmarkResult( 

216 name="file_discovery", 

217 duration_seconds=file_discovery_duration, 

218 metadata={"files_found": len(python_files)}, 

219 ), 

220 ) 

221 

222 start_time = time.time() 

223 pyproject_path = self.project_root / "pyproject.toml" 

224 if pyproject_path.exists(): 

225 with suppress(Exception): 

226 import tomllib 

227 

228 with pyproject_path.open("rb") as f: 

229 tomllib.load(f) 

230 config_load_duration = time.time() - start_time 

231 

232 results.append( 

233 BenchmarkResult( 

234 name="config_loading", 

235 duration_seconds=config_load_duration, 

236 ), 

237 ) 

238 

239 return results 

240 

241 def _benchmark_file_operations(self) -> dict[str, float]: 

242 stats = {} 

243 

244 test_files = list(self.project_root.glob("*.py"))[:10] 

245 if test_files: 

246 start_time = time.time() 

247 for file_path in test_files: 

248 with suppress(Exception): 

249 file_path.read_text(encoding="utf-8") 

250 read_duration = time.time() - start_time 

251 stats["file_read_ops"] = read_duration / len(test_files) 

252 

253 return stats 

254 

255 def _generate_performance_recommendations( 

256 self, 

257 report: PerformanceReport, 

258 ) -> list[str]: 

259 recommendations = [] 

260 

261 self._add_test_suite_recommendations(report, recommendations) 

262 self._add_hook_performance_recommendations(report, recommendations) 

263 self._add_component_performance_recommendations(report, recommendations) 

264 self._add_overall_performance_recommendations(report, recommendations) 

265 

266 return recommendations 

267 

268 def _add_test_suite_recommendations( 

269 self, 

270 report: PerformanceReport, 

271 recommendations: list[str], 

272 ) -> None: 

273 if not report.test_benchmarks: 

274 return 

275 

276 for iteration_data in report.test_benchmarks.values(): 

277 if self._is_slow_test_iteration(iteration_data): 

278 recommendations.append( 

279 "Consider optimizing test suite-execution time exceeds 1 minute", 

280 ) 

281 break 

282 

283 def _is_slow_test_iteration(self, iteration_data: Any) -> bool: 

284 return ( 

285 isinstance(iteration_data, dict) 

286 and iteration_data.get("total_duration", 0) > 60 

287 ) 

288 

289 def _add_hook_performance_recommendations( 

290 self, 

291 report: PerformanceReport, 

292 recommendations: list[str], 

293 ) -> None: 

294 slow_hooks = self._identify_slow_hooks(report.hook_performance) 

295 if slow_hooks: 

296 recommendations.append(self._format_slow_hooks_message(slow_hooks)) 

297 

298 def _identify_slow_hooks( 

299 self, 

300 hook_performance: dict[str, float], 

301 ) -> list[tuple[str, float]]: 

302 slow_hooks = [] 

303 for hook_name, perf_data in hook_performance.items(): 

304 if isinstance(perf_data, dict): 

305 mean_duration = perf_data.get("mean_duration", 0) 

306 if mean_duration > 30: 

307 slow_hooks.append((hook_name, mean_duration)) 

308 return slow_hooks 

309 

310 def _format_slow_hooks_message(self, slow_hooks: list[tuple[str, float]]) -> str: 

311 hooks_info = ", ".join(f"{h}({d: .1f}s)" for h, d in slow_hooks[:3]) 

312 return ( 

313 f"Slow hooks detected: {hooks_info}. " 

314 "Consider hook optimization or selective execution." 

315 ) 

316 

317 def _add_component_performance_recommendations( 

318 self, 

319 report: PerformanceReport, 

320 recommendations: list[str], 

321 ) -> None: 

322 slow_components = self._identify_slow_components(report.workflow_benchmarks) 

323 if slow_components: 

324 components_names = ", ".join(c.name for c in slow_components) 

325 recommendations.append( 

326 f"Slow workflow components: {components_names}. " 

327 "Consider caching or optimization.", 

328 ) 

329 

330 def _identify_slow_components( 

331 self, 

332 workflow_benchmarks: list[BenchmarkResult], 

333 ) -> list[BenchmarkResult]: 

334 return [b for b in workflow_benchmarks if b.duration_seconds > 5] 

335 

336 def _add_overall_performance_recommendations( 

337 self, 

338 report: PerformanceReport, 

339 recommendations: list[str], 

340 ) -> None: 

341 if report.total_duration > 300: 

342 recommendations.append( 

343 "Overall workflow execution is slow. Consider enabling - - skip-hooks " 

344 "during development iterations.", 

345 ) 

346 

347 def _compare_with_baseline( 

348 self, 

349 current_report: PerformanceReport, 

350 ) -> dict[str, float]: 

351 baseline_comparison = {} 

352 

353 try: 

354 history = self._load_performance_history() 

355 if not history: 

356 return baseline_comparison 

357 

358 self._add_overall_performance_comparison( 

359 current_report, 

360 history, 

361 baseline_comparison, 

362 ) 

363 self._add_component_performance_comparison( 

364 current_report, 

365 history, 

366 baseline_comparison, 

367 ) 

368 

369 except Exception as e: 

370 baseline_comparison["error"] = f"Could not load baseline: {e}" 

371 

372 return baseline_comparison 

373 

374 def _load_performance_history(self) -> list[dict[str, Any]] | None: 

375 if not self.history_file.exists(): 

376 return None 

377 

378 with self.history_file.open() as f: 

379 history = json.load(f) 

380 

381 return history if history and len(history) > 1 else None 

382 

383 def _add_overall_performance_comparison( 

384 self, 

385 current_report: PerformanceReport, 

386 history: list[dict[str, Any]], 

387 comparison: dict[str, Any], 

388 ) -> None: 

389 recent_runs = history[-5:] 

390 baseline_duration = statistics.median( 

391 [r["total_duration"] for r in recent_runs], 

392 ) 

393 

394 performance_change = ( 

395 (current_report.total_duration - baseline_duration) / baseline_duration 

396 ) * 100 

397 comparison["overall_performance_change_percent"] = performance_change 

398 

399 def _add_component_performance_comparison( 

400 self, 

401 current_report: PerformanceReport, 

402 history: list[dict[str, Any]], 

403 comparison: dict[str, Any], 

404 ) -> None: 

405 recent_runs = history[-5:] 

406 if not recent_runs: 

407 return 

408 

409 component_durations = recent_runs[-1].get("component_durations", {}) 

410 

411 for component in current_report.workflow_benchmarks: 

412 if component.name in component_durations: 

413 old_duration = component_durations[component.name] 

414 change = self._calculate_performance_change( 

415 component.duration_seconds, 

416 old_duration, 

417 ) 

418 comparison[f"{component.name}_change_percent"] = change 

419 

420 def _calculate_performance_change( 

421 self, 

422 current_duration: float, 

423 old_duration: float, 

424 ) -> float: 

425 return ((current_duration - old_duration) / old_duration) * 100 

426 

427 def _save_performance_history(self, report: PerformanceReport) -> None: 

428 try: 

429 history = [] 

430 if self.history_file.exists(): 

431 with self.history_file.open() as f: 

432 history = json.load(f) 

433 

434 record = { 

435 "timestamp": time.time(), 

436 "total_duration": report.total_duration, 

437 "component_durations": { 

438 c.name: c.duration_seconds for c in report.workflow_benchmarks 

439 }, 

440 "hook_durations": { 

441 hook: (perf["mean_duration"] if isinstance(perf, dict) else perf) 

442 for hook, perf in report.hook_performance.items() 

443 }, 

444 "recommendations_count": len(report.recommendations), 

445 } 

446 

447 history.append(record) 

448 

449 history = history[-50:] 

450 

451 with self.history_file.open("w") as f: 

452 json.dump(history, f, indent=2) 

453 

454 except Exception as e: 

455 self.console.print( 

456 f"[yellow]⚠️[/ yellow] Could not save performance history: {e}", 

457 ) 

458 

459 def display_performance_report(self, report: PerformanceReport) -> None: 

460 self.console.print( 

461 "\n[bold cyan]🚀 Performance Benchmark Report[/ bold cyan]\n" 

462 ) 

463 

464 self._display_overall_stats(report) 

465 self._display_workflow_components(report) 

466 self._display_hook_performance(report) 

467 self._display_baseline_comparison(report) 

468 self._display_recommendations(report) 

469 

470 self.console.print( 

471 f"\n[dim]📁 Benchmark data saved to: {self.benchmarks_dir}[/ dim]", 

472 ) 

473 

474 def _display_overall_stats(self, report: PerformanceReport) -> None: 

475 self.console.print( 

476 f"[green]⏱️ Total Duration: {report.total_duration: .2f}s[/ green]", 

477 ) 

478 

479 def _display_workflow_components(self, report: PerformanceReport) -> None: 

480 if not report.workflow_benchmarks: 

481 return 

482 

483 table = Table(title="Workflow Component Performance") 

484 table.add_column("Component", style="cyan") 

485 table.add_column("Duration (s)", style="yellow", justify="right") 

486 table.add_column("Metadata", style="dim") 

487 

488 for benchmark in report.workflow_benchmarks: 

489 metadata_str = ", ".join(f"{k}={v}" for k, v in benchmark.metadata.items()) 

490 table.add_row( 

491 benchmark.name, 

492 f"{benchmark.duration_seconds: .3f}", 

493 metadata_str, 

494 ) 

495 

496 self.console.print(table) 

497 self.console.print() 

498 

499 def _display_hook_performance(self, report: PerformanceReport) -> None: 

500 if not report.hook_performance: 

501 return 

502 

503 table = Table(title="Hook Performance Analysis") 

504 table.add_column("Hook", style="cyan") 

505 table.add_column("Mean (s)", style="yellow", justify="right") 

506 table.add_column("Min (s)", style="green", justify="right") 

507 table.add_column("Max (s)", style="red", justify="right") 

508 

509 for hook_name, perf_data in report.hook_performance.items(): 

510 if isinstance(perf_data, dict): 

511 table.add_row( 

512 hook_name, 

513 f"{perf_data.get('mean_duration', 0): .2f}", 

514 f"{perf_data.get('min_duration', 0): .2f}", 

515 f"{perf_data.get('max_duration', 0): .2f}", 

516 ) 

517 

518 self.console.print(table) 

519 self.console.print() 

520 

521 def _display_baseline_comparison(self, report: PerformanceReport) -> None: 

522 if not report.baseline_comparison: 

523 return 

524 

525 self._print_comparison_header() 

526 self._print_comparison_metrics(report.baseline_comparison) 

527 self.console.print() 

528 

529 def _print_comparison_header(self) -> None: 

530 self.console.print("[bold]📊 Performance Comparison[/ bold]") 

531 

532 def _print_comparison_metrics(self, baseline_comparison: dict[str, t.Any]) -> None: 

533 for metric, value in baseline_comparison.items(): 

534 if isinstance(value, float | int) and "percent" in metric: 

535 color = "green" if value < 0 else "red" if value > 10 else "yellow" 

536 direction = "faster" if value < 0 else "slower" 

537 self.console.print( 

538 f" {metric}: [{color}]{abs(value): .1f}% {direction}[/{color}]", 

539 ) 

540 

541 def _display_recommendations(self, report: PerformanceReport) -> None: 

542 if report.recommendations: 

543 self.console.print( 

544 "[bold yellow]💡 Performance Recommendations[/ bold yellow]", 

545 ) 

546 for i, rec in enumerate(report.recommendations, 1): 

547 self.console.print(f" {i}. {rec}") 

548 else: 

549 self.console.print("[green]✨ No performance issues detected ![/ green]") 

550 

551 def get_performance_trends(self, days: int = 7) -> dict[str, Any]: 

552 try: 

553 recent_history = self._get_recent_history(days) 

554 if not recent_history: 

555 return self._handle_insufficient_trend_data() 

556 

557 trends = {} 

558 self._add_duration_trends(recent_history, trends) 

559 self._add_component_trends(recent_history, trends) 

560 trends["data_points"] = len(recent_history) 

561 

562 return trends 

563 

564 except Exception as e: 

565 return {"error": f"Could not analyze trends: {e}"} 

566 

567 def _get_recent_history(self, days: int) -> list[dict[str, Any]] | None: 

568 if not self.history_file.exists(): 

569 return None 

570 

571 with self.history_file.open() as f: 

572 history = json.load(f) 

573 

574 cutoff_time = time.time() - (days * 86400) 

575 recent_history = [r for r in history if r.get("timestamp", 0) > cutoff_time] 

576 

577 return recent_history if len(recent_history) >= 2 else None 

578 

579 def _handle_insufficient_trend_data(self) -> dict[str, str]: 

580 if not self.history_file.exists(): 

581 return {"error": "No performance history available"} 

582 return {"error": "Insufficient data for trend analysis"} 

583 

584 def _add_duration_trends( 

585 self, recent_history: list[dict[str, Any]], trends: dict[str, Any] 

586 ) -> None: 

587 durations = [r["total_duration"] for r in recent_history] 

588 trends["duration_trend"] = { 

589 "current": durations[-1], 

590 "average": statistics.mean(durations), 

591 "trend": self._determine_trend_direction(durations), 

592 } 

593 

594 def _add_component_trends( 

595 self, recent_history: list[dict[str, Any]], trends: dict[str, Any] 

596 ) -> None: 

597 component_trends = {} 

598 latest_components = recent_history[-1].get("component_durations", {}) 

599 

600 for component in latest_components: 

601 component_durations = self._extract_component_durations( 

602 recent_history, 

603 component, 

604 ) 

605 if len(component_durations) >= 2: 

606 component_trends[component] = { 

607 "current": component_durations[-1], 

608 "average": statistics.mean(component_durations), 

609 "trend": self._determine_trend_direction(component_durations), 

610 } 

611 

612 trends["component_trends"] = component_trends 

613 

614 def _extract_component_durations( 

615 self, 

616 recent_history: list[dict[str, Any]], 

617 component: str, 

618 ) -> list[float]: 

619 return [ 

620 r.get("component_durations", {}).get(component) 

621 for r in recent_history 

622 if component in r.get("component_durations", {}) 

623 ] 

624 

625 def _determine_trend_direction(self, durations: list[float]) -> str: 

626 current = durations[-1] 

627 historical_average = statistics.mean(durations[:-1]) 

628 return "improving" if current < historical_average else "degrading"