|
| 1 | +"""Engine performance tracking for CodeFRAME. |
| 2 | +
|
| 3 | +Records per-run engine metrics and computes aggregate statistics |
| 4 | +for comparing engine performance (react vs plan vs external adapters). |
| 5 | +
|
| 6 | +This module is headless - no FastAPI or HTTP dependencies. |
| 7 | +""" |
| 8 | + |
| 9 | +from typing import Optional |
| 10 | + |
| 11 | +from codeframe.core.workspace import Workspace, get_db_connection, _utc_now |
| 12 | + |
| 13 | + |
| 14 | +def record_run( |
| 15 | + workspace: Workspace, |
| 16 | + run_id: str, |
| 17 | + engine: str, |
| 18 | + task_id: str, |
| 19 | + status: str, |
| 20 | + duration_ms: Optional[int] = None, |
| 21 | + tokens_used: int = 0, |
| 22 | + gates_passed: Optional[int] = None, |
| 23 | + self_corrections: int = 0, |
| 24 | +) -> None: |
| 25 | + """Record an engine run in the run_engine_log table. |
| 26 | +
|
| 27 | + After inserting, recomputes aggregate stats for the engine. |
| 28 | +
|
| 29 | + Args: |
| 30 | + workspace: Active workspace. |
| 31 | + run_id: Unique run identifier. |
| 32 | + engine: Engine name (e.g. "react", "plan"). |
| 33 | + task_id: Task that was executed. |
| 34 | + status: Final run status (COMPLETED, FAILED, BLOCKED). |
| 35 | + duration_ms: Execution duration in milliseconds. |
| 36 | + tokens_used: Total LLM tokens consumed. |
| 37 | + gates_passed: 1 if all gates passed, 0 if not, None if no gate data. |
| 38 | + self_corrections: Number of self-correction attempts. |
| 39 | + """ |
| 40 | + now = _utc_now().isoformat() |
| 41 | + |
| 42 | + conn = get_db_connection(workspace) |
| 43 | + try: |
| 44 | + conn.execute( |
| 45 | + "INSERT INTO run_engine_log " |
| 46 | + "(run_id, engine, task_id, workspace_id, status, duration_ms, " |
| 47 | + "tokens_used, gates_passed, self_corrections, created_at) " |
| 48 | + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", |
| 49 | + ( |
| 50 | + run_id, |
| 51 | + engine, |
| 52 | + task_id, |
| 53 | + workspace.id, |
| 54 | + status, |
| 55 | + duration_ms, |
| 56 | + tokens_used, |
| 57 | + gates_passed, |
| 58 | + self_corrections, |
| 59 | + now, |
| 60 | + ), |
| 61 | + ) |
| 62 | + # Recompute aggregates in the same connection to avoid TOCTOU issues |
| 63 | + _update_aggregate_stats_conn(conn, workspace.id, engine) |
| 64 | + conn.commit() |
| 65 | + finally: |
| 66 | + conn.close() |
| 67 | + |
| 68 | + |
| 69 | +def _update_aggregate_stats(workspace: Workspace, engine: str) -> None: |
| 70 | + """Recompute aggregate metrics for an engine (opens its own connection). |
| 71 | +
|
| 72 | + Convenience wrapper for external callers (e.g., data seeding). |
| 73 | + """ |
| 74 | + conn = get_db_connection(workspace) |
| 75 | + try: |
| 76 | + _update_aggregate_stats_conn(conn, workspace.id, engine) |
| 77 | + conn.commit() |
| 78 | + finally: |
| 79 | + conn.close() |
| 80 | + |
| 81 | + |
| 82 | +def _update_aggregate_stats_conn(conn, ws_id: str, engine: str) -> None: |
| 83 | + """Recompute aggregate metrics using an existing connection. |
| 84 | +
|
| 85 | + Does NOT commit — caller is responsible for committing. |
| 86 | + """ |
| 87 | + now = _utc_now().isoformat() |
| 88 | + |
| 89 | + cur = conn.cursor() |
| 90 | + |
| 91 | + # Compute all metrics in one pass where possible |
| 92 | + row = cur.execute( |
| 93 | + "SELECT " |
| 94 | + " COUNT(*), " |
| 95 | + " COUNT(CASE WHEN status = 'COMPLETED' THEN 1 END), " |
| 96 | + " COUNT(CASE WHEN status = 'FAILED' THEN 1 END), " |
| 97 | + " COUNT(CASE WHEN gates_passed = 1 THEN 1 END), " |
| 98 | + " COUNT(CASE WHEN gates_passed IS NOT NULL THEN 1 END), " |
| 99 | + " COUNT(CASE WHEN self_corrections > 0 THEN 1 END), " |
| 100 | + " AVG(CASE WHEN duration_ms IS NOT NULL THEN duration_ms END), " |
| 101 | + " SUM(tokens_used), " |
| 102 | + " SUM(CASE WHEN status = 'COMPLETED' THEN tokens_used ELSE 0 END), " |
| 103 | + " COUNT(CASE WHEN status = 'COMPLETED' THEN 1 END) " |
| 104 | + "FROM run_engine_log " |
| 105 | + "WHERE engine = ? AND workspace_id = ?", |
| 106 | + (engine, ws_id), |
| 107 | + ).fetchone() |
| 108 | + |
| 109 | + total = row[0] |
| 110 | + completed = row[1] |
| 111 | + failed = row[2] |
| 112 | + gates_pass_count = row[3] |
| 113 | + gates_total = row[4] |
| 114 | + self_corr_count = row[5] |
| 115 | + avg_duration = row[6] |
| 116 | + total_tokens = row[7] or 0 |
| 117 | + completed_tokens = row[8] or 0 |
| 118 | + completed_count = row[9] |
| 119 | + |
| 120 | + gate_pass_rate = ( |
| 121 | + 100.0 * gates_pass_count / gates_total if gates_total > 0 else 0.0 |
| 122 | + ) |
| 123 | + self_correction_rate = ( |
| 124 | + 100.0 * self_corr_count / total if total > 0 else 0.0 |
| 125 | + ) |
| 126 | + avg_tokens_per_task = ( |
| 127 | + completed_tokens / completed_count if completed_count > 0 else 0.0 |
| 128 | + ) |
| 129 | + |
| 130 | + metrics = { |
| 131 | + "tasks_attempted": float(total), |
| 132 | + "tasks_completed": float(completed), |
| 133 | + "tasks_failed": float(failed), |
| 134 | + "gate_pass_rate": round(gate_pass_rate, 2), |
| 135 | + "self_correction_rate": round(self_correction_rate, 2), |
| 136 | + "avg_duration_ms": round(avg_duration, 2) if avg_duration is not None else 0.0, |
| 137 | + "total_tokens": float(total_tokens), |
| 138 | + "avg_tokens_per_task": round(avg_tokens_per_task, 2), |
| 139 | + } |
| 140 | + |
| 141 | + for metric, value in metrics.items(): |
| 142 | + cur.execute( |
| 143 | + "INSERT OR REPLACE INTO engine_stats " |
| 144 | + "(workspace_id, engine, metric, value, updated_at) " |
| 145 | + "VALUES (?, ?, ?, ?, ?)", |
| 146 | + (ws_id, engine, metric, value, now), |
| 147 | + ) |
| 148 | + |
| 149 | + |
| 150 | +def get_engine_stats( |
| 151 | + workspace: Workspace, engine: Optional[str] = None |
| 152 | +) -> dict[str, dict[str, float]]: |
| 153 | + """Get aggregate engine statistics. |
| 154 | +
|
| 155 | + Args: |
| 156 | + workspace: Active workspace. |
| 157 | + engine: Optional engine filter. If None, returns all engines. |
| 158 | +
|
| 159 | + Returns: |
| 160 | + Dict keyed by engine name, each value is a dict of metric -> value. |
| 161 | + Empty dict if no stats exist. |
| 162 | + """ |
| 163 | + conn = get_db_connection(workspace) |
| 164 | + try: |
| 165 | + if engine is not None: |
| 166 | + rows = conn.execute( |
| 167 | + "SELECT engine, metric, value FROM engine_stats " |
| 168 | + "WHERE workspace_id = ? AND engine = ?", |
| 169 | + (workspace.id, engine), |
| 170 | + ).fetchall() |
| 171 | + else: |
| 172 | + rows = conn.execute( |
| 173 | + "SELECT engine, metric, value FROM engine_stats " |
| 174 | + "WHERE workspace_id = ?", |
| 175 | + (workspace.id,), |
| 176 | + ).fetchall() |
| 177 | + finally: |
| 178 | + conn.close() |
| 179 | + |
| 180 | + result: dict[str, dict[str, float]] = {} |
| 181 | + for eng, metric, value in rows: |
| 182 | + if eng not in result: |
| 183 | + result[eng] = {} |
| 184 | + result[eng][metric] = value |
| 185 | + |
| 186 | + return result |
| 187 | + |
| 188 | + |
| 189 | +def get_run_log( |
| 190 | + workspace: Workspace, engine: Optional[str] = None, limit: int = 100 |
| 191 | +) -> list[dict]: |
| 192 | + """Get raw per-run records from the run_engine_log table. |
| 193 | +
|
| 194 | + Args: |
| 195 | + workspace: Active workspace. |
| 196 | + engine: Optional engine filter. |
| 197 | + limit: Maximum records to return (default 100). |
| 198 | +
|
| 199 | + Returns: |
| 200 | + List of dicts, each representing a run record. |
| 201 | + Ordered by created_at DESC. |
| 202 | + """ |
| 203 | + conn = get_db_connection(workspace) |
| 204 | + try: |
| 205 | + if engine is not None: |
| 206 | + rows = conn.execute( |
| 207 | + "SELECT run_id, engine, task_id, workspace_id, status, " |
| 208 | + "duration_ms, tokens_used, gates_passed, self_corrections, " |
| 209 | + "created_at FROM run_engine_log " |
| 210 | + "WHERE workspace_id = ? AND engine = ? " |
| 211 | + "ORDER BY created_at DESC LIMIT ?", |
| 212 | + (workspace.id, engine, limit), |
| 213 | + ).fetchall() |
| 214 | + else: |
| 215 | + rows = conn.execute( |
| 216 | + "SELECT run_id, engine, task_id, workspace_id, status, " |
| 217 | + "duration_ms, tokens_used, gates_passed, self_corrections, " |
| 218 | + "created_at FROM run_engine_log " |
| 219 | + "WHERE workspace_id = ? " |
| 220 | + "ORDER BY created_at DESC LIMIT ?", |
| 221 | + (workspace.id, limit), |
| 222 | + ).fetchall() |
| 223 | + finally: |
| 224 | + conn.close() |
| 225 | + |
| 226 | + columns = [ |
| 227 | + "run_id", "engine", "task_id", "workspace_id", "status", |
| 228 | + "duration_ms", "tokens_used", "gates_passed", "self_corrections", |
| 229 | + "created_at", |
| 230 | + ] |
| 231 | + return [dict(zip(columns, row)) for row in rows] |
0 commit comments