Coverage for /Users/les/Projects/crackerjack/crackerjack/services/metrics.py: 0%
74 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import json
2import sqlite3
3import threading
4from contextlib import contextmanager
5from datetime import date, datetime
6from pathlib import Path
7from typing import Any
10class MetricsCollector:
11 def __init__(self, db_path: Path | None = None) -> None:
12 if db_path is None:
13 db_dir = Path.home() / ".cache" / "crackerjack"
14 db_dir.mkdir(parents=True, exist_ok=True)
15 db_path = db_dir / "metrics.db"
17 self.db_path = db_path
18 self._lock = threading.Lock()
19 self._init_database()
21 def _init_database(self) -> None:
22 with self._get_connection() as conn:
23 conn.executescript("""
24 - - Jobs table
25 CREATE TABLE IF NOT EXISTS jobs (
26 id INTEGER PRIMARY KEY AUTOINCREMENT,
27 job_id TEXT UNIQUE NOT NULL,
28 start_time TIMESTAMP NOT NULL,
29 end_time TIMESTAMP,
30 status TEXT NOT NULL, - - 'running', 'success', 'failed', 'cancelled'
31 iterations INTEGER DEFAULT 0,
32 ai_agent BOOLEAN DEFAULT 0,
33 error_message TEXT,
34 metadata TEXT - - JSON field for additional data
35 );
37 - - Errors table
38 CREATE TABLE IF NOT EXISTS errors (
39 id INTEGER PRIMARY KEY AUTOINCREMENT,
40 job_id TEXT,
41 timestamp TIMESTAMP NOT NULL,
42 error_type TEXT NOT NULL, - - 'hook', 'test', 'lint', 'type_check', etc.
43 error_category TEXT, - - 'ruff', 'pyright', 'pytest', etc.
44 error_message TEXT,
45 file_path TEXT,
46 line_number INTEGER,
47 FOREIGN KEY (job_id) REFERENCES jobs(job_id)
48 );
50 - - Hook executions table
51 CREATE TABLE IF NOT EXISTS hook_executions (
52 id INTEGER PRIMARY KEY AUTOINCREMENT,
53 job_id TEXT,
54 timestamp TIMESTAMP NOT NULL,
55 hook_name TEXT NOT NULL,
56 hook_type TEXT, - - 'fast', 'comprehensive'
57 execution_time_ms INTEGER,
58 status TEXT, - - 'success', 'failed', 'skipped'
59 FOREIGN KEY (job_id) REFERENCES jobs(job_id)
60 );
62 - - Test executions table
63 CREATE TABLE IF NOT EXISTS test_executions (
64 id INTEGER PRIMARY KEY AUTOINCREMENT,
65 job_id TEXT,
66 timestamp TIMESTAMP NOT NULL,
67 total_tests INTEGER,
68 passed INTEGER,
69 failed INTEGER,
70 skipped INTEGER,
71 execution_time_ms INTEGER,
72 coverage_percent REAL,
73 FOREIGN KEY (job_id) REFERENCES jobs(job_id)
74 );
76 - - Orchestration executions table (NEW)
77 CREATE TABLE IF NOT EXISTS orchestration_executions (
78 id INTEGER PRIMARY KEY AUTOINCREMENT,
79 job_id TEXT,
80 timestamp TIMESTAMP NOT NULL,
81 execution_strategy TEXT NOT NULL, - - 'batch', 'individual', 'adaptive', 'selective'
82 progress_level TEXT NOT NULL, - - 'basic', 'detailed', 'granular', 'streaming'
83 ai_mode TEXT NOT NULL, - - 'single - agent', 'multi - agent', 'coordinator'
84 iteration_count INTEGER DEFAULT 1,
85 strategy_switches INTEGER DEFAULT 0, - - How many times strategy changed
86 correlation_insights TEXT, - - JSON of correlation analysis results
87 total_execution_time_ms INTEGER,
88 hooks_execution_time_ms INTEGER,
89 tests_execution_time_ms INTEGER,
90 ai_analysis_time_ms INTEGER,
91 FOREIGN KEY (job_id) REFERENCES jobs(job_id)
92 );
94 - - Strategy decisions table (NEW)
95 CREATE TABLE IF NOT EXISTS strategy_decisions (
96 id INTEGER PRIMARY KEY AUTOINCREMENT,
97 job_id TEXT,
98 iteration INTEGER,
99 timestamp TIMESTAMP NOT NULL,
100 previous_strategy TEXT,
101 selected_strategy TEXT NOT NULL,
102 decision_reason TEXT, - - Why this strategy was chosen
103 context_data TEXT, - - JSON of execution context
104 effectiveness_score REAL, - - How well the strategy worked (0 - 1)
105 FOREIGN KEY (job_id) REFERENCES jobs(job_id)
106 );
108 - - Individual test executions table (NEW - more granular than test_executions)
109 CREATE TABLE IF NOT EXISTS individual_test_executions (
110 id INTEGER PRIMARY KEY AUTOINCREMENT,
111 job_id TEXT,
112 timestamp TIMESTAMP NOT NULL,
113 test_id TEXT NOT NULL, - - Full test identifier
114 test_file TEXT NOT NULL,
115 test_class TEXT,
116 test_method TEXT,
117 status TEXT NOT NULL, - - 'passed', 'failed', 'skipped', 'error'
118 execution_time_ms INTEGER,
119 error_message TEXT,
120 error_traceback TEXT,
121 FOREIGN KEY (job_id) REFERENCES jobs(job_id)
122 );
124 - - Daily summary table (for quick stats)
125 CREATE TABLE IF NOT EXISTS daily_summary (
126 date DATE PRIMARY KEY,
127 total_jobs INTEGER DEFAULT 0,
128 successful_jobs INTEGER DEFAULT 0,
129 failed_jobs INTEGER DEFAULT 0,
130 total_errors INTEGER DEFAULT 0,
131 hook_errors INTEGER DEFAULT 0,
132 test_errors INTEGER DEFAULT 0,
133 lint_errors INTEGER DEFAULT 0,
134 type_errors INTEGER DEFAULT 0,
135 avg_job_duration_ms INTEGER,
136 total_ai_fixes INTEGER DEFAULT 0,
137 orchestrated_jobs INTEGER DEFAULT 0, - - NEW
138 avg_orchestration_iterations REAL DEFAULT 0, - - NEW
139 most_effective_strategy TEXT - - NEW
140 );
142 --Create indexes for performance
143 CREATE INDEX IF NOT EXISTS idx_jobs_start_time ON jobs(start_time);
144 CREATE INDEX IF NOT EXISTS idx_errors_job_id ON errors(job_id);
145 CREATE INDEX IF NOT EXISTS idx_errors_type ON errors(error_type);
146 CREATE INDEX IF NOT EXISTS idx_hooks_job_id ON hook_executions(job_id);
147 CREATE INDEX IF NOT EXISTS idx_tests_job_id ON test_executions(job_id);
148 CREATE INDEX IF NOT EXISTS idx_orchestration_job_id ON orchestration_executions(job_id);
149 CREATE INDEX IF NOT EXISTS idx_strategy_decisions_job_id ON strategy_decisions(job_id);
150 CREATE INDEX IF NOT EXISTS idx_individual_tests_job_id ON individual_test_executions(job_id);
151 CREATE INDEX IF NOT EXISTS idx_strategy_decisions_strategy ON strategy_decisions(selected_strategy);
152 """)
154 @contextmanager
155 def _get_connection(self):
156 conn = sqlite3.connect(str(self.db_path))
157 conn.row_factory = sqlite3.Row
158 try:
159 yield conn
160 conn.commit()
161 except Exception:
162 conn.rollback()
163 raise
164 finally:
165 conn.close()
167 def start_job(
168 self,
169 job_id: str,
170 ai_agent: bool = False,
171 metadata: dict[str, Any] | None = None,
172 ) -> None:
173 with self._lock, self._get_connection() as conn:
174 conn.execute(
175 """
176 INSERT INTO jobs (job_id, start_time, status, ai_agent, metadata)
177 VALUES (?, ?, 'running', ?, ?)
178 """,
179 (job_id, datetime.now(), ai_agent, json.dumps(metadata or {})),
180 )
182 def end_job(
183 self,
184 job_id: str,
185 status: str,
186 iterations: int = 0,
187 error_message: str | None = None,
188 ) -> None:
189 with self._lock, self._get_connection() as conn:
190 conn.execute(
191 """
192 UPDATE jobs
193 SET end_time=?, status=?, iterations=?, error_message=?
194 WHERE job_id=?
195 """,
196 (datetime.now(), status, iterations, error_message, job_id),
197 )
199 self._update_daily_summary(conn, datetime.now().date())
201 def record_error(
202 self,
203 job_id: str,
204 error_type: str,
205 error_category: str,
206 error_message: str,
207 file_path: str | None = None,
208 line_number: int | None = None,
209 ) -> None:
210 with self._lock, self._get_connection() as conn:
211 conn.execute(
212 """
213 INSERT INTO errors (job_id, timestamp, error_type, error_category,
214 error_message, file_path, line_number)
215 VALUES (?, ?, ?, ?, ?, ?, ?)
216 """,
217 (
218 job_id,
219 datetime.now(),
220 error_type,
221 error_category,
222 error_message,
223 file_path,
224 line_number,
225 ),
226 )
228 def record_hook_execution(
229 self,
230 job_id: str,
231 hook_name: str,
232 hook_type: str,
233 execution_time_ms: int,
234 status: str,
235 ) -> None:
236 with self._lock, self._get_connection() as conn:
237 conn.execute(
238 """
239 INSERT INTO hook_executions (job_id, timestamp, hook_name,
240 hook_type, execution_time_ms, status)
241 VALUES (?, ?, ?, ?, ?, ?)
242 """,
243 (
244 job_id,
245 datetime.now(),
246 hook_name,
247 hook_type,
248 execution_time_ms,
249 status,
250 ),
251 )
253 def record_test_execution(
254 self,
255 job_id: str,
256 total_tests: int,
257 passed: int,
258 failed: int,
259 skipped: int,
260 execution_time_ms: int,
261 coverage_percent: float | None = None,
262 ) -> None:
263 with self._lock, self._get_connection() as conn:
264 conn.execute(
265 """
266 INSERT INTO test_executions (job_id, timestamp, total_tests,
267 passed, failed, skipped,
268 execution_time_ms, coverage_percent)
269 VALUES (?, ?, ?, ?, ?, ?, ?, ?)
270 """,
271 (
272 job_id,
273 datetime.now(),
274 total_tests,
275 passed,
276 failed,
277 skipped,
278 execution_time_ms,
279 coverage_percent,
280 ),
281 )
283 def record_orchestration_execution(
284 self,
285 job_id: str,
286 execution_strategy: str,
287 progress_level: str,
288 ai_mode: str,
289 iteration_count: int,
290 strategy_switches: int,
291 correlation_insights: dict[str, Any],
292 total_execution_time_ms: int,
293 hooks_execution_time_ms: int,
294 tests_execution_time_ms: int,
295 ai_analysis_time_ms: int,
296 ) -> None:
297 with self._lock, self._get_connection() as conn:
298 conn.execute(
299 """
300 INSERT INTO orchestration_executions
301 (job_id, timestamp, execution_strategy, progress_level, ai_mode,
302 iteration_count, strategy_switches, correlation_insights,
303 total_execution_time_ms, hooks_execution_time_ms,
304 tests_execution_time_ms, ai_analysis_time_ms)
305 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
306 """,
307 (
308 job_id,
309 datetime.now(),
310 execution_strategy,
311 progress_level,
312 ai_mode,
313 iteration_count,
314 strategy_switches,
315 json.dumps(correlation_insights),
316 total_execution_time_ms,
317 hooks_execution_time_ms,
318 tests_execution_time_ms,
319 ai_analysis_time_ms,
320 ),
321 )
323 def record_strategy_decision(
324 self,
325 job_id: str,
326 iteration: int,
327 previous_strategy: str | None,
328 selected_strategy: str,
329 decision_reason: str,
330 context_data: dict[str, Any],
331 effectiveness_score: float | None = None,
332 ) -> None:
333 with self._lock, self._get_connection() as conn:
334 conn.execute(
335 """
336 INSERT INTO strategy_decisions
337 (job_id, iteration, timestamp, previous_strategy, selected_strategy,
338 decision_reason, context_data, effectiveness_score)
339 VALUES (?, ?, ?, ?, ?, ?, ?, ?)
340 """,
341 (
342 job_id,
343 iteration,
344 datetime.now(),
345 previous_strategy,
346 selected_strategy,
347 decision_reason,
348 json.dumps(context_data),
349 effectiveness_score,
350 ),
351 )
353 def record_individual_test(
354 self,
355 job_id: str,
356 test_id: str,
357 test_file: str,
358 test_class: str | None,
359 test_method: str | None,
360 status: str,
361 execution_time_ms: int | None,
362 error_message: str | None = None,
363 error_traceback: str | None = None,
364 ) -> None:
365 with self._lock, self._get_connection() as conn:
366 conn.execute(
367 """
368 INSERT INTO individual_test_executions
369 (job_id, timestamp, test_id, test_file, test_class, test_method,
370 status, execution_time_ms, error_message, error_traceback)
371 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
372 """,
373 (
374 job_id,
375 datetime.now(),
376 test_id,
377 test_file,
378 test_class,
379 test_method,
380 status,
381 execution_time_ms,
382 error_message,
383 error_traceback,
384 ),
385 )
387 def get_orchestration_stats(self) -> dict[str, Any]:
388 with self._get_connection() as conn:
389 strategy_stats = conn.execute("""
390 SELECT
391 selected_strategy,
392 COUNT(*) as usage_count,
393 AVG(effectiveness_score) as avg_effectiveness,
394 AVG(
395 SELECT iteration_count
396 FROM orchestration_executions o
397 WHERE o.job_id=sd.job_id
398 ) as avg_iterations_needed
399 FROM strategy_decisions sd
400 WHERE effectiveness_score IS NOT NULL
401 GROUP BY selected_strategy
402 ORDER BY avg_effectiveness DESC, usage_count DESC
403 """).fetchall()
405 correlation_patterns = conn.execute("""
406 SELECT
407 json_extract(correlation_insights, '$.problematic_hooks') as problematic_hooks,
408 COUNT(*) as frequency
409 FROM orchestration_executions
410 WHERE correlation_insights != 'null'
411 AND correlation_insights != '{}'
412 GROUP BY problematic_hooks
413 ORDER BY frequency DESC
414 LIMIT 10
415 """).fetchall()
417 performance_stats = conn.execute("""
418 SELECT
419 execution_strategy,
420 COUNT(*) as executions,
421 AVG(total_execution_time_ms) as avg_total_time,
422 AVG(hooks_execution_time_ms) as avg_hooks_time,
423 AVG(tests_execution_time_ms) as avg_tests_time,
424 AVG(ai_analysis_time_ms) as avg_ai_time,
425 AVG(iteration_count) as avg_iterations
426 FROM orchestration_executions
427 GROUP BY execution_strategy
428 """).fetchall()
430 test_failure_patterns = conn.execute("""
431 SELECT
432 test_file,
433 test_class,
434 test_method,
435 COUNT(*) as failure_count,
436 AVG(execution_time_ms) as avg_execution_time
437 FROM individual_test_executions
438 WHERE status='failed'
439 GROUP BY test_file, test_class, test_method
440 ORDER BY failure_count DESC
441 LIMIT 15
442 """).fetchall()
444 return {
445 "strategy_effectiveness": [dict(row) for row in strategy_stats],
446 "correlation_patterns": [dict(row) for row in correlation_patterns],
447 "performance_by_strategy": [dict(row) for row in performance_stats],
448 "test_failure_patterns": [dict(row) for row in test_failure_patterns],
449 }
451 def _update_daily_summary(
452 self,
453 conn: sqlite3.Connection,
454 date: date,
455 ) -> None:
456 job_stats = conn.execute(
457 """
458 SELECT
459 COUNT(*) as total_jobs,
460 SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) as successful_jobs,
461 SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) as failed_jobs,
462 AVG(CASE
463 WHEN end_time IS NOT NULL
464 THEN (julianday(end_time)-julianday(start_time)) * 86400000
465 ELSE NULL
466 END) as avg_duration_ms,
467 SUM(CASE WHEN ai_agent=1 AND status='success' THEN 1 ELSE 0 END) as ai_fixes
468 FROM jobs
469 WHERE DATE(start_time) = ?
470 """,
471 (date,),
472 ).fetchone()
474 error_stats = conn.execute(
475 """
476 SELECT
477 COUNT(*) as total_errors,
478 SUM(CASE WHEN error_type='hook' THEN 1 ELSE 0 END) as hook_errors,
479 SUM(CASE WHEN error_type='test' THEN 1 ELSE 0 END) as test_errors,
480 SUM(CASE WHEN error_type='lint' THEN 1 ELSE 0 END) as lint_errors,
481 SUM(CASE WHEN error_type='type_check' THEN 1 ELSE 0 END) as type_errors
482 FROM errors
483 WHERE DATE(timestamp) = ?
484 """,
485 (date,),
486 ).fetchone()
488 orchestration_stats = conn.execute(
489 """
490 SELECT
491 COUNT(*) as orchestrated_jobs,
492 AVG(iteration_count) as avg_iterations,
493 (SELECT selected_strategy
494 FROM strategy_decisions sd2
495 WHERE DATE(sd2.timestamp) = ?
496 GROUP BY selected_strategy
497 ORDER BY COUNT(*) DESC
498 LIMIT 1) as most_effective_strategy
499 FROM orchestration_executions
500 WHERE DATE(timestamp) = ?
501 """,
502 (date, date),
503 ).fetchone()
505 conn.execute(
506 """
507 INSERT OR REPLACE INTO daily_summary
508 (date, total_jobs, successful_jobs, failed_jobs, total_errors,
509 hook_errors, test_errors, lint_errors, type_errors,
510 avg_job_duration_ms, total_ai_fixes, orchestrated_jobs,
511 avg_orchestration_iterations, most_effective_strategy)
512 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
513 """,
514 (
515 date,
516 job_stats["total_jobs"] or 0,
517 job_stats["successful_jobs"] or 0,
518 job_stats["failed_jobs"] or 0,
519 error_stats["total_errors"] or 0,
520 error_stats["hook_errors"] or 0,
521 error_stats["test_errors"] or 0,
522 error_stats["lint_errors"] or 0,
523 error_stats["type_errors"] or 0,
524 int(job_stats["avg_duration_ms"] or 0),
525 job_stats["ai_fixes"] or 0,
526 orchestration_stats["orchestrated_jobs"] or 0,
527 float(orchestration_stats["avg_iterations"] or 0),
528 orchestration_stats["most_effective_strategy"],
529 ),
530 )
532 def get_all_time_stats(self) -> dict[str, Any]:
533 with self._get_connection() as conn:
534 job_stats = conn.execute("""
535 SELECT
536 COUNT(*) as total_jobs,
537 SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) as successful_jobs,
538 SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) as failed_jobs,
539 SUM(CASE WHEN ai_agent=1 THEN 1 ELSE 0 END) as ai_agent_jobs,
540 AVG(iterations) as avg_iterations
541 FROM jobs
542 """).fetchone()
544 error_stats = conn.execute("""
545 SELECT error_type, COUNT( * ) as count
546 FROM errors
547 GROUP BY error_type
548 """).fetchall()
550 common_errors = conn.execute("""
551 SELECT error_category, error_message, COUNT( * ) as count
552 FROM errors
553 GROUP BY error_category, error_message
554 ORDER BY count DESC
555 LIMIT 10
556 """).fetchall()
558 return {
559 "total_jobs": job_stats["total_jobs"] or 0,
560 "successful_jobs": job_stats["successful_jobs"] or 0,
561 "failed_jobs": job_stats["failed_jobs"] or 0,
562 "ai_agent_jobs": job_stats["ai_agent_jobs"] or 0,
563 "avg_iterations": float(job_stats["avg_iterations"] or 0),
564 "error_breakdown": {
565 row["error_type"]: row["count"] for row in error_stats
566 },
567 "common_errors": [dict(row) for row in common_errors],
568 }
571_metrics_collector: MetricsCollector | None = None
574def get_metrics_collector() -> MetricsCollector:
575 global _metrics_collector
576 if _metrics_collector is None:
577 _metrics_collector = MetricsCollector()
578 return _metrics_collector