Sdm0 commited on
Commit
7444884
Β·
verified Β·
1 Parent(s): 37646ae

Deploy ce6abfbb

Browse files
QUALITY_IMPROVEMENTS.md CHANGED
@@ -1,24 +1,26 @@
1
- # Review quality improvements
2
-
3
- Implemented changes:
4
- - Group test suggestions separately, cap low/info, and exclude them from the risk score.
5
- - Check changed-file/line overlap and derive excerpts from actual source. Source grounding does not prove semantic correctness.
6
- - Compiler claims without diagnostics are flagged for verification and excluded from the score.
7
- - Explain risk-score deductions and disclose prompt truncation, reviewed files, Fast windows, incremental scope, and reviewer status.
8
- - Withhold ungrounded findings from GitHub posting and report the withheld count.
9
- - Record owner-scoped correct/incorrect/useful feedback on completed findings in the job database.
10
- - Edit/delete/default provider controls, with browser-local persistence and last successful connection/JSON test metadata.
11
- - RAGAS metrics have individual deadlines, independent result statuses, explicit skipped unsupported metrics, and bounded hosted inputs. No lexical fallback is labeled RAGAS.
12
- - Preserve per-metric successes/failures and evaluation configuration through polling and database persistence. Diff-proxy context is disclosed.
13
- - Distinguish provider-reported cost, estimates, free-model estimates, and unknown costs. Response latency is not mislabeled TTFT.
14
- - Offline regression tool compares stored predictions against located labels with one-to-one matching; partial gold labels do not yield precision claims.
15
-
16
- Run regression matching without inference:
17
-
18
- ```
19
- python -m eval_data.offline_regression --predictions review.json --fixture eval_data/curated_located_fixture.jsonl --output eval_data/regression_report.json
20
- ```
21
-
22
- The curated initial fixture is partial. Location/category/concept matches are evaluation proxies, not proof that a finding is correct. No local models are loaded.
23
-
24
- Validation: backend and frontend regression tests plus the production frontend build. Live verification is reported separately; no improvement percentages are claimed without a controlled benchmark.
 
 
 
1
+ # Review quality improvements
2
+
3
+ Implemented changes:
4
+ - Group test suggestions separately, cap low/info, and exclude them from the risk score.
5
+ - Check changed-file/line overlap and derive excerpts from actual source. Source grounding does not prove semantic correctness.
6
+ - Compiler claims without diagnostics are flagged for verification and excluded from the score.
7
+ - Explain risk-score deductions and disclose prompt truncation, reviewed files, Fast windows, incremental scope, and reviewer status.
8
+ - Withhold ungrounded findings from GitHub posting and report the withheld count.
9
+ - Record owner-scoped correct/incorrect/useful feedback on completed findings in the job database.
10
+ - Edit/delete/default provider controls, with browser-local persistence and last successful connection/JSON test metadata.
11
+ - RAGAS metrics have individual deadlines, independent result statuses, explicit skipped unsupported metrics, and bounded hosted inputs. No lexical fallback is labeled RAGAS.
12
+ - Preserve per-metric successes/failures and evaluation configuration through polling and database persistence. Diff-proxy context is disclosed.
13
+ - Distinguish provider-reported cost, estimates, free-model estimates, and unknown costs. Response latency is not mislabeled TTFT.
14
+ - Offline regression tool compares stored predictions against located labels with one-to-one matching; partial gold labels do not yield precision claims.
15
+
16
+ Run regression matching without inference:
17
+
18
+ ```
19
+ python -m eval_data.offline_regression --predictions review.json --fixture eval_data/curated_located_fixture.jsonl --output eval_data/regression_report.json
20
+ ```
21
+
22
+ The curated initial fixture is partial. Location/category/concept matches are evaluation proxies, not proof that a finding is correct. No local models are loaded.
23
+
24
+ Validation: backend and frontend regression tests plus the production frontend build. Live verification is reported separately; no improvement percentages are claimed without a controlled benchmark.
25
+
26
+ Live verification (2026-10-21): Vercel UI and HF backend; calcom/cal.diy PR #10600 with the saved MiniMax free endpoint in Fast mode completed in 40 seconds. All three reviewers completed. Results grouped 9 test suggestions separately from 3 low-severity findings; score breakdown excluded the suggestions. Feedback saved successfully. Provider connection test returned valid JSON in 1.2 seconds; default selection survived refresh. RAGAS context precision completed (1.000, using a truncated PR-diff proxy); faithfulness returned a provider connection error and the UI reported partial evaluation. This run is workflow evidence, not proof of finding correctness or retrieval accuracy.
api.py CHANGED
@@ -1,637 +1,637 @@
1
- """Small HTTP boundary for the React client.
2
-
3
- The review engine remains in the existing LangGraph modules. This service only
4
- owns job lifecycle and approval state; production deployments should replace
5
- the process-local registry with a durable store and queue.
6
- """
7
- from __future__ import annotations
8
-
9
- import os
10
- import hashlib
11
- import time
12
- from pathlib import Path
13
- import json
14
- import secrets
15
- import sqlite3
16
- import threading
17
- import uuid
18
- import requests
19
- from concurrent.futures import ThreadPoolExecutor
20
- from datetime import datetime, timezone
21
- from typing import Any, Literal
22
-
23
- from fastapi import FastAPI, Header, HTTPException, Request
24
- from fastapi.responses import RedirectResponse
25
- from fastapi.middleware.cors import CORSMiddleware
26
- from langgraph.types import Command
27
- from pydantic import BaseModel, Field
28
-
29
- from app import DB_PATH, _build_and_stream, _normalize_endpoint_name, _ragas_tasks, _ragas_lock, _spawn_ragas_background
30
- from graph import build_graph
31
- from observability import TokenCostCallback, flush_langfuse, get_langfuse_handler
32
- from state import Finding, Verdict
33
- from endpoints import register_endpoint, unregister_endpoint
34
-
35
- app = FastAPI(title="OpenCodeReview API", version="0.1.0")
36
- allowed_origins = [item.strip() for item in os.getenv("OCR_ALLOWED_ORIGINS", "http://localhost:5173").split(",") if item.strip()]
37
- app.add_middleware(CORSMiddleware, allow_origins=allowed_origins, allow_methods=["GET", "POST"], allow_headers=["*"], allow_credentials=True)
38
-
39
- _jobs: dict[str, dict[str, Any]] = {}
40
- _lock = threading.Lock()
41
- _executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
42
- _rate_lock = threading.Lock()
43
- _rate_windows: dict[str, list[float]] = {}
44
- _oauth_states: set[str] = set()
45
- _sessions: dict[str, dict[str, Any]] = {}
46
-
47
- def _rate_limit(request: Request) -> None:
48
- limit = int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0)
49
- if limit <= 0:
50
- return
51
- now = datetime.now(timezone.utc).timestamp()
52
- forwarded = request.headers.get("x-forwarded-for") or request.headers.get("x-real-ip")
53
- key = (forwarded.split(",", 1)[0].strip() if forwarded else None) or "global"
54
- with _rate_lock:
55
- window = [stamp for stamp in _rate_windows.get(key, []) if now - stamp < 60]
56
- if len(window) >= limit:
57
- raise HTTPException(status_code=429, detail="Rate limit exceeded")
58
- window.append(now)
59
- _rate_windows[key] = window
60
-
61
-
62
- def _postgres_connect():
63
- """Return a Supabase Postgres connection when configured, else None."""
64
- url = os.getenv("SUPABASE_DB_URL", "").strip()
65
- if not url:
66
- return None
67
- try:
68
- import psycopg
69
- return psycopg.connect(url)
70
- except Exception:
71
- return None
72
-
73
- def _init_jobs() -> None:
74
- pg = _postgres_connect()
75
- if pg is not None:
76
- with pg:
77
- with pg.cursor() as cur:
78
- cur.execute("""create table if not exists public.review_jobs (
79
- id uuid primary key, repo text not null, pr_number integer not null,
80
- endpoint text, status text not null, payload jsonb not null,
81
- created_at timestamptz not null default now(), updated_at timestamptz not null default now())""")
82
- cur.execute("create index if not exists review_jobs_status_idx on public.review_jobs (status)")
83
- pg.close()
84
- return
85
- with sqlite3.connect(DB_PATH) as conn:
86
- conn.execute("CREATE TABLE IF NOT EXISTS review_jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
87
- conn.commit()
88
-
89
- _init_jobs()
90
-
91
- def _save_job(job: dict[str, Any]) -> None:
92
- payload = {k: v for k, v in job.items() if k not in {"future", "ragas_inputs"}}
93
- if "config" in payload:
94
- payload["config"] = {"configurable": payload["config"].get("configurable", {})}
95
- pg = _postgres_connect()
96
- if pg is not None:
97
- with pg:
98
- with pg.cursor() as cur:
99
- cur.execute("""insert into public.review_jobs (id, repo, pr_number, endpoint, status, payload, updated_at)
100
- values (%s, %s, %s, %s, %s, %s::jsonb, now())
101
- on conflict (id) do update set repo=excluded.repo, pr_number=excluded.pr_number,
102
- endpoint=excluded.endpoint, status=excluded.status, payload=excluded.payload, updated_at=now()""",
103
- (job["id"], job["repo"], job["pr_number"], job.get("endpoint"), job["status"], json.dumps(payload, default=str)))
104
- pg.close()
105
- return
106
- with sqlite3.connect(DB_PATH) as conn:
107
- conn.execute("INSERT OR REPLACE INTO review_jobs (id, payload) VALUES (?, ?)", (job["id"], json.dumps(payload, default=str)))
108
- conn.commit()
109
-
110
- def _load_job(job_id: str) -> dict[str, Any] | None:
111
- pg = _postgres_connect()
112
- if pg is not None:
113
- with pg.cursor() as cur:
114
- cur.execute("select payload from public.review_jobs where id = %s", (job_id,))
115
- row = cur.fetchone()
116
- pg.close()
117
- if not row:
118
- return None
119
- return json.loads(row[0]) if isinstance(row[0], str) else row[0]
120
- with sqlite3.connect(DB_PATH) as conn:
121
- row = conn.execute("SELECT payload FROM review_jobs WHERE id = ?", (job_id,)).fetchone()
122
- return json.loads(row[0]) if row else None
123
-
124
- def _load_jobs() -> list[dict[str, Any]]:
125
- pg = _postgres_connect()
126
- if pg is not None:
127
- with pg.cursor() as cur:
128
- cur.execute("select payload from public.review_jobs")
129
- rows = cur.fetchall()
130
- pg.close()
131
- return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
132
- with sqlite3.connect(DB_PATH) as conn:
133
- rows = conn.execute("SELECT payload FROM review_jobs").fetchall()
134
- return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
135
-
136
-
137
- class ReviewRequest(BaseModel):
138
- repo: str = Field(pattern=r"^[\w.-]+/[\w.-]+$")
139
- pr_number: int = Field(gt=0)
140
- endpoint: str | None = None
141
- provider: str | None = Field(default=None, pattern=r"^(openai|anthropic|google)$")
142
- model: str | None = None
143
- api_key: str | None = None
144
- base_url: str | None = None
145
- review_mode: Literal["fast", "thorough"] = "thorough"
146
- baseline_sha: str | None = Field(default=None, pattern=r"^[0-9a-fA-F]{40}$")
147
-
148
-
149
- class DecisionRequest(BaseModel):
150
- action: Literal["approve", "reject"]
151
-
152
-
153
- class FindingFeedbackRequest(BaseModel):
154
- finding_index: int = Field(ge=0)
155
- label: Literal['correct', 'incorrect', 'useful']
156
-
157
-
158
- def _authorize(token: str | None) -> None:
159
- expected = os.getenv("OCR_API_KEY", "").strip()
160
- # Authentication is opt-in for local development, but deployments can
161
- # require it explicitly. Never silently treat a missing production key
162
- # as authenticated.
163
- require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
164
- if require_auth and not expected:
165
- raise HTTPException(status_code=503, detail="API authentication is not configured")
166
- if expected and (not token or not secrets.compare_digest(token, expected)):
167
- raise HTTPException(status_code=401, detail="Invalid API key")
168
-
169
- def _authorize_request(token: str | None, request: Request) -> None:
170
- if _session(request):
171
- return
172
- _authorize(token)
173
-
174
- def _session(request: Request) -> dict[str, Any] | None:
175
- sid = request.cookies.get("ocr_session")
176
- return _sessions.get(sid) if sid else None
177
-
178
- @app.get("/api/auth/github/start")
179
- def github_login() -> RedirectResponse:
180
- client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
181
- if not client_id:
182
- raise HTTPException(status_code=503, detail="GitHub OAuth is not configured")
183
- state = secrets.token_urlsafe(32)
184
- _oauth_states.add(state)
185
- callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
186
- url = "https://github.com/login/oauth/authorize?" + requests.compat.urlencode({"client_id": client_id, "redirect_uri": callback, "scope": "read:user user:email repo", "state": state})
187
- return RedirectResponse(url)
188
-
189
- @app.get("/api/auth/github/callback")
190
- def github_callback(code: str, state: str, response: Request) -> RedirectResponse:
191
- if state not in _oauth_states:
192
- raise HTTPException(status_code=400, detail="Invalid OAuth state")
193
- _oauth_states.discard(state)
194
- client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
195
- client_secret = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "").strip()
196
- callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
197
- token_resp = requests.post("https://github.com/login/oauth/access_token", data={"client_id": client_id, "client_secret": client_secret, "code": code, "redirect_uri": callback}, headers={"Accept": "application/json"}, timeout=20)
198
- token_resp.raise_for_status()
199
- access_token = token_resp.json().get("access_token")
200
- if not access_token:
201
- raise HTTPException(status_code=502, detail="GitHub did not return an access token")
202
- user_resp = requests.get("https://api.github.com/user", headers={"Authorization": f"Bearer {access_token}", "Accept": "application/vnd.github+json"}, timeout=20)
203
- user_resp.raise_for_status()
204
- user = user_resp.json()
205
- sid = secrets.token_urlsafe(32)
206
- _sessions[sid] = {"token": access_token, "github_id": user.get("id"), "login": user.get("login")}
207
- frontend = os.getenv("OCR_FRONTEND_URL", allowed_origins[0] if allowed_origins else "http://localhost:5173")
208
- out = RedirectResponse(frontend)
209
- out.set_cookie("ocr_session", sid, httponly=True, secure=frontend.startswith("https://"), samesite="lax", max_age=86400)
210
- return out
211
-
212
- @app.get("/api/auth/me")
213
- def github_me(request: Request) -> dict[str, Any]:
214
- session = _session(request)
215
- if not session:
216
- raise HTTPException(status_code=401, detail="Not authenticated")
217
- return {"github_id": session["github_id"], "login": session["login"]}
218
-
219
- @app.post("/api/auth/logout")
220
- def github_logout(request: Request) -> dict[str, str]:
221
- sid = request.cookies.get("ocr_session")
222
- if sid:
223
- _sessions.pop(sid, None)
224
- return {"status": "logged_out"}
225
-
226
-
227
- def _public_job(job: dict[str, Any]) -> dict[str, Any]:
228
- result = {key: value for key, value in job.items() if key not in {"config", "future", "request_fingerprint", "owner_id", "ragas_inputs"}}
229
- now = time.time()
230
- result["elapsed_seconds"] = round(max(0, now - job.get("started_timestamp", now)), 1) if job.get("status") in {"processing", "queued"} else job.get("elapsed_seconds", 0)
231
- if job.get("status") == "queued":
232
- result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
233
- return result
234
-
235
- def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
236
- result = _public_job(job)
237
- task_id = result.get("ragas_task_id")
238
- with _ragas_lock:
239
- task = _ragas_tasks.get(task_id) if task_id else None
240
- def finish():
241
- metrics = (task or {}).get('metrics') or job.get('ragas_metrics') or {}
242
- evaluation = (task or {}).get('evaluation') or job.get('ragas_evaluation') or {}
243
- result.setdefault('ragas', {}).update(metrics=metrics, evaluation=evaluation)
244
- if metrics and result['ragas'].get('scores') and any(m.get('status') != 'completed' for m in metrics.values()):
245
- result['ragas']['status'] = 'partial'
246
- if metrics != job.get('ragas_metrics', {}) or evaluation != job.get('ragas_evaluation', {}):
247
- with _lock:
248
- live = _jobs.get(job.get('id'))
249
- if live is not None:
250
- live.update(ragas_metrics=metrics, ragas_evaluation=evaluation)
251
- _save_job(live)
252
- return result
253
- if not task_id:
254
- result["ragas"] = {
255
- "status": "skipped",
256
- "scores": result.get("ragas_scores") or {},
257
- "reason": "Review incomplete; scoring was not started" if result.get("status") == "incomplete" else "No retrieval context was available for RAGAS evaluation",
258
- }
259
- else:
260
- if job.get("ragas_status") in {"failed", "unavailable", "completed_no_scores"}:
261
- result["ragas"] = {
262
- "status": job["ragas_status"],
263
- "scores": job.get("ragas_scores") or {},
264
- "error": job.get("ragas_error"),
265
- }
266
- return finish()
267
- with _ragas_lock:
268
- task = _ragas_tasks.get(task_id)
269
- if not task:
270
- # Task registries are process-local. A restart invalidates an
271
- # in-flight task instead of making the client poll forever.
272
- if result.get("ragas_scores"):
273
- result["ragas"] = {"status": "completed", "scores": result["ragas_scores"]}
274
- else:
275
- result["ragas"] = {"status": "unavailable", "error": "RAGAS task was lost during process restart"}
276
- with _lock:
277
- live = _jobs.get(job.get("id"))
278
- if live is not None:
279
- live["ragas_status"] = "unavailable"
280
- live["ragas_error"] = result["ragas"]["error"]
281
- _save_job(live)
282
- elif not task.get("done"):
283
- timeout = float(task.get("timeout_seconds") or os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90"))
284
- started = float(task.get("started", 0) or 0)
285
- if started and datetime.now(timezone.utc).timestamp() - started > timeout:
286
- result["ragas"] = {"status": "failed", "error": f"RAGAS exceeded {int(timeout)} second timeout"}
287
- with _lock:
288
- live = _jobs.get(job.get("id"))
289
- if live is not None:
290
- live["ragas_status"] = "failed"
291
- live["ragas_error"] = result["ragas"]["error"]
292
- _save_job(live)
293
- else:
294
- result["ragas"] = {"status": "pending"}
295
- elif task.get("error"):
296
- result["ragas"] = {"status": "failed", "error": task.get("error")}
297
- with _lock:
298
- live = _jobs.get(job.get("id"))
299
- if live is not None:
300
- live["ragas_status"] = "failed"
301
- live["ragas_error"] = task.get("error")
302
- _save_job(live)
303
- else:
304
- scores = task.get("scores") or {}
305
- if scores:
306
- result["ragas"] = {"status": "completed", "scores": scores}
307
- if not job.get("ragas_scores"):
308
- with _lock:
309
- live = _jobs.get(job.get("id"))
310
- if live is not None:
311
- live["ragas_scores"] = scores
312
- live["ragas_status"] = "completed"
313
- _save_job(live)
314
- else:
315
- result["ragas"] = {"status": "completed_no_scores", "scores": {}, "error": "RAGAS completed without metric values"}
316
- with _lock:
317
- live = _jobs.get(job.get("id"))
318
- if live is not None:
319
- live["ragas_status"] = "completed_no_scores"
320
- live["ragas_error"] = result["ragas"]["error"]
321
- _save_job(live)
322
- return finish()
323
-
324
-
325
- def _run_job(job_id: str, request: ReviewRequest) -> None:
326
- with _lock:
327
- if _jobs.get(job_id, {}).get("status") == "cancelled":
328
- return
329
- if job_id in _jobs:
330
- _jobs[job_id].update(status="processing", started_timestamp=time.time(), progress={"stage": "ingestion", "completed_stages": []})
331
- _save_job(_jobs[job_id])
332
- try:
333
- ephemeral_endpoint = None
334
- endpoint_name = _normalize_endpoint_name(request.endpoint)
335
- if request.api_key:
336
- if not request.provider or not request.model:
337
- raise ValueError("provider and model are required when supplying a user API key")
338
- ephemeral_endpoint = f"user-{job_id}"
339
- register_endpoint(ephemeral_endpoint, request.provider, request.api_key, request.base_url, request.model)
340
- endpoint_name = ephemeral_endpoint
341
- def save_ragas(scores: dict, error: str | None) -> None:
342
- with _lock:
343
- live = _jobs.get(job_id)
344
- if live is None:
345
- return
346
- live["ragas_scores"] = scores or None
347
- live["ragas_status"] = "failed" if error else ("completed" if scores else "completed_no_scores")
348
- live["ragas_error"] = error
349
- _save_job(live)
350
-
351
- def progress(stage: str, elapsed: float, update: dict | None = None) -> None:
352
- with _lock:
353
- live = _jobs[job_id]
354
- if live.get("status") == "cancelled":
355
- raise RuntimeError("Review cancelled")
356
- completed = live.setdefault("progress", {}).setdefault("completed_stages", [])
357
- if stage not in completed:
358
- completed.append(stage)
359
- live["progress"]["stage"] = stage
360
- live.setdefault("stage_timings", {})[stage] = round(elapsed, 2)
361
- if isinstance(update, dict):
362
- stages = update.get("review_stages", [])
363
- if isinstance(stages, list):
364
- live.setdefault("review_stages", []).extend(stages)
365
- for key in ("findings",):
366
- for finding in update.get(key, []) or []:
367
- if hasattr(finding, "model_dump"):
368
- finding = finding.model_dump(mode="json")
369
- if isinstance(finding, dict):
370
- live.setdefault("findings", []).append(finding)
371
- _save_job(live)
372
-
373
- state, config, cost, ragas, ragas_inputs = _build_and_stream(
374
- request.repo,
375
- request.pr_number,
376
- endpoint_name,
377
- ragas_background=True,
378
- ragas_result_callback=save_ragas,
379
- progress_callback=progress,
380
- review_mode=request.review_mode,
381
- baseline_sha=request.baseline_sha,
382
- )
383
- actual_head = state.values.get("head_sha")
384
- verdict: Verdict | None = state.values.get("verdict")
385
- findings: list[Finding] = state.values.get("final_findings", [])
386
- with _lock:
387
- if _jobs[job_id].get("status") == "cancelled":
388
- return
389
- if actual_head and _jobs[job_id].get("head_sha") != actual_head:
390
- # The PR moved between metadata lookup and ingestion. The result
391
- # can still be viewed, but must not satisfy the old cache key.
392
- _jobs[job_id]["request_fingerprint"] = None
393
- _jobs[job_id]["head_sha"] = actual_head
394
- stages = state.values.get("review_stages", [])
395
- incomplete = bool(verdict and verdict.recommendation == "incomplete")
396
- _jobs[job_id].update(review_coverage=state.values.get("review_coverage", {}), review_stages=stages, elapsed_seconds=round(time.time() - _jobs[job_id]["started_timestamp"], 2), status="incomplete" if incomplete else "awaiting_approval", config=config, verdict=verdict.model_dump(mode="json") if verdict else None, findings=[item.model_dump(mode="json") for item in findings], cost=cost, cost_details=config.get("metadata", {}).get("cost_details"), ragas_task_id=ragas if isinstance(ragas, str) else None, ragas_scores=ragas if isinstance(ragas, dict) else None, ragas_inputs=None)
397
- _save_job(_jobs[job_id])
398
- except Exception as exc:
399
- with _lock:
400
- if _jobs[job_id].get("status") != "cancelled":
401
- _jobs[job_id].update(status="failed", error=str(exc)[:500])
402
- _save_job(_jobs[job_id])
403
- finally:
404
- if 'ephemeral_endpoint' in locals() and ephemeral_endpoint:
405
- unregister_endpoint(ephemeral_endpoint)
406
-
407
-
408
- def _hydrate_jobs() -> None:
409
- """Restore persisted jobs after a process restart and resume interrupted work."""
410
- for persisted in _load_jobs():
411
- # Evaluation inputs may include an in-memory endpoint object. Never
412
- # retain or expose that snapshot: it can contain a user's provider key.
413
- if "ragas_inputs" in persisted:
414
- persisted.pop("ragas_inputs", None)
415
- _save_job(persisted)
416
- job_id = persisted.get("id")
417
- if not job_id:
418
- continue
419
- status = persisted.get("status")
420
- _jobs[job_id] = persisted
421
- if persisted.get("ragas_task_id") and not persisted.get("ragas_status"):
422
- persisted.update(ragas_status="unavailable", ragas_error="Evaluation interrupted by restart; it was not automatically replayed.")
423
- _save_job(persisted)
424
- if status in {"queued", "processing"} and persisted.get("custom_provider"):
425
- persisted.update(status="failed", error="Provider credentials were not persisted; resubmit this review after restart.")
426
- _save_job(persisted)
427
- continue
428
- if status in {"queued", "processing", "processing_decision"}:
429
- # Decision processing cannot be safely replayed without an explicit
430
- # user action; review execution can be resumed idempotently.
431
- if status == "processing_decision":
432
- _jobs[job_id]["status"] = "awaiting_approval"
433
- _save_job(_jobs[job_id])
434
- continue
435
- try:
436
- request = ReviewRequest(repo=persisted["repo"], pr_number=int(persisted["pr_number"]), endpoint=persisted.get("endpoint"))
437
- except Exception:
438
- _jobs[job_id].update(status="failed", error="Persisted job request is invalid")
439
- _save_job(_jobs[job_id])
440
- continue
441
- _jobs[job_id]["status"] = "queued"
442
- _save_job(_jobs[job_id])
443
- _jobs[job_id]["future"] = _executor.submit(_run_job, job_id, request)
444
-
445
-
446
- _hydrate_jobs()
447
-
448
-
449
- @app.get("/api/health")
450
- def health() -> dict[str, Any]:
451
- provider_configured = any(
452
- os.getenv(name, "").strip()
453
- for name in ("GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
454
- )
455
- require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
456
- persistence = "local_default_path"
457
- if os.getenv("SUPABASE_DB_URL"):
458
- probe = _postgres_connect()
459
- if probe is not None:
460
- probe.close()
461
- persistence = "supabase_postgres"
462
- else:
463
- persistence = "supabase_configured_unreachable"
464
- elif os.getenv("OPENCODEREVIEW_DB_PATH"):
465
- persistence = "configured_path"
466
- return {
467
- "status": "ok",
468
- "inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
469
- "authentication": "required" if require_auth else "optional",
470
- "rate_limit_per_minute": int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0),
471
- "persistence": persistence,
472
- "local_embeddings": os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower()
473
- in {"1", "true", "yes", "on"},
474
- }
475
-
476
-
477
- @app.post("/api/reviews", status_code=202)
478
- def create_review(request: ReviewRequest, http_request: Request, x_api_key: str | None = Header(default=None), idempotency_key: str | None = Header(default=None, alias="Idempotency-Key")) -> dict[str, Any]:
479
- _authorize_request(x_api_key, http_request)
480
- _rate_limit(http_request)
481
- owner = str((_session(http_request) or {}).get("github_id") or "api-key")
482
- material = request.model_dump()
483
- head_sha = base_sha = None
484
- try:
485
- token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
486
- headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
487
- if token:
488
- headers["Authorization"] = f"Bearer {token}"
489
- response = requests.get(f"https://api.github.com/repos/{request.repo}/pulls/{request.pr_number}", headers=headers, timeout=6)
490
- response.raise_for_status()
491
- pull = response.json()
492
- head_sha, base_sha = pull["head"]["sha"], pull["base"]["sha"]
493
- except (requests.RequestException, KeyError, ValueError):
494
- pass # Active deduplication still works if GitHub metadata is unavailable.
495
- prompt_hash = hashlib.sha256()
496
- for source in sorted(Path(__file__).parent.joinpath("prompts").glob("*.txt")):
497
- prompt_hash.update(source.read_bytes())
498
- for source in sorted(Path(__file__).parent.joinpath("nodes").glob("*.py")):
499
- prompt_hash.update(source.read_bytes())
500
- material.update(head_sha=head_sha, base_sha=base_sha, pipeline_version=prompt_hash.hexdigest())
501
- fingerprint = hashlib.sha256(json.dumps({"owner": owner, "request": material}, sort_keys=True).encode()).hexdigest()
502
- # Reuse completed previews only for an identical immutable diff and configuration.
503
- with _lock:
504
- existing = next((item for item in _jobs.values() if item.get("owner_id") == owner and item.get("request_fingerprint") == fingerprint and (item.get("status") in {"queued", "processing"} or (head_sha and base_sha and item.get("status") == "awaiting_approval" and time.time() - item.get("started_timestamp", 0) < 900))), None)
505
- if existing is None:
506
- job_id = str(uuid.uuid4())
507
- job = {"id": job_id, "repo": request.repo, "pr_number": request.pr_number, "endpoint": request.endpoint, "review_mode": request.review_mode, "baseline_sha": request.baseline_sha, "custom_provider": bool(request.api_key), "head_sha": head_sha, "base_sha": base_sha, "owner_id": owner, "request_fingerprint": fingerprint, "status": "queued", "created_at": datetime.now(timezone.utc).isoformat()}
508
- _jobs[job_id] = job
509
- _save_job(job)
510
- else:
511
- job = existing
512
- if existing is not None:
513
- return {**_with_ragas(job), "reused": True}
514
- job["future"] = _executor.submit(_run_job, job_id, request)
515
- return _with_ragas(job)
516
-
517
-
518
- @app.post("/api/reviews/{job_id}/cancel")
519
- def cancel_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
520
- _authorize_request(x_api_key, request)
521
- owner = str((_session(request) or {}).get("github_id") or "api-key")
522
- with _lock:
523
- job = _jobs.get(job_id)
524
- if not job or job.get("owner_id", "api-key") != owner:
525
- raise HTTPException(status_code=404, detail="Review not found")
526
- if job.get("status") not in {"queued", "processing"}:
527
- raise HTTPException(status_code=409, detail="Only queued or processing reviews can be cancelled")
528
- future = job.get("future")
529
- if future:
530
- future.cancel()
531
- job.update(status="cancelled", cancellation_note="Running calls finish within their timeout; no results will be posted.")
532
- _save_job(job)
533
- return _public_job(job)
534
-
535
-
536
- @app.get("/api/reviews/{job_id}")
537
- def get_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
538
- # API-key authorization remains supported for polling; OAuth callers use the cookie path.
539
- _authorize_request(x_api_key, request)
540
- with _lock:
541
- job = _jobs.get(job_id)
542
- if not job:
543
- job = _load_job(job_id)
544
- owner = str((_session(request) or {}).get("github_id") or "api-key")
545
- if not job or job.get("owner_id", "api-key") != owner:
546
- raise HTTPException(status_code=404, detail="Review not found")
547
- return _with_ragas(job)
548
-
549
-
550
- @app.post('/api/reviews/{job_id}/feedback')
551
- def finding_feedback(job_id: str, payload: FindingFeedbackRequest, request: Request,
552
- x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
553
- _authorize_request(x_api_key, request)
554
- _rate_limit(request)
555
- owner = str((_session(request) or {}).get('github_id') or 'api-key')
556
- with _lock:
557
- job = _jobs.get(job_id) or _load_job(job_id)
558
- if not job or job.get('owner_id', 'api-key') != owner:
559
- raise HTTPException(status_code=404, detail='Review not found')
560
- if job.get('status') not in {'awaiting_approval', 'incomplete', 'posted', 'partially_posted', 'rejected', 'post_failed'}:
561
- raise HTTPException(status_code=409, detail='Wait until the review finishes before giving feedback')
562
- if payload.finding_index >= len(job.get('findings') or []):
563
- raise HTTPException(status_code=422, detail='Finding does not exist')
564
- feedback = dict(job.get('feedback') or {})
565
- feedback[str(payload.finding_index)] = payload.label
566
- job['feedback'] = feedback
567
- job['feedback_updated_at'] = datetime.now(timezone.utc).isoformat()
568
- _jobs[job_id] = job
569
- _save_job(job)
570
- return {'feedback': feedback}
571
-
572
-
573
- @app.post("/api/reviews/{job_id}/decision")
574
- def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
575
- _authorize_request(x_api_key, http_request)
576
- _rate_limit(http_request)
577
- with _lock:
578
- preview = _jobs.get(job_id) or _load_job(job_id)
579
- owner = str((_session(http_request) or {}).get("github_id") or "api-key")
580
- if not preview or preview.get("owner_id", "api-key") != owner:
581
- raise HTTPException(status_code=404, detail="Review not found")
582
- if request.action == "approve" and preview.get("baseline_sha"):
583
- raise HTTPException(status_code=409, detail="Incremental reviews are preview-only. Run a full review before posting.")
584
- if preview and request.action == "approve" and preview.get("head_sha"):
585
- headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
586
- token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
587
- if token:
588
- headers["Authorization"] = f"Bearer {token}"
589
- try:
590
- response = requests.get(f"https://api.github.com/repos/{preview['repo']}/pulls/{preview['pr_number']}", headers=headers, timeout=6)
591
- response.raise_for_status()
592
- current = response.json()
593
- if current["head"]["sha"] != preview["head_sha"] or current["base"]["sha"] != preview.get("base_sha"):
594
- raise HTTPException(status_code=409, detail="PR changed since this review; start a new review before posting.")
595
- except (requests.RequestException, KeyError, ValueError) as exc:
596
- raise HTTPException(status_code=503, detail="Cannot verify the current PR commit; retry before posting.") from exc
597
- with _lock:
598
- job = _jobs.get(job_id)
599
- if not job:
600
- job = _load_job(job_id)
601
- if not job:
602
- raise HTTPException(status_code=404, detail="Review not found")
603
- if job.get("status") != "awaiting_approval":
604
- raise HTTPException(status_code=409, detail="Review is not awaiting approval")
605
- config = job["config"]
606
- job["status"] = "processing_decision"
607
- _save_job(job)
608
- if request.action == "reject":
609
- with _lock:
610
- job.update(status="rejected", decision="reject")
611
- _save_job(job)
612
- return _public_job(job)
613
- graph = build_graph(DB_PATH)
614
- try:
615
- callbacks = [TokenCostCallback()]
616
- handler = get_langfuse_handler()
617
- if handler:
618
- callbacks.append(handler)
619
- config = dict(config)
620
- config["callbacks"] = callbacks
621
- result = graph.invoke(Command(resume={"action": "approve"}), config)
622
- posting_result = result.get("posting_result") if isinstance(result, dict) else None
623
- final_status = (posting_result or {}).get("status", "posted")
624
- with _lock:
625
- job.update(status=final_status, decision="approve", posting_result=posting_result)
626
- _save_job(job)
627
- return _public_job(job)
628
- except Exception as exc:
629
- with _lock:
630
- job.update(status="failed", error=str(exc)[:500])
631
- _save_job(job)
632
- raise HTTPException(status_code=500, detail="Decision processing failed") from exc
633
- finally:
634
- conn = getattr(graph, "_opencodereview_conn", None)
635
- if conn:
636
- conn.close()
637
- flush_langfuse()
 
1
+ """Small HTTP boundary for the React client.
2
+
3
+ The review engine remains in the existing LangGraph modules. This service only
4
+ owns job lifecycle and approval state; production deployments should replace
5
+ the process-local registry with a durable store and queue.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import hashlib
11
+ import time
12
+ from pathlib import Path
13
+ import json
14
+ import secrets
15
+ import sqlite3
16
+ import threading
17
+ import uuid
18
+ import requests
19
+ from concurrent.futures import ThreadPoolExecutor
20
+ from datetime import datetime, timezone
21
+ from typing import Any, Literal
22
+
23
+ from fastapi import FastAPI, Header, HTTPException, Request
24
+ from fastapi.responses import RedirectResponse
25
+ from fastapi.middleware.cors import CORSMiddleware
26
+ from langgraph.types import Command
27
+ from pydantic import BaseModel, Field
28
+
29
+ from app import DB_PATH, _build_and_stream, _normalize_endpoint_name, _ragas_tasks, _ragas_lock, _spawn_ragas_background
30
+ from graph import build_graph
31
+ from observability import TokenCostCallback, flush_langfuse, get_langfuse_handler
32
+ from state import Finding, Verdict
33
+ from endpoints import register_endpoint, unregister_endpoint
34
+
35
+ app = FastAPI(title="OpenCodeReview API", version="0.1.0")
36
+ allowed_origins = [item.strip() for item in os.getenv("OCR_ALLOWED_ORIGINS", "http://localhost:5173").split(",") if item.strip()]
37
+ app.add_middleware(CORSMiddleware, allow_origins=allowed_origins, allow_methods=["GET", "POST"], allow_headers=["*"], allow_credentials=True)
38
+
39
+ _jobs: dict[str, dict[str, Any]] = {}
40
+ _lock = threading.Lock()
41
+ _executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
42
+ _rate_lock = threading.Lock()
43
+ _rate_windows: dict[str, list[float]] = {}
44
+ _oauth_states: set[str] = set()
45
+ _sessions: dict[str, dict[str, Any]] = {}
46
+
47
+ def _rate_limit(request: Request) -> None:
48
+ limit = int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0)
49
+ if limit <= 0:
50
+ return
51
+ now = datetime.now(timezone.utc).timestamp()
52
+ forwarded = request.headers.get("x-forwarded-for") or request.headers.get("x-real-ip")
53
+ key = (forwarded.split(",", 1)[0].strip() if forwarded else None) or "global"
54
+ with _rate_lock:
55
+ window = [stamp for stamp in _rate_windows.get(key, []) if now - stamp < 60]
56
+ if len(window) >= limit:
57
+ raise HTTPException(status_code=429, detail="Rate limit exceeded")
58
+ window.append(now)
59
+ _rate_windows[key] = window
60
+
61
+
62
+ def _postgres_connect():
63
+ """Return a Supabase Postgres connection when configured, else None."""
64
+ url = os.getenv("SUPABASE_DB_URL", "").strip()
65
+ if not url:
66
+ return None
67
+ try:
68
+ import psycopg
69
+ return psycopg.connect(url)
70
+ except Exception:
71
+ return None
72
+
73
+ def _init_jobs() -> None:
74
+ pg = _postgres_connect()
75
+ if pg is not None:
76
+ with pg:
77
+ with pg.cursor() as cur:
78
+ cur.execute("""create table if not exists public.review_jobs (
79
+ id uuid primary key, repo text not null, pr_number integer not null,
80
+ endpoint text, status text not null, payload jsonb not null,
81
+ created_at timestamptz not null default now(), updated_at timestamptz not null default now())""")
82
+ cur.execute("create index if not exists review_jobs_status_idx on public.review_jobs (status)")
83
+ pg.close()
84
+ return
85
+ with sqlite3.connect(DB_PATH) as conn:
86
+ conn.execute("CREATE TABLE IF NOT EXISTS review_jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
87
+ conn.commit()
88
+
89
+ _init_jobs()
90
+
91
+ def _save_job(job: dict[str, Any]) -> None:
92
+ payload = {k: v for k, v in job.items() if k not in {"future", "ragas_inputs"}}
93
+ if "config" in payload:
94
+ payload["config"] = {"configurable": payload["config"].get("configurable", {})}
95
+ pg = _postgres_connect()
96
+ if pg is not None:
97
+ with pg:
98
+ with pg.cursor() as cur:
99
+ cur.execute("""insert into public.review_jobs (id, repo, pr_number, endpoint, status, payload, updated_at)
100
+ values (%s, %s, %s, %s, %s, %s::jsonb, now())
101
+ on conflict (id) do update set repo=excluded.repo, pr_number=excluded.pr_number,
102
+ endpoint=excluded.endpoint, status=excluded.status, payload=excluded.payload, updated_at=now()""",
103
+ (job["id"], job["repo"], job["pr_number"], job.get("endpoint"), job["status"], json.dumps(payload, default=str)))
104
+ pg.close()
105
+ return
106
+ with sqlite3.connect(DB_PATH) as conn:
107
+ conn.execute("INSERT OR REPLACE INTO review_jobs (id, payload) VALUES (?, ?)", (job["id"], json.dumps(payload, default=str)))
108
+ conn.commit()
109
+
110
+ def _load_job(job_id: str) -> dict[str, Any] | None:
111
+ pg = _postgres_connect()
112
+ if pg is not None:
113
+ with pg.cursor() as cur:
114
+ cur.execute("select payload from public.review_jobs where id = %s", (job_id,))
115
+ row = cur.fetchone()
116
+ pg.close()
117
+ if not row:
118
+ return None
119
+ return json.loads(row[0]) if isinstance(row[0], str) else row[0]
120
+ with sqlite3.connect(DB_PATH) as conn:
121
+ row = conn.execute("SELECT payload FROM review_jobs WHERE id = ?", (job_id,)).fetchone()
122
+ return json.loads(row[0]) if row else None
123
+
124
+ def _load_jobs() -> list[dict[str, Any]]:
125
+ pg = _postgres_connect()
126
+ if pg is not None:
127
+ with pg.cursor() as cur:
128
+ cur.execute("select payload from public.review_jobs")
129
+ rows = cur.fetchall()
130
+ pg.close()
131
+ return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
132
+ with sqlite3.connect(DB_PATH) as conn:
133
+ rows = conn.execute("SELECT payload FROM review_jobs").fetchall()
134
+ return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
135
+
136
+
137
+ class ReviewRequest(BaseModel):
138
+ repo: str = Field(pattern=r"^[\w.-]+/[\w.-]+$")
139
+ pr_number: int = Field(gt=0)
140
+ endpoint: str | None = None
141
+ provider: str | None = Field(default=None, pattern=r"^(openai|anthropic|google)$")
142
+ model: str | None = None
143
+ api_key: str | None = None
144
+ base_url: str | None = None
145
+ review_mode: Literal["fast", "thorough"] = "thorough"
146
+ baseline_sha: str | None = Field(default=None, pattern=r"^[0-9a-fA-F]{40}$")
147
+
148
+
149
+ class DecisionRequest(BaseModel):
150
+ action: Literal["approve", "reject"]
151
+
152
+
153
+ class FindingFeedbackRequest(BaseModel):
154
+ finding_index: int = Field(ge=0)
155
+ label: Literal['correct', 'incorrect', 'useful']
156
+
157
+
158
+ def _authorize(token: str | None) -> None:
159
+ expected = os.getenv("OCR_API_KEY", "").strip()
160
+ # Authentication is opt-in for local development, but deployments can
161
+ # require it explicitly. Never silently treat a missing production key
162
+ # as authenticated.
163
+ require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
164
+ if require_auth and not expected:
165
+ raise HTTPException(status_code=503, detail="API authentication is not configured")
166
+ if expected and (not token or not secrets.compare_digest(token, expected)):
167
+ raise HTTPException(status_code=401, detail="Invalid API key")
168
+
169
+ def _authorize_request(token: str | None, request: Request) -> None:
170
+ if _session(request):
171
+ return
172
+ _authorize(token)
173
+
174
+ def _session(request: Request) -> dict[str, Any] | None:
175
+ sid = request.cookies.get("ocr_session")
176
+ return _sessions.get(sid) if sid else None
177
+
178
+ @app.get("/api/auth/github/start")
179
+ def github_login() -> RedirectResponse:
180
+ client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
181
+ if not client_id:
182
+ raise HTTPException(status_code=503, detail="GitHub OAuth is not configured")
183
+ state = secrets.token_urlsafe(32)
184
+ _oauth_states.add(state)
185
+ callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
186
+ url = "https://github.com/login/oauth/authorize?" + requests.compat.urlencode({"client_id": client_id, "redirect_uri": callback, "scope": "read:user user:email repo", "state": state})
187
+ return RedirectResponse(url)
188
+
189
+ @app.get("/api/auth/github/callback")
190
+ def github_callback(code: str, state: str, response: Request) -> RedirectResponse:
191
+ if state not in _oauth_states:
192
+ raise HTTPException(status_code=400, detail="Invalid OAuth state")
193
+ _oauth_states.discard(state)
194
+ client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
195
+ client_secret = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "").strip()
196
+ callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
197
+ token_resp = requests.post("https://github.com/login/oauth/access_token", data={"client_id": client_id, "client_secret": client_secret, "code": code, "redirect_uri": callback}, headers={"Accept": "application/json"}, timeout=20)
198
+ token_resp.raise_for_status()
199
+ access_token = token_resp.json().get("access_token")
200
+ if not access_token:
201
+ raise HTTPException(status_code=502, detail="GitHub did not return an access token")
202
+ user_resp = requests.get("https://api.github.com/user", headers={"Authorization": f"Bearer {access_token}", "Accept": "application/vnd.github+json"}, timeout=20)
203
+ user_resp.raise_for_status()
204
+ user = user_resp.json()
205
+ sid = secrets.token_urlsafe(32)
206
+ _sessions[sid] = {"token": access_token, "github_id": user.get("id"), "login": user.get("login")}
207
+ frontend = os.getenv("OCR_FRONTEND_URL", allowed_origins[0] if allowed_origins else "http://localhost:5173")
208
+ out = RedirectResponse(frontend)
209
+ out.set_cookie("ocr_session", sid, httponly=True, secure=frontend.startswith("https://"), samesite="lax", max_age=86400)
210
+ return out
211
+
212
+ @app.get("/api/auth/me")
213
+ def github_me(request: Request) -> dict[str, Any]:
214
+ session = _session(request)
215
+ if not session:
216
+ raise HTTPException(status_code=401, detail="Not authenticated")
217
+ return {"github_id": session["github_id"], "login": session["login"]}
218
+
219
+ @app.post("/api/auth/logout")
220
+ def github_logout(request: Request) -> dict[str, str]:
221
+ sid = request.cookies.get("ocr_session")
222
+ if sid:
223
+ _sessions.pop(sid, None)
224
+ return {"status": "logged_out"}
225
+
226
+
227
+ def _public_job(job: dict[str, Any]) -> dict[str, Any]:
228
+ result = {key: value for key, value in job.items() if key not in {"config", "future", "request_fingerprint", "owner_id", "ragas_inputs"}}
229
+ now = time.time()
230
+ result["elapsed_seconds"] = round(max(0, now - job.get("started_timestamp", now)), 1) if job.get("status") in {"processing", "queued"} else job.get("elapsed_seconds", 0)
231
+ if job.get("status") == "queued":
232
+ result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
233
+ return result
234
+
235
+ def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
236
+ result = _public_job(job)
237
+ task_id = result.get("ragas_task_id")
238
+ with _ragas_lock:
239
+ task = _ragas_tasks.get(task_id) if task_id else None
240
+ def finish():
241
+ metrics = (task or {}).get('metrics') or job.get('ragas_metrics') or {}
242
+ evaluation = (task or {}).get('evaluation') or job.get('ragas_evaluation') or {}
243
+ result.setdefault('ragas', {}).update(metrics=metrics, evaluation=evaluation)
244
+ if metrics and result['ragas'].get('scores') and any(m.get('status') != 'completed' for m in metrics.values()):
245
+ result['ragas']['status'] = 'partial'
246
+ if metrics != job.get('ragas_metrics', {}) or evaluation != job.get('ragas_evaluation', {}):
247
+ with _lock:
248
+ live = _jobs.get(job.get('id'))
249
+ if live is not None:
250
+ live.update(ragas_metrics=metrics, ragas_evaluation=evaluation)
251
+ _save_job(live)
252
+ return result
253
+ if not task_id:
254
+ result["ragas"] = {
255
+ "status": "skipped",
256
+ "scores": result.get("ragas_scores") or {},
257
+ "reason": "Review incomplete; scoring was not started" if result.get("status") == "incomplete" else "No retrieval context was available for RAGAS evaluation",
258
+ }
259
+ else:
260
+ if job.get("ragas_status") in {"failed", "unavailable", "completed_no_scores"}:
261
+ result["ragas"] = {
262
+ "status": job["ragas_status"],
263
+ "scores": job.get("ragas_scores") or {},
264
+ "error": job.get("ragas_error"),
265
+ }
266
+ return finish()
267
+ with _ragas_lock:
268
+ task = _ragas_tasks.get(task_id)
269
+ if not task:
270
+ # Task registries are process-local. A restart invalidates an
271
+ # in-flight task instead of making the client poll forever.
272
+ if result.get("ragas_scores"):
273
+ result["ragas"] = {"status": "completed", "scores": result["ragas_scores"]}
274
+ else:
275
+ result["ragas"] = {"status": "unavailable", "error": "RAGAS task was lost during process restart"}
276
+ with _lock:
277
+ live = _jobs.get(job.get("id"))
278
+ if live is not None:
279
+ live["ragas_status"] = "unavailable"
280
+ live["ragas_error"] = result["ragas"]["error"]
281
+ _save_job(live)
282
+ elif not task.get("done"):
283
+ timeout = float(task.get("timeout_seconds") or os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90"))
284
+ started = float(task.get("started", 0) or 0)
285
+ if started and datetime.now(timezone.utc).timestamp() - started > timeout:
286
+ result["ragas"] = {"status": "failed", "error": f"RAGAS exceeded {int(timeout)} second timeout"}
287
+ with _lock:
288
+ live = _jobs.get(job.get("id"))
289
+ if live is not None:
290
+ live["ragas_status"] = "failed"
291
+ live["ragas_error"] = result["ragas"]["error"]
292
+ _save_job(live)
293
+ else:
294
+ result["ragas"] = {"status": "pending"}
295
+ elif task.get("error"):
296
+ result["ragas"] = {"status": "failed", "error": task.get("error")}
297
+ with _lock:
298
+ live = _jobs.get(job.get("id"))
299
+ if live is not None:
300
+ live["ragas_status"] = "failed"
301
+ live["ragas_error"] = task.get("error")
302
+ _save_job(live)
303
+ else:
304
+ scores = task.get("scores") or {}
305
+ if scores:
306
+ result["ragas"] = {"status": "completed", "scores": scores}
307
+ if not job.get("ragas_scores"):
308
+ with _lock:
309
+ live = _jobs.get(job.get("id"))
310
+ if live is not None:
311
+ live["ragas_scores"] = scores
312
+ live["ragas_status"] = "completed"
313
+ _save_job(live)
314
+ else:
315
+ result["ragas"] = {"status": "completed_no_scores", "scores": {}, "error": "RAGAS completed without metric values"}
316
+ with _lock:
317
+ live = _jobs.get(job.get("id"))
318
+ if live is not None:
319
+ live["ragas_status"] = "completed_no_scores"
320
+ live["ragas_error"] = result["ragas"]["error"]
321
+ _save_job(live)
322
+ return finish()
323
+
324
+
325
+ def _run_job(job_id: str, request: ReviewRequest) -> None:
326
+ with _lock:
327
+ if _jobs.get(job_id, {}).get("status") == "cancelled":
328
+ return
329
+ if job_id in _jobs:
330
+ _jobs[job_id].update(status="processing", started_timestamp=time.time(), progress={"stage": "ingestion", "completed_stages": []})
331
+ _save_job(_jobs[job_id])
332
+ try:
333
+ ephemeral_endpoint = None
334
+ endpoint_name = _normalize_endpoint_name(request.endpoint)
335
+ if request.api_key:
336
+ if not request.provider or not request.model:
337
+ raise ValueError("provider and model are required when supplying a user API key")
338
+ ephemeral_endpoint = f"user-{job_id}"
339
+ register_endpoint(ephemeral_endpoint, request.provider, request.api_key, request.base_url, request.model)
340
+ endpoint_name = ephemeral_endpoint
341
+ def save_ragas(scores: dict, error: str | None) -> None:
342
+ with _lock:
343
+ live = _jobs.get(job_id)
344
+ if live is None:
345
+ return
346
+ live["ragas_scores"] = scores or None
347
+ live["ragas_status"] = "failed" if error else ("completed" if scores else "completed_no_scores")
348
+ live["ragas_error"] = error
349
+ _save_job(live)
350
+
351
+ def progress(stage: str, elapsed: float, update: dict | None = None) -> None:
352
+ with _lock:
353
+ live = _jobs[job_id]
354
+ if live.get("status") == "cancelled":
355
+ raise RuntimeError("Review cancelled")
356
+ completed = live.setdefault("progress", {}).setdefault("completed_stages", [])
357
+ if stage not in completed:
358
+ completed.append(stage)
359
+ live["progress"]["stage"] = stage
360
+ live.setdefault("stage_timings", {})[stage] = round(elapsed, 2)
361
+ if isinstance(update, dict):
362
+ stages = update.get("review_stages", [])
363
+ if isinstance(stages, list):
364
+ live.setdefault("review_stages", []).extend(stages)
365
+ for key in ("findings",):
366
+ for finding in update.get(key, []) or []:
367
+ if hasattr(finding, "model_dump"):
368
+ finding = finding.model_dump(mode="json")
369
+ if isinstance(finding, dict):
370
+ live.setdefault("findings", []).append(finding)
371
+ _save_job(live)
372
+
373
+ state, config, cost, ragas, ragas_inputs = _build_and_stream(
374
+ request.repo,
375
+ request.pr_number,
376
+ endpoint_name,
377
+ ragas_background=True,
378
+ ragas_result_callback=save_ragas,
379
+ progress_callback=progress,
380
+ review_mode=request.review_mode,
381
+ baseline_sha=request.baseline_sha,
382
+ )
383
+ actual_head = state.values.get("head_sha")
384
+ verdict: Verdict | None = state.values.get("verdict")
385
+ findings: list[Finding] = state.values.get("final_findings", [])
386
+ with _lock:
387
+ if _jobs[job_id].get("status") == "cancelled":
388
+ return
389
+ if actual_head and _jobs[job_id].get("head_sha") != actual_head:
390
+ # The PR moved between metadata lookup and ingestion. The result
391
+ # can still be viewed, but must not satisfy the old cache key.
392
+ _jobs[job_id]["request_fingerprint"] = None
393
+ _jobs[job_id]["head_sha"] = actual_head
394
+ stages = state.values.get("review_stages", [])
395
+ incomplete = bool(verdict and verdict.recommendation == "incomplete")
396
+ _jobs[job_id].update(review_coverage=state.values.get("review_coverage", {}), review_stages=stages, elapsed_seconds=round(time.time() - _jobs[job_id]["started_timestamp"], 2), status="incomplete" if incomplete else "awaiting_approval", config=config, verdict=verdict.model_dump(mode="json") if verdict else None, findings=[item.model_dump(mode="json") for item in findings], cost=cost, cost_details=config.get("metadata", {}).get("cost_details"), ragas_task_id=ragas if isinstance(ragas, str) else None, ragas_scores=ragas if isinstance(ragas, dict) else None, ragas_inputs=None)
397
+ _save_job(_jobs[job_id])
398
+ except Exception as exc:
399
+ with _lock:
400
+ if _jobs[job_id].get("status") != "cancelled":
401
+ _jobs[job_id].update(status="failed", error=str(exc)[:500])
402
+ _save_job(_jobs[job_id])
403
+ finally:
404
+ if 'ephemeral_endpoint' in locals() and ephemeral_endpoint:
405
+ unregister_endpoint(ephemeral_endpoint)
406
+
407
+
408
+ def _hydrate_jobs() -> None:
409
+ """Restore persisted jobs after a process restart and resume interrupted work."""
410
+ for persisted in _load_jobs():
411
+ # Evaluation inputs may include an in-memory endpoint object. Never
412
+ # retain or expose that snapshot: it can contain a user's provider key.
413
+ if "ragas_inputs" in persisted:
414
+ persisted.pop("ragas_inputs", None)
415
+ _save_job(persisted)
416
+ job_id = persisted.get("id")
417
+ if not job_id:
418
+ continue
419
+ status = persisted.get("status")
420
+ _jobs[job_id] = persisted
421
+ if persisted.get("ragas_task_id") and not persisted.get("ragas_status"):
422
+ persisted.update(ragas_status="unavailable", ragas_error="Evaluation interrupted by restart; it was not automatically replayed.")
423
+ _save_job(persisted)
424
+ if status in {"queued", "processing"} and persisted.get("custom_provider"):
425
+ persisted.update(status="failed", error="Provider credentials were not persisted; resubmit this review after restart.")
426
+ _save_job(persisted)
427
+ continue
428
+ if status in {"queued", "processing", "processing_decision"}:
429
+ # Decision processing cannot be safely replayed without an explicit
430
+ # user action; review execution can be resumed idempotently.
431
+ if status == "processing_decision":
432
+ _jobs[job_id]["status"] = "awaiting_approval"
433
+ _save_job(_jobs[job_id])
434
+ continue
435
+ try:
436
+ request = ReviewRequest(repo=persisted["repo"], pr_number=int(persisted["pr_number"]), endpoint=persisted.get("endpoint"))
437
+ except Exception:
438
+ _jobs[job_id].update(status="failed", error="Persisted job request is invalid")
439
+ _save_job(_jobs[job_id])
440
+ continue
441
+ _jobs[job_id]["status"] = "queued"
442
+ _save_job(_jobs[job_id])
443
+ _jobs[job_id]["future"] = _executor.submit(_run_job, job_id, request)
444
+
445
+
446
+ _hydrate_jobs()
447
+
448
+
449
+ @app.get("/api/health")
450
+ def health() -> dict[str, Any]:
451
+ provider_configured = any(
452
+ os.getenv(name, "").strip()
453
+ for name in ("GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
454
+ )
455
+ require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
456
+ persistence = "local_default_path"
457
+ if os.getenv("SUPABASE_DB_URL"):
458
+ probe = _postgres_connect()
459
+ if probe is not None:
460
+ probe.close()
461
+ persistence = "supabase_postgres"
462
+ else:
463
+ persistence = "supabase_configured_unreachable"
464
+ elif os.getenv("OPENCODEREVIEW_DB_PATH"):
465
+ persistence = "configured_path"
466
+ return {
467
+ "status": "ok",
468
+ "inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
469
+ "authentication": "required" if require_auth else "optional",
470
+ "rate_limit_per_minute": int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0),
471
+ "persistence": persistence,
472
+ "local_embeddings": os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower()
473
+ in {"1", "true", "yes", "on"},
474
+ }
475
+
476
+
477
+ @app.post("/api/reviews", status_code=202)
478
+ def create_review(request: ReviewRequest, http_request: Request, x_api_key: str | None = Header(default=None), idempotency_key: str | None = Header(default=None, alias="Idempotency-Key")) -> dict[str, Any]:
479
+ _authorize_request(x_api_key, http_request)
480
+ _rate_limit(http_request)
481
+ owner = str((_session(http_request) or {}).get("github_id") or "api-key")
482
+ material = request.model_dump()
483
+ head_sha = base_sha = None
484
+ try:
485
+ token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
486
+ headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
487
+ if token:
488
+ headers["Authorization"] = f"Bearer {token}"
489
+ response = requests.get(f"https://api.github.com/repos/{request.repo}/pulls/{request.pr_number}", headers=headers, timeout=6)
490
+ response.raise_for_status()
491
+ pull = response.json()
492
+ head_sha, base_sha = pull["head"]["sha"], pull["base"]["sha"]
493
+ except (requests.RequestException, KeyError, ValueError):
494
+ pass # Active deduplication still works if GitHub metadata is unavailable.
495
+ prompt_hash = hashlib.sha256()
496
+ for source in sorted(Path(__file__).parent.joinpath("prompts").glob("*.txt")):
497
+ prompt_hash.update(source.read_bytes())
498
+ for source in sorted(Path(__file__).parent.joinpath("nodes").glob("*.py")):
499
+ prompt_hash.update(source.read_bytes())
500
+ material.update(head_sha=head_sha, base_sha=base_sha, pipeline_version=prompt_hash.hexdigest())
501
+ fingerprint = hashlib.sha256(json.dumps({"owner": owner, "request": material}, sort_keys=True).encode()).hexdigest()
502
+ # Reuse completed previews only for an identical immutable diff and configuration.
503
+ with _lock:
504
+ existing = next((item for item in _jobs.values() if item.get("owner_id") == owner and item.get("request_fingerprint") == fingerprint and (item.get("status") in {"queued", "processing"} or (head_sha and base_sha and item.get("status") == "awaiting_approval" and time.time() - item.get("started_timestamp", 0) < 900))), None)
505
+ if existing is None:
506
+ job_id = str(uuid.uuid4())
507
+ job = {"id": job_id, "repo": request.repo, "pr_number": request.pr_number, "endpoint": request.endpoint, "review_mode": request.review_mode, "baseline_sha": request.baseline_sha, "custom_provider": bool(request.api_key), "head_sha": head_sha, "base_sha": base_sha, "owner_id": owner, "request_fingerprint": fingerprint, "status": "queued", "created_at": datetime.now(timezone.utc).isoformat()}
508
+ _jobs[job_id] = job
509
+ _save_job(job)
510
+ else:
511
+ job = existing
512
+ if existing is not None:
513
+ return {**_with_ragas(job), "reused": True}
514
+ job["future"] = _executor.submit(_run_job, job_id, request)
515
+ return _with_ragas(job)
516
+
517
+
518
+ @app.post("/api/reviews/{job_id}/cancel")
519
+ def cancel_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
520
+ _authorize_request(x_api_key, request)
521
+ owner = str((_session(request) or {}).get("github_id") or "api-key")
522
+ with _lock:
523
+ job = _jobs.get(job_id)
524
+ if not job or job.get("owner_id", "api-key") != owner:
525
+ raise HTTPException(status_code=404, detail="Review not found")
526
+ if job.get("status") not in {"queued", "processing"}:
527
+ raise HTTPException(status_code=409, detail="Only queued or processing reviews can be cancelled")
528
+ future = job.get("future")
529
+ if future:
530
+ future.cancel()
531
+ job.update(status="cancelled", cancellation_note="Running calls finish within their timeout; no results will be posted.")
532
+ _save_job(job)
533
+ return _public_job(job)
534
+
535
+
536
+ @app.get("/api/reviews/{job_id}")
537
+ def get_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
538
+ # API-key authorization remains supported for polling; OAuth callers use the cookie path.
539
+ _authorize_request(x_api_key, request)
540
+ with _lock:
541
+ job = _jobs.get(job_id)
542
+ if not job:
543
+ job = _load_job(job_id)
544
+ owner = str((_session(request) or {}).get("github_id") or "api-key")
545
+ if not job or job.get("owner_id", "api-key") != owner:
546
+ raise HTTPException(status_code=404, detail="Review not found")
547
+ return _with_ragas(job)
548
+
549
+
550
+ @app.post('/api/reviews/{job_id}/feedback')
551
+ def finding_feedback(job_id: str, payload: FindingFeedbackRequest, request: Request,
552
+ x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
553
+ _authorize_request(x_api_key, request)
554
+ _rate_limit(request)
555
+ owner = str((_session(request) or {}).get('github_id') or 'api-key')
556
+ with _lock:
557
+ job = _jobs.get(job_id) or _load_job(job_id)
558
+ if not job or job.get('owner_id', 'api-key') != owner:
559
+ raise HTTPException(status_code=404, detail='Review not found')
560
+ if job.get('status') not in {'awaiting_approval', 'incomplete', 'posted', 'partially_posted', 'rejected', 'post_failed'}:
561
+ raise HTTPException(status_code=409, detail='Wait until the review finishes before giving feedback')
562
+ if payload.finding_index >= len(job.get('findings') or []):
563
+ raise HTTPException(status_code=422, detail='Finding does not exist')
564
+ feedback = dict(job.get('feedback') or {})
565
+ feedback[str(payload.finding_index)] = payload.label
566
+ job['feedback'] = feedback
567
+ job['feedback_updated_at'] = datetime.now(timezone.utc).isoformat()
568
+ _jobs[job_id] = job
569
+ _save_job(job)
570
+ return {'feedback': feedback}
571
+
572
+
573
+ @app.post("/api/reviews/{job_id}/decision")
574
+ def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
575
+ _authorize_request(x_api_key, http_request)
576
+ _rate_limit(http_request)
577
+ with _lock:
578
+ preview = _jobs.get(job_id) or _load_job(job_id)
579
+ owner = str((_session(http_request) or {}).get("github_id") or "api-key")
580
+ if not preview or preview.get("owner_id", "api-key") != owner:
581
+ raise HTTPException(status_code=404, detail="Review not found")
582
+ if request.action == "approve" and preview.get("baseline_sha"):
583
+ raise HTTPException(status_code=409, detail="Incremental reviews are preview-only. Run a full review before posting.")
584
+ if preview and request.action == "approve" and preview.get("head_sha"):
585
+ headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
586
+ token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
587
+ if token:
588
+ headers["Authorization"] = f"Bearer {token}"
589
+ try:
590
+ response = requests.get(f"https://api.github.com/repos/{preview['repo']}/pulls/{preview['pr_number']}", headers=headers, timeout=6)
591
+ response.raise_for_status()
592
+ current = response.json()
593
+ if current["head"]["sha"] != preview["head_sha"] or current["base"]["sha"] != preview.get("base_sha"):
594
+ raise HTTPException(status_code=409, detail="PR changed since this review; start a new review before posting.")
595
+ except (requests.RequestException, KeyError, ValueError) as exc:
596
+ raise HTTPException(status_code=503, detail="Cannot verify the current PR commit; retry before posting.") from exc
597
+ with _lock:
598
+ job = _jobs.get(job_id)
599
+ if not job:
600
+ job = _load_job(job_id)
601
+ if not job:
602
+ raise HTTPException(status_code=404, detail="Review not found")
603
+ if job.get("status") != "awaiting_approval":
604
+ raise HTTPException(status_code=409, detail="Review is not awaiting approval")
605
+ config = job["config"]
606
+ job["status"] = "processing_decision"
607
+ _save_job(job)
608
+ if request.action == "reject":
609
+ with _lock:
610
+ job.update(status="rejected", decision="reject")
611
+ _save_job(job)
612
+ return _public_job(job)
613
+ graph = build_graph(DB_PATH)
614
+ try:
615
+ callbacks = [TokenCostCallback()]
616
+ handler = get_langfuse_handler()
617
+ if handler:
618
+ callbacks.append(handler)
619
+ config = dict(config)
620
+ config["callbacks"] = callbacks
621
+ result = graph.invoke(Command(resume={"action": "approve"}), config)
622
+ posting_result = result.get("posting_result") if isinstance(result, dict) else None
623
+ final_status = (posting_result or {}).get("status", "posted")
624
+ with _lock:
625
+ job.update(status=final_status, decision="approve", posting_result=posting_result)
626
+ _save_job(job)
627
+ return _public_job(job)
628
+ except Exception as exc:
629
+ with _lock:
630
+ job.update(status="failed", error=str(exc)[:500])
631
+ _save_job(job)
632
+ raise HTTPException(status_code=500, detail="Decision processing failed") from exc
633
+ finally:
634
+ conn = getattr(graph, "_opencodereview_conn", None)
635
+ if conn:
636
+ conn.close()
637
+ flush_langfuse()
app.py CHANGED
The diff for this file is too large to render. See raw diff
 
eval_data/curated_located_fixture.jsonl CHANGED
@@ -1 +1 @@
1
- {"repo":"calcom/cal.diy","pr_number":10600,"pr_url":"https://github.com/calcom/cal.diy/pull/10600","label_scope":"partial","label_notes":"Two manually located code-review concerns, not an exhaustive gold set. Diff locations must be rechecked if the PR changes. Does not establish production vulnerability exploitability.","gold_issues":[{"file_path":"packages/features/auth/lib/next-auth-options.ts","line_start":136,"line_end":155,"category":"security","severity":"medium","comment":"Non-atomic backup-code read-modify-write permits concurrent reuse or lost updates.","concept_terms":["concurrent","race","atomic","reuse"]},{"file_path":"packages/features/auth/lib/next-auth-options.ts","line_start":143,"line_end":145,"category":"correctness","severity":"low","comment":"Backup code comparison rejects uppercase hex input because it is not normalized to lowercase.","concept_terms":["uppercase","lowercase","sensitive","normalize"]}]}
 
1
+ {"repo":"calcom/cal.diy","pr_number":10600,"pr_url":"https://github.com/calcom/cal.diy/pull/10600","label_scope":"partial","label_notes":"Two manually located code-review concerns, not an exhaustive gold set. Diff locations must be rechecked if the PR changes. Does not establish production vulnerability exploitability.","gold_issues":[{"file_path":"packages/features/auth/lib/next-auth-options.ts","line_start":136,"line_end":155,"category":"security","severity":"medium","comment":"Non-atomic backup-code read-modify-write permits concurrent reuse or lost updates.","concept_terms":["concurrent","race","atomic","reuse"]},{"file_path":"packages/features/auth/lib/next-auth-options.ts","line_start":143,"line_end":145,"category":"correctness","severity":"low","comment":"Backup code comparison rejects uppercase hex input because it is not normalized to lowercase.","concept_terms":["uppercase","lowercase","sensitive","normalize"]}]}
eval_data/offline_regression.py CHANGED
@@ -1,93 +1,93 @@
1
- """Offline location/category/concept matching, with no provider or model calls.
2
-
3
- Usage: python -m eval_data.offline_regression --predictions review.json --fixture labelled.jsonl --output report.json
4
- Gold rows require repo/pr_number (or pr_url) and findings/gold_issues with
5
- file_path, line_start/line_end, category, comment, and optional concept_terms.
6
- Scores are deterministic matching proxies, not proof of semantic correctness.
7
- """
8
- from __future__ import annotations
9
- import argparse
10
- import json
11
- import re
12
- from pathlib import Path
13
-
14
-
15
- def identity(row):
16
- url = row.get("pr_url") or row.get("task_id")
17
- if url:
18
- return str(url).replace("https://github.com/", "").replace("/pull/", "#")
19
- return f"{row.get('repo')}#{row.get('pr_number')}"
20
-
21
-
22
- def load_rows(path):
23
- text = Path(path).read_text(encoding="utf-8")
24
- try:
25
- rows = json.loads(text)
26
- return rows if isinstance(rows, list) else [rows]
27
- except json.JSONDecodeError:
28
- return [json.loads(line) for line in text.splitlines() if line.strip()]
29
-
30
-
31
- def match_score(prediction, gold):
32
- if prediction.get("file_path") != gold.get("file_path") or not gold.get("file_path"):
33
- return None
34
- if prediction.get("category") != gold.get("category") or not gold.get("category"):
35
- return None
36
- ps = int(prediction.get("line_start") or 0)
37
- gs = int(gold.get("line_start") or gold.get("line") or 0)
38
- if not ps or not gs:
39
- return None
40
- pe, ge = int(prediction.get("line_end") or ps), int(gold.get("line_end") or gs)
41
- if ps > ge + 3 or gs > pe + 3:
42
- return None
43
- words = set(re.findall(r"[a-z]+", prediction.get("comment", "").lower()))
44
- concepts = gold.get("concept_terms") or re.findall(r"[a-z]{4,}", gold.get("comment", "").lower())
45
- overlap = sum(1 for term in concepts if term.lower() in words)
46
- return overlap / max(1, len(concepts)) if overlap else None
47
-
48
-
49
- def evaluate(predictions, fixtures):
50
- indexed = {identity(row): row for row in fixtures}
51
- partial_labels = False
52
- total = dict(matched=0, predicted_bugs=0, gold_bugs=0, suggestions=0, duplicate_predictions=0, unlocatable_gold=0, rows=0)
53
- cases = []
54
- for prediction in predictions:
55
- key = identity(prediction)
56
- if key not in indexed:
57
- cases.append({"id": key, "status": "skipped", "reason": "No labelled fixture"})
58
- continue
59
- total["rows"] += 1
60
- partial_labels = partial_labels or indexed[key].get("label_scope") != "exhaustive"
61
- gold = indexed[key].get("findings") or indexed[key].get("gold_issues") or []
62
- total["unlocatable_gold"] += sum(not item.get("file_path") or not (item.get("line_start") or item.get("line")) for item in gold)
63
- valid = [item for item in gold if item.get("file_path") and (item.get("line_start") or item.get("line"))]
64
- bugs = [item for item in prediction.get("findings", []) if item.get("category") != "test_coverage" and item.get("kind") not in {"suggestion", "test_suggestion"}]
65
- total["suggestions"] += len(prediction.get("findings", [])) - len(bugs)
66
- total["predicted_bugs"] += len(bugs)
67
- total["gold_bugs"] += len(valid)
68
- edges = sorted([(score, pi, gi) for pi, pred in enumerate(bugs) for gi, item in enumerate(valid) if (score := match_score(pred, item)) is not None], reverse=True)
69
- used_predictions, used_gold = set(), set()
70
- for score, pi, gi in edges:
71
- if pi not in used_predictions and gi not in used_gold:
72
- used_predictions.add(pi)
73
- used_gold.add(gi)
74
- total["matched"] += len(used_gold)
75
- duplicate = sum(any(match_score(pred, item) is not None for item in valid) for pi, pred in enumerate(bugs) if pi not in used_predictions)
76
- total["duplicate_predictions"] += duplicate
77
- cases.append({"id": key, "status": prediction.get("status"), "matched": len(used_gold), "false_positives": len(bugs) - len(used_predictions), "missed": len(valid) - len(used_gold), "elapsed_seconds": prediction.get("elapsed_seconds"), "reviewer_failures": sum(item.get("status") == "failed" for item in prediction.get("review_stages", []))})
78
- return {"method": "location_category_concept_proxy_v1", "limitations": "Deterministic matching is not a semantic correctness judge. Labels and unmatched/duplicate predictions require human review. Unlocatable gold is excluded, never counted as a pass.", "totals": total, "label_scope": "partial" if partial_labels else "exhaustive", "precision": total["matched"] / total["predicted_bugs"] if total["predicted_bugs"] and not partial_labels and total["gold_bugs"] else None, "annotated_match_rate": total["matched"] / total["predicted_bugs"] if total["predicted_bugs"] and total["gold_bugs"] else None, "recall": total["matched"] / total["gold_bugs"] if total["gold_bugs"] else None, "cases": cases}
79
-
80
-
81
- def main():
82
- parser = argparse.ArgumentParser(description=__doc__)
83
- parser.add_argument("--predictions", required=True)
84
- parser.add_argument("--fixture", required=True)
85
- parser.add_argument("--output", default="eval_data/regression_report.json")
86
- args = parser.parse_args()
87
- report = evaluate(load_rows(args.predictions), load_rows(args.fixture))
88
- Path(args.output).write_text(json.dumps(report, indent=2), encoding="utf-8")
89
- print(json.dumps(report, indent=2))
90
-
91
-
92
- if __name__ == "__main__":
93
- main()
 
1
+ """Offline location/category/concept matching, with no provider or model calls.
2
+
3
+ Usage: python -m eval_data.offline_regression --predictions review.json --fixture labelled.jsonl --output report.json
4
+ Gold rows require repo/pr_number (or pr_url) and findings/gold_issues with
5
+ file_path, line_start/line_end, category, comment, and optional concept_terms.
6
+ Scores are deterministic matching proxies, not proof of semantic correctness.
7
+ """
8
+ from __future__ import annotations
9
+ import argparse
10
+ import json
11
+ import re
12
+ from pathlib import Path
13
+
14
+
15
+ def identity(row):
16
+ url = row.get("pr_url") or row.get("task_id")
17
+ if url:
18
+ return str(url).replace("https://github.com/", "").replace("/pull/", "#")
19
+ return f"{row.get('repo')}#{row.get('pr_number')}"
20
+
21
+
22
+ def load_rows(path):
23
+ text = Path(path).read_text(encoding="utf-8")
24
+ try:
25
+ rows = json.loads(text)
26
+ return rows if isinstance(rows, list) else [rows]
27
+ except json.JSONDecodeError:
28
+ return [json.loads(line) for line in text.splitlines() if line.strip()]
29
+
30
+
31
+ def match_score(prediction, gold):
32
+ if prediction.get("file_path") != gold.get("file_path") or not gold.get("file_path"):
33
+ return None
34
+ if prediction.get("category") != gold.get("category") or not gold.get("category"):
35
+ return None
36
+ ps = int(prediction.get("line_start") or 0)
37
+ gs = int(gold.get("line_start") or gold.get("line") or 0)
38
+ if not ps or not gs:
39
+ return None
40
+ pe, ge = int(prediction.get("line_end") or ps), int(gold.get("line_end") or gs)
41
+ if ps > ge + 3 or gs > pe + 3:
42
+ return None
43
+ words = set(re.findall(r"[a-z]+", prediction.get("comment", "").lower()))
44
+ concepts = gold.get("concept_terms") or re.findall(r"[a-z]{4,}", gold.get("comment", "").lower())
45
+ overlap = sum(1 for term in concepts if term.lower() in words)
46
+ return overlap / max(1, len(concepts)) if overlap else None
47
+
48
+
49
+ def evaluate(predictions, fixtures):
50
+ indexed = {identity(row): row for row in fixtures}
51
+ partial_labels = False
52
+ total = dict(matched=0, predicted_bugs=0, gold_bugs=0, suggestions=0, duplicate_predictions=0, unlocatable_gold=0, rows=0)
53
+ cases = []
54
+ for prediction in predictions:
55
+ key = identity(prediction)
56
+ if key not in indexed:
57
+ cases.append({"id": key, "status": "skipped", "reason": "No labelled fixture"})
58
+ continue
59
+ total["rows"] += 1
60
+ partial_labels = partial_labels or indexed[key].get("label_scope") != "exhaustive"
61
+ gold = indexed[key].get("findings") or indexed[key].get("gold_issues") or []
62
+ total["unlocatable_gold"] += sum(not item.get("file_path") or not (item.get("line_start") or item.get("line")) for item in gold)
63
+ valid = [item for item in gold if item.get("file_path") and (item.get("line_start") or item.get("line"))]
64
+ bugs = [item for item in prediction.get("findings", []) if item.get("category") != "test_coverage" and item.get("kind") not in {"suggestion", "test_suggestion"}]
65
+ total["suggestions"] += len(prediction.get("findings", [])) - len(bugs)
66
+ total["predicted_bugs"] += len(bugs)
67
+ total["gold_bugs"] += len(valid)
68
+ edges = sorted([(score, pi, gi) for pi, pred in enumerate(bugs) for gi, item in enumerate(valid) if (score := match_score(pred, item)) is not None], reverse=True)
69
+ used_predictions, used_gold = set(), set()
70
+ for score, pi, gi in edges:
71
+ if pi not in used_predictions and gi not in used_gold:
72
+ used_predictions.add(pi)
73
+ used_gold.add(gi)
74
+ total["matched"] += len(used_gold)
75
+ duplicate = sum(any(match_score(pred, item) is not None for item in valid) for pi, pred in enumerate(bugs) if pi not in used_predictions)
76
+ total["duplicate_predictions"] += duplicate
77
+ cases.append({"id": key, "status": prediction.get("status"), "matched": len(used_gold), "false_positives": len(bugs) - len(used_predictions), "missed": len(valid) - len(used_gold), "elapsed_seconds": prediction.get("elapsed_seconds"), "reviewer_failures": sum(item.get("status") == "failed" for item in prediction.get("review_stages", []))})
78
+ return {"method": "location_category_concept_proxy_v1", "limitations": "Deterministic matching is not a semantic correctness judge. Labels and unmatched/duplicate predictions require human review. Unlocatable gold is excluded, never counted as a pass.", "totals": total, "label_scope": "partial" if partial_labels else "exhaustive", "precision": total["matched"] / total["predicted_bugs"] if total["predicted_bugs"] and not partial_labels and total["gold_bugs"] else None, "annotated_match_rate": total["matched"] / total["predicted_bugs"] if total["predicted_bugs"] and total["gold_bugs"] else None, "recall": total["matched"] / total["gold_bugs"] if total["gold_bugs"] else None, "cases": cases}
79
+
80
+
81
+ def main():
82
+ parser = argparse.ArgumentParser(description=__doc__)
83
+ parser.add_argument("--predictions", required=True)
84
+ parser.add_argument("--fixture", required=True)
85
+ parser.add_argument("--output", default="eval_data/regression_report.json")
86
+ args = parser.parse_args()
87
+ report = evaluate(load_rows(args.predictions), load_rows(args.fixture))
88
+ Path(args.output).write_text(json.dumps(report, indent=2), encoding="utf-8")
89
+ print(json.dumps(report, indent=2))
90
+
91
+
92
+ if __name__ == "__main__":
93
+ main()
eval_data/ragas_eval.py CHANGED
@@ -1,631 +1,661 @@
1
- #!/usr/bin/env python3
2
- """RAGAS-based evaluation of retrieval quality for OpenCodeReview.
3
-
4
- Computes **context_precision** and **context_recall** metrics from the
5
- RAGAS framework (https://docs.ragas.io/) on the retrieved context chunks
6
- produced by the ``retrieval_node``.
7
-
8
- These metrics answer:
9
- - **Context Precision**: Are the most relevant code chunks ranked first?
10
- - **Context Recall**: Does the retrieved set contain all the information
11
- needed for the reviewers to produce accurate findings?
12
-
13
- Usage
14
- -----
15
- from eval_data.ragas_eval import compute_ragas_retrieval_scores
16
-
17
- score = compute_ragas_retrieval_scores(
18
- query="diff of PR ...",
19
- retrieved_contexts=["chunk1 text", "chunk2 text", ...],
20
- ground_truth="Human review comment text ...",
21
- )
22
- # score == {"context_precision": 0.85, "context_recall": 0.72}
23
-
24
- Lazy imports minimise overhead when RAGAS is not installed.
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- from contextvars import ContextVar
30
- import logging
31
- import os
32
- import threading
33
- import time
34
- from typing import Any, Optional
35
-
36
- logger = logging.getLogger(__name__)
37
-
38
- # ─── Lazy RAGAS imports with graceful fallback ──────────────────────────────
39
-
40
- _RAGAS_AVAILABLE: bool | None = None
41
-
42
-
43
- def _check_ragas() -> bool:
44
- """Return True if RAGAS is available.
45
-
46
- Note: ``litellm`` is NOT required because RAGAS scoring uses the
47
- project's own LLM factory (Gemini or Groq via LangChain), not
48
- litellm internally.
49
- """
50
- global _RAGAS_AVAILABLE
51
- if _RAGAS_AVAILABLE is not None:
52
- return _RAGAS_AVAILABLE
53
- try:
54
- import ragas # noqa: F401
55
- _RAGAS_AVAILABLE = True
56
- except ImportError:
57
- logger.warning(
58
- "ragas not installed. Install with: pip install ragas"
59
- )
60
- _RAGAS_AVAILABLE = False
61
- return _RAGAS_AVAILABLE
62
-
63
-
64
- # Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
65
- # burst of ~20-30 model calls per review (context-precision judgments,
66
- # faithfulness verification, answer relevancy, MMR relevance checks).
67
- # Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
68
- # limits so scoring completes instead of tripping 429s β€” which previously
69
- # caused long retry backoffs and 0.0000 scores. Override with the
70
- # OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
71
- _RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
72
- _ragas_throttle_lock = threading.Lock()
73
- _metric_deadline = ContextVar("ragas_metric_deadline", default=None)
74
-
75
-
76
- class _ThrottledChatModel:
77
- """Wrap a LangChain chat model so every underlying API call RAGAS makes
78
- is spaced by a fixed interval.
79
-
80
- RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
81
- the langchain model) and the custom MMR path call the model through
82
- different entry points (sync/async, single/batched). Intercepting
83
- ``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
84
- every request is throttled regardless of ragas version.
85
- """
86
-
87
- def __init__(self, model, interval: float | None = None):
88
- self._model = model
89
- self._interval = _RAGAS_INTERVAL if interval is None else interval
90
- self._quota_exhausted = False
91
-
92
- def _call(self, method, *args, **kwargs):
93
- try:
94
- return method(*args, **kwargs)
95
- except Exception as exc:
96
- if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
97
- self._quota_exhausted = True
98
- raise
99
-
100
- async def _acall(self, method, *args, **kwargs):
101
- try:
102
- return await method(*args, **kwargs)
103
- except Exception as exc:
104
- if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
105
- self._quota_exhausted = True
106
- raise
107
-
108
- def _wait(self) -> None:
109
- deadline = _metric_deadline.get()
110
- if deadline is not None and time.monotonic() >= deadline:
111
- raise TimeoutError("Metric deadline exceeded; no further judge calls")
112
- if self._quota_exhausted:
113
- raise RuntimeError("Evaluation stopped: provider authentication or quota limit; no further calls will be made for this evaluation.")
114
- if self._interval > 0:
115
- with _ragas_throttle_lock:
116
- time.sleep(self._interval)
117
-
118
- # ── Sync entry points ───────────────────────────────────────────────
119
- def invoke(self, *args, **kwargs):
120
- self._wait()
121
- return self._call(self._model.invoke, *args, **kwargs)
122
-
123
- def generate(self, messages, *args, **kwargs):
124
- # Serialize LangChain batch calls into individual throttled
125
- # requests so every underlying API call is spaced by the interval.
126
- if (
127
- isinstance(messages, list)
128
- and messages
129
- and isinstance(messages[0], list)
130
- ):
131
- from langchain_core.outputs import Generation, LLMResult
132
-
133
- generations = []
134
- for msgs in messages:
135
- self._wait()
136
- # invoke() does not accept callbacks/run_manager/config that
137
- # ragas may forward to generate() β€” drop them here.
138
- resp = self._call(self._model.invoke, msgs)
139
- text = resp.content if hasattr(resp, "content") else str(resp)
140
- generations.append([Generation(text=text, message=resp)])
141
- return LLMResult(generations=generations, llm_output=None)
142
- self._wait()
143
- return self._call(self._model.generate, messages, *args, **kwargs)
144
-
145
- # ── Async entry points ──────────────────────────────────────────────
146
- async def ainvoke(self, *args, **kwargs):
147
- self._wait()
148
- return await self._acall(self._model.ainvoke, *args, **kwargs)
149
-
150
- async def agenerate(self, messages, *args, **kwargs):
151
- if (
152
- isinstance(messages, list)
153
- and messages
154
- and isinstance(messages[0], list)
155
- ):
156
- from langchain_core.outputs import Generation, LLMResult
157
-
158
- generations = []
159
- for msgs in messages:
160
- self._wait()
161
- # Same kwargs caveat as generate(): ainvoke has no callbacks.
162
- resp = await self._acall(self._model.ainvoke, msgs)
163
- text = resp.content if hasattr(resp, "content") else str(resp)
164
- generations.append([Generation(text=text, message=resp)])
165
- return LLMResult(generations=generations, llm_output=None)
166
- self._wait()
167
- return await self._acall(self._model.agenerate, messages, *args, **kwargs)
168
-
169
- # ── Everything else passes through ──────────────────────────────────
170
- def __getattr__(self, name: str):
171
- return getattr(self._model, name)
172
-
173
-
174
- def _wrap_evaluator(llm):
175
- from ragas.llms import LangchainLLMWrapper
176
- from ragas.run_config import RunConfig
177
- return LangchainLLMWrapper(_ThrottledChatModel(llm), run_config=RunConfig(timeout=12, max_retries=1, max_wait=0, max_workers=1))
178
-
179
-
180
- def _get_evaluator_llm(endpoint: Optional[str] = None):
181
- """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
182
-
183
- Priority:
184
- 1. **Custom endpoint** β€” when *endpoint* names a configured
185
- ``OCR_ENDPOINT_*`` config, it is used (any provider the user added).
186
- 2. **Groq** (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
187
- 3. **Google Gemini** (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``
188
-
189
- Groq is preferred over Gemini because scoring fires many LLM calls per
190
- review and the Gemini free tier (15 req/min) is already shared with the
191
- main review pipeline β€” using Groq's separate quota pool avoids the 429
192
- rate-limit failures that used to zero out the metrics.
193
-
194
- RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
195
- """
196
- from ragas.llms import LangchainLLMWrapper
197
-
198
- try:
199
- if endpoint:
200
- from llm_factory import create_llm
201
-
202
- llm = create_llm(endpoint=endpoint, temperature=0, timeout=15, max_retries=0)
203
- logger.info("RAGAS evaluator: using custom endpoint %s", endpoint)
204
- return _wrap_evaluator(llm)
205
-
206
- from llm_factory import _get_groq_chat, _get_gemini_chat
207
-
208
- # Keep evaluation bounded: RAGAS runs several provider calls and
209
- # retrying each one can otherwise hold a review open for minutes.
210
- configured_model = os.getenv("RAGAS_MODEL", "").strip()
211
- if configured_model.startswith("groq/"):
212
- configured_model = configured_model.split("/", 1)[1]
213
- groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": 15}
214
- if configured_model:
215
- groq_kwargs["model"] = configured_model
216
- llm = _get_groq_chat(**groq_kwargs)
217
- if llm is None:
218
- logger.info(
219
- "RAGAS evaluator: GROQ_API_KEY not set β€” falling back to Gemini"
220
- )
221
- llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=15)
222
- if llm is None:
223
- raise ValueError(
224
- "No LLM available for RAGAS scoring. "
225
- "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
226
- )
227
- logger.info(
228
- "RAGAS evaluator: using %s (throttled %ss)",
229
- type(llm).__name__,
230
- _RAGAS_INTERVAL,
231
- )
232
- return _wrap_evaluator(llm)
233
- except ValueError as exc:
234
- logger.warning("RAGAS evaluator: %s", exc)
235
- raise RuntimeError(
236
- "No LLM available for RAGAS scoring. "
237
- "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
238
- ) from exc
239
-
240
-
241
- # ─── Score computation ─────────────────────────────────────────────────────
242
-
243
-
244
- def _score_one_metric(name, sample, llm, timeout):
245
- from ragas import metrics
246
- from ragas.run_config import RunConfig
247
- classes = {"context_precision": "LLMContextPrecisionWithoutReference", "faithfulness": "Faithfulness", "context_recall": "ContextRecall"}
248
- scorer = getattr(metrics, classes[name])(llm=llm)
249
- scorer.init(RunConfig(timeout=timeout, max_retries=1, max_wait=0, max_workers=1))
250
- return float(scorer.single_turn_score(sample))
251
-
252
-
253
- def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None, *, metric_timeout=None, progress_callback=None):
254
- """Run independent bounded RAGAS metrics, preserving successes and real failures.
255
-
256
- No local embedding model is loaded. Lexical overlap is never substituted for
257
- RAGAS. Input caps reduce judge latency and are disclosed in the report.
258
- """
259
- import math
260
- import queue
261
- from contextvars import copy_context
262
- started = time.monotonic()
263
- total_budget = max(1.0, float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "30")))
264
- per_metric = max(.05, float(metric_timeout or os.getenv("OCR_RAGAS_METRIC_TIMEOUT_SECONDS", "12")))
265
- names = ["context_precision", "faithfulness"]
266
- if ground_truth:
267
- names.append("context_recall")
268
- report = {"scores": {}, "metrics": {}, "evaluation": {"engine": "RAGAS", "local_models": False, "metric_timeout_seconds": per_metric, "input_truncated": len(query) > 6000 or len(answer or "") > 4000 or len(retrieved_contexts) > 2 or any(len(c) > 4000 for c in retrieved_contexts)}}
269
- def finish(name, status, value=None, error=None, duration=0):
270
- report["metrics"][name] = {"status": status, "value": value, "error": error, "duration_seconds": round(duration, 3)}
271
- if value is not None:
272
- report["scores"][name] = value
273
- if progress_callback:
274
- progress_callback(report)
275
- for name, reason in [("answer_relevancy", "Requires embeddings; local models are disabled"), ("mmr", "Extra judge calls disabled in hosted evaluation")]:
276
- finish(name, "skipped", error=reason)
277
- if not ground_truth:
278
- finish("context_recall", "skipped", error="No reference answer provided")
279
- if not answer or not retrieved_contexts:
280
- for name in names:
281
- finish(name, "skipped", error="A complete answer and context are required")
282
- return report
283
- try:
284
- if not _check_ragas():
285
- raise RuntimeError("RAGAS is not installed")
286
- from ragas.dataset_schema import SingleTurnSample
287
- llm = _get_evaluator_llm(endpoint=endpoint)
288
- sample = SingleTurnSample(user_input=query[:6000], response=answer[:4000], retrieved_contexts=[c[:4000] for c in retrieved_contexts[:2]], reference=ground_truth[:4000] if ground_truth else None)
289
- except Exception as exc:
290
- for name in names:
291
- finish(name, "failed", error=type(exc).__name__)
292
- return report
293
- pending = {}
294
- for name in names:
295
- remaining = total_budget - (time.monotonic() - started) - 1
296
- if remaining <= 0:
297
- finish(name, "timed_out", error="Evaluation setup exhausted deadline")
298
- continue
299
- deadline = time.monotonic() + min(per_metric, remaining)
300
- output = queue.Queue(maxsize=1)
301
- def run(metric=name, target=output, limit=min(per_metric, remaining)):
302
- metric_started = time.monotonic()
303
- token = _metric_deadline.set(metric_started + limit)
304
- try:
305
- value = _score_one_metric(metric, sample, llm, limit)
306
- if not math.isfinite(value) or not 0 <= value <= 1:
307
- raise ValueError("Invalid metric value")
308
- target.put(("completed", round(value, 4), None, time.monotonic() - metric_started))
309
- except Exception as exc:
310
- target.put(("failed", None, type(exc).__name__, time.monotonic() - metric_started))
311
- finally:
312
- _metric_deadline.reset(token)
313
- threading.Thread(target=copy_context().run, args=(run,), daemon=True).start()
314
- pending[name] = (output, deadline)
315
- while pending:
316
- for name, (output, deadline) in list(pending.items()):
317
- try:
318
- status, value, error, duration = output.get_nowait()
319
- except queue.Empty:
320
- if time.monotonic() < deadline:
321
- continue
322
- status, value, error, duration = "timed_out", None, "Metric deadline exceeded", per_metric
323
- finish(name, status, value, error, duration)
324
- del pending[name]
325
- if pending:
326
- time.sleep(.01)
327
- report["evaluation"]["duration_seconds"] = round(time.monotonic() - started, 3)
328
- return report
329
-
330
-
331
- def compute_ragas_retrieval_scores(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None):
332
- """Compatibility mapping. Failed/skipped metrics remain None, never invented scores."""
333
- report = compute_ragas_report(query, retrieved_contexts, ground_truth, answer, endpoint)
334
- return {name: metric["value"] for name, metric in report["metrics"].items()}
335
-
336
-
337
- def _create_ragas_embeddings():
338
- """Return a lightweight embedding object compatible with RAGAS metrics.
339
-
340
- Wraps the ChromaDB ONNX MiniLM embedding function so that metrics like
341
- ``ResponseRelevancy`` can compute cosine similarity between embeddings.
342
- The underlying ONNX model is cached globally and loads in <1 s.
343
- """
344
- if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
345
- logger.info("Local RAGAS embeddings disabled; skipping answer relevancy")
346
- return None
347
- try:
348
- from chromadb.utils import embedding_functions
349
-
350
- if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
351
- ef = embedding_functions.ONNXMiniLM_L6_V2()
352
- else:
353
- ef = embedding_functions.SentenceTransformerEmbeddingFunction(
354
- model_name="all-MiniLM-L6-v2"
355
- )
356
-
357
- class _RagasEmbeddings:
358
- def __init__(self, ef):
359
- self._ef = ef
360
-
361
- def embed_query(self, text: str) -> list[float]:
362
- result = self._ef([text])[0]
363
- return list(result) if not isinstance(result, list) else result
364
-
365
- def embed_documents(self, texts: list[str]) -> list[list[float]]:
366
- results = self._ef(texts)
367
- return [list(r) if not isinstance(r, list) else r for r in results]
368
-
369
- return _RagasEmbeddings(ef)
370
- except Exception as exc:
371
- logger.warning("Cannot create RAGAS embeddings: %s", exc)
372
- return None
373
-
374
-
375
- def _compute_mmr(
376
- query: str,
377
- retrieved_contexts: list[str],
378
- llm: Any,
379
- ) -> float:
380
- """Compute Mean Reciprocal Rank β€” how early the first relevant chunk appears.
381
-
382
- Uses the LLM to judge each chunk's relevance to the query in order.
383
- The first chunk judged relevant determines the reciprocal rank:
384
- ``1 / rank_of_first_relevant``. Returns 0.0 if none are relevant.
385
-
386
- Parameters
387
- ----------
388
- query : str
389
- The search query (PR diff).
390
- retrieved_contexts : list[str]
391
- Ranked list of retrieved code chunks.
392
- llm : LangchainLLMWrapper
393
- RAGAS-wrapped LLM for relevance judgments.
394
-
395
- Returns
396
- -------
397
- float
398
- MMR score in [0, 1]; 0.0 when chunks were judged but none were
399
- relevant.
400
-
401
- Raises
402
- ------
403
- RuntimeError
404
- If every relevance judgment failed (e.g. LLM rate-limited) β€”
405
- callers treat this as a failed metric rather than a fake 0.0.
406
- """
407
- if not retrieved_contexts:
408
- return 0.0
409
-
410
- # Score up to the first 5 chunks for relevance using the LLM.
411
- # Top-5 MMR is standard β€” rank 5 yields 1/5 = 0.20, and
412
- # anything beyond rank 5 barely changes the score anyway.
413
- MAX_MMR_RANK = 2
414
- top_chunks = retrieved_contexts[:MAX_MMR_RANK]
415
-
416
- judged = 0
417
- for rank, chunk in enumerate(top_chunks, start=1):
418
- try:
419
- prompt = (
420
- f"Is the following code/document chunk relevant to the question?\n\n"
421
- f"Question: {query[:2_000]}\n\n"
422
- f"Chunk: {chunk[:2_000]}\n\n"
423
- f"Answer with exactly one word: YES or NO"
424
- )
425
- # Use the wrapped LangChain model for fast synchronous invoke.
426
- # LangchainLLMWrapper stores the model as .langchain_llm in ragas
427
- # 0.4.x and as .llm in 0.3.x β€” accept both.
428
- langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
429
- # Space the relevance judgments too β€” this unwrapped path bypasses
430
- # the model wrapper on some ragas versions, so sleep explicitly
431
- # (unless the wrapper is already in the path, to avoid double-sleep).
432
- if not isinstance(langchain_model, _ThrottledChatModel):
433
- time.sleep(_RAGAS_INTERVAL)
434
- raw = langchain_model.invoke(prompt)
435
- response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
436
- if response_text.startswith("Y"):
437
- return 1.0 / rank
438
- judged += 1 # judge responded β€” chunk deemed not relevant
439
- except Exception:
440
- continue
441
-
442
- if judged == 0:
443
- # Every relevance judgment failed (e.g. LLM rate-limited) β€” surface
444
- # this as a failed metric instead of a misleading 0.0.
445
- raise RuntimeError("all MMR relevance judgments failed")
446
-
447
- return 0.0
448
-
449
-
450
- def log_ragas_scores_to_langfuse(
451
- scores: dict[str, float | None],
452
- repo: str = "",
453
- pr_number: int = 0,
454
- handler: Any = None,
455
- ) -> None:
456
- """Log RAGAS metrics as Langfuse scores (linked to the review trace).
457
-
458
- Parameters
459
- ----------
460
- scores : dict
461
- Output of :func:`compute_ragas_retrieval_scores`.
462
- repo : str
463
- GitHub repository name (e.g. ``\"psf/requests\"``).
464
- pr_number : int
465
- Pull request number.
466
- handler : Langfuse CallbackHandler or None
467
- Handler from the current review run, used to link scores to the trace.
468
- """
469
- try:
470
- from observability import log_langfuse_score
471
- except ImportError:
472
- logger.debug("observability module not available β€” skipping Langfuse")
473
- return
474
-
475
- for metric_name, value in scores.items():
476
- if value is None:
477
- continue
478
- log_langfuse_score(
479
- name=f"ragas_{metric_name}",
480
- value=value,
481
- comment=f"{repo}#{pr_number} β€” {metric_name}",
482
- handler=handler,
483
- )
484
-
485
-
486
- # ─── Standalone CLI ─────────────────────────────────────────────────────────
487
-
488
-
489
- def main() -> None:
490
- """CLI entry point: compute RAGAS scores from a JSONL dataset.
491
-
492
- Usage::
493
-
494
- python eval_data/ragas_eval.py --data eval_data/prs.jsonl
495
- """
496
- import argparse
497
- import json
498
-
499
- parser = argparse.ArgumentParser(
500
- description="Compute RAGAS retrieval quality scores on evaluation data",
501
- )
502
- parser.add_argument(
503
- "--data", default=None,
504
- help="Path to JSONL dataset (same format as evaluate.py)",
505
- )
506
- parser.add_argument(
507
- "--output", default=None,
508
- help="Path to write per-PR RAGAS scores (JSON)",
509
- )
510
- parser.add_argument(
511
- "--max-prs", type=int, default=None,
512
- help="Max PRs to process",
513
- )
514
- parser.add_argument(
515
- "--log-to-observability", action="store_true",
516
- help="Log RAGAS scores to Langfuse",
517
- )
518
- args = parser.parse_args()
519
-
520
- logging.basicConfig(
521
- level=logging.INFO,
522
- format="%(asctime)s [%(levelname)s] %(name)s β€” %(message)s",
523
- )
524
-
525
- if not args.data:
526
- # If no data file specified, try default location
527
- default_path = os.path.join(
528
- os.path.dirname(__file__), "prs.jsonl"
529
- )
530
- if os.path.exists(default_path):
531
- args.data = default_path
532
- else:
533
- logger.error(
534
- "No --data provided and default not found at %s. "
535
- "Run eval_data/fetcher.py first.",
536
- default_path,
537
- )
538
- return
539
-
540
- with open(args.data, "r", encoding="utf-8") as f:
541
- entries = [json.loads(line) for line in f if line.strip()]
542
-
543
- if args.max_prs:
544
- entries = entries[: args.max_prs]
545
-
546
- all_scores: list[dict] = []
547
- for entry in entries:
548
- repo = entry.get("repo", "?")
549
- pr = entry.get("pr_number", 0)
550
- diff = entry.get("diff", "")
551
- ground_truth_list = entry.get("ground_truth", [])
552
-
553
- # Use the diff as the query, and first few human comments
554
- # as a proxy for "what the retrieval should have found"
555
- query = diff[:8_000] if diff else entry.get("title", "")
556
- gt_text = (
557
- " ".join(
558
- g.get("comment", "")
559
- for g in ground_truth_list[:5]
560
- )
561
- if ground_truth_list
562
- else None
563
- )
564
-
565
- # Retrieved contexts come from the graph run, but for the CLI
566
- # we don't re-run the graph β€” we just skip if no retrieval data
567
- # is available in the entry.
568
- stored_contexts = entry.get("retrieved_contexts", [])
569
- if not stored_contexts:
570
- logger.info(
571
- "[%s#%d] No stored retrieval contexts β€” skipping RAGAS",
572
- repo, pr,
573
- )
574
- continue
575
-
576
- logger.info("[%s#%d] Computing RAGAS scores …", repo, pr)
577
- try:
578
- scores = compute_ragas_retrieval_scores(
579
- query=query,
580
- retrieved_contexts=stored_contexts,
581
- ground_truth=gt_text,
582
- )
583
- except RuntimeError as exc:
584
- logger.warning("[%s#%d] %s", repo, pr, exc)
585
- break
586
-
587
- scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
588
- all_scores.append(scores)
589
-
590
- if args.log_to_observability:
591
- log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)
592
-
593
- print(
594
- f" {repo}#{pr}: "
595
- + " | ".join(
596
- f"{k}={v:.3f}" for k, v in scores.items()
597
- if k not in ("repo", "pr_number", "id") and v is not None
598
- )
599
- )
600
-
601
- # Print aggregate
602
- if all_scores:
603
- print()
604
- print("=" * 60)
605
- print(" Aggregate RAGAS scores")
606
- print("=" * 60)
607
- metrics = [
608
- k for k in all_scores[0].keys()
609
- if k not in ("repo", "pr_number", "id")
610
- ]
611
- for metric in metrics:
612
- values = [
613
- s.get(metric) for s in all_scores
614
- if s.get(metric) is not None
615
- ]
616
- if not values:
617
- print(f" {metric:30s}: n/a (no successful scores)")
618
- continue
619
- avg = sum(values) / len(values)
620
- print(f" {metric:30s}: {avg:.4f} (over {len(values)} PRs)")
621
- print()
622
-
623
- # Save output
624
- if args.output and all_scores:
625
- with open(args.output, "w", encoding="utf-8") as f:
626
- json.dump(all_scores, f, indent=2)
627
- logger.info("Saved RAGAS scores to %s", args.output)
628
-
629
-
630
- if __name__ == "__main__":
631
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """RAGAS-based evaluation of retrieval quality for OpenCodeReview.
3
+
4
+ Computes **context_precision** and **context_recall** metrics from the
5
+ RAGAS framework (https://docs.ragas.io/) on the retrieved context chunks
6
+ produced by the ``retrieval_node``.
7
+
8
+ These metrics answer:
9
+ - **Context Precision**: Are the most relevant code chunks ranked first?
10
+ - **Context Recall**: Does the retrieved set contain all the information
11
+ needed for the reviewers to produce accurate findings?
12
+
13
+ Usage
14
+ -----
15
+ from eval_data.ragas_eval import compute_ragas_retrieval_scores
16
+
17
+ score = compute_ragas_retrieval_scores(
18
+ query="diff of PR ...",
19
+ retrieved_contexts=["chunk1 text", "chunk2 text", ...],
20
+ ground_truth="Human review comment text ...",
21
+ )
22
+ # score == {"context_precision": 0.85, "context_recall": 0.72}
23
+
24
+ Lazy imports minimise overhead when RAGAS is not installed.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from contextvars import ContextVar
30
+ import logging
31
+ import os
32
+ import threading
33
+ import time
34
+ from typing import Any, Optional
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ # ─── Lazy RAGAS imports with graceful fallback ──────────────────────────────
39
+
40
+ _RAGAS_AVAILABLE: bool | None = None
41
+
42
+
43
+ def _check_ragas() -> bool:
44
+ """Return True if RAGAS is available.
45
+
46
+ Note: ``litellm`` is NOT required because RAGAS scoring uses the
47
+ project's own LLM factory (Gemini or Groq via LangChain), not
48
+ litellm internally.
49
+ """
50
+ global _RAGAS_AVAILABLE
51
+ if _RAGAS_AVAILABLE is not None:
52
+ return _RAGAS_AVAILABLE
53
+ try:
54
+ import ragas # noqa: F401
55
+ _RAGAS_AVAILABLE = True
56
+ except ImportError:
57
+ logger.warning(
58
+ "ragas not installed. Install with: pip install ragas"
59
+ )
60
+ _RAGAS_AVAILABLE = False
61
+ return _RAGAS_AVAILABLE
62
+
63
+
64
+ # Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
65
+ # burst of ~20-30 model calls per review (context-precision judgments,
66
+ # faithfulness verification, answer relevancy, MMR relevance checks).
67
+ # Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
68
+ # limits so scoring completes instead of tripping 429s β€” which previously
69
+ # caused long retry backoffs and 0.0000 scores. Override with the
70
+ # OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
71
+ _RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
72
+ _ragas_throttle_lock = threading.Lock()
73
+ _metric_deadline = ContextVar("ragas_metric_deadline", default=None)
74
+
75
+
76
+ class _ThrottledChatModel:
77
+ """Wrap a LangChain chat model so every underlying API call RAGAS makes
78
+ is spaced by a fixed interval.
79
+
80
+ RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
81
+ the langchain model) and the custom MMR path call the model through
82
+ different entry points (sync/async, single/batched). Intercepting
83
+ ``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
84
+ every request is throttled regardless of ragas version.
85
+ """
86
+
87
+ def __init__(self, model, interval: float | None = None):
88
+ self._model = model
89
+ self._interval = _RAGAS_INTERVAL if interval is None else interval
90
+ self._quota_exhausted = False
91
+
92
+ def _call(self, method, *args, **kwargs):
93
+ try:
94
+ return method(*args, **kwargs)
95
+ except Exception as exc:
96
+ if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
97
+ self._quota_exhausted = True
98
+ raise
99
+
100
+ async def _acall(self, method, *args, **kwargs):
101
+ try:
102
+ return await method(*args, **kwargs)
103
+ except Exception as exc:
104
+ if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
105
+ self._quota_exhausted = True
106
+ raise
107
+
108
+ def _wait(self) -> None:
109
+ deadline = _metric_deadline.get()
110
+ if deadline is not None and time.monotonic() >= deadline:
111
+ raise TimeoutError("Metric deadline exceeded; no further judge calls")
112
+ if self._quota_exhausted:
113
+ raise RuntimeError("Evaluation stopped: provider authentication or quota limit; no further calls will be made for this evaluation.")
114
+ if self._interval > 0:
115
+ with _ragas_throttle_lock:
116
+ time.sleep(self._interval)
117
+
118
+ # ── Sync entry points ───────────────────────────────────────────────
119
+ def invoke(self, *args, **kwargs):
120
+ self._wait()
121
+ return self._call(self._model.invoke, *args, **kwargs)
122
+
123
+ def generate(self, messages, *args, **kwargs):
124
+ # Serialize LangChain batch calls into individual throttled
125
+ # requests so every underlying API call is spaced by the interval.
126
+ if (
127
+ isinstance(messages, list)
128
+ and messages
129
+ and isinstance(messages[0], list)
130
+ ):
131
+ from langchain_core.outputs import Generation, LLMResult
132
+
133
+ generations = []
134
+ for msgs in messages:
135
+ self._wait()
136
+ # invoke() does not accept callbacks/run_manager/config that
137
+ # ragas may forward to generate() β€” drop them here.
138
+ resp = self._call(self._model.invoke, msgs)
139
+ text = resp.content if hasattr(resp, "content") else str(resp)
140
+ generations.append([Generation(text=text, message=resp)])
141
+ return LLMResult(generations=generations, llm_output=None)
142
+ self._wait()
143
+ return self._call(self._model.generate, messages, *args, **kwargs)
144
+
145
+ # ── Async entry points ──────────────────────────────────────────────
146
+ async def ainvoke(self, *args, **kwargs):
147
+ self._wait()
148
+ return await self._acall(self._model.ainvoke, *args, **kwargs)
149
+
150
+ async def agenerate(self, messages, *args, **kwargs):
151
+ if (
152
+ isinstance(messages, list)
153
+ and messages
154
+ and isinstance(messages[0], list)
155
+ ):
156
+ from langchain_core.outputs import Generation, LLMResult
157
+
158
+ generations = []
159
+ for msgs in messages:
160
+ self._wait()
161
+ # Same kwargs caveat as generate(): ainvoke has no callbacks.
162
+ resp = await self._acall(self._model.ainvoke, msgs)
163
+ text = resp.content if hasattr(resp, "content") else str(resp)
164
+ generations.append([Generation(text=text, message=resp)])
165
+ return LLMResult(generations=generations, llm_output=None)
166
+ self._wait()
167
+ return await self._acall(self._model.agenerate, messages, *args, **kwargs)
168
+
169
+ # ── Everything else passes through ──────────────────────────────────
170
+ def __getattr__(self, name: str):
171
+ return getattr(self._model, name)
172
+
173
+
174
+ def _wrap_evaluator(llm):
175
+ from ragas.llms import LangchainLLMWrapper
176
+ from ragas.run_config import RunConfig
177
+ return LangchainLLMWrapper(_ThrottledChatModel(llm), run_config=RunConfig(timeout=12, max_retries=1, max_wait=0, max_workers=1))
178
+
179
+
180
+ def _get_evaluator_llm(endpoint: Optional[str] = None):
181
+ """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
182
+
183
+ Priority:
184
+ 1. **Custom endpoint** β€” when *endpoint* names a configured
185
+ ``OCR_ENDPOINT_*`` config, it is used (any provider the user added).
186
+ 2. **Groq** (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
187
+ 3. **Google Gemini** (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``
188
+
189
+ Groq is preferred over Gemini because scoring fires many LLM calls per
190
+ review and the Gemini free tier (15 req/min) is already shared with the
191
+ main review pipeline β€” using Groq's separate quota pool avoids the 429
192
+ rate-limit failures that used to zero out the metrics.
193
+
194
+ RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
195
+ """
196
+ from ragas.llms import LangchainLLMWrapper
197
+
198
+ try:
199
+ if endpoint:
200
+ from llm_factory import create_llm
201
+ from endpoints import EndpointConfig, get_endpoint
202
+ configured = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
203
+ timeout = 15
204
+ if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
205
+ import httpx
206
+ # LangChain caches HTTP clients for hashable timeout values.
207
+ # An unhashable Timeout forces a private pool for this loop.
208
+ timeout = httpx.Timeout(15)
209
+ llm = create_llm(endpoint=endpoint, temperature=0, timeout=timeout, max_retries=0)
210
+ logger.info("RAGAS evaluator: using selected custom endpoint")
211
+ return _wrap_evaluator(llm)
212
+
213
+ from llm_factory import _get_groq_chat, _get_gemini_chat
214
+
215
+ # Keep evaluation bounded: RAGAS runs several provider calls and
216
+ # retrying each one can otherwise hold a review open for minutes.
217
+ configured_model = os.getenv("RAGAS_MODEL", "").strip()
218
+ if configured_model.startswith("groq/"):
219
+ configured_model = configured_model.split("/", 1)[1]
220
+ groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": 15}
221
+ if configured_model:
222
+ groq_kwargs["model"] = configured_model
223
+ llm = _get_groq_chat(**groq_kwargs)
224
+ if llm is None:
225
+ logger.info(
226
+ "RAGAS evaluator: GROQ_API_KEY not set β€” falling back to Gemini"
227
+ )
228
+ llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=15)
229
+ if llm is None:
230
+ raise ValueError(
231
+ "No LLM available for RAGAS scoring. "
232
+ "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
233
+ )
234
+ logger.info(
235
+ "RAGAS evaluator: using %s (throttled %ss)",
236
+ type(llm).__name__,
237
+ _RAGAS_INTERVAL,
238
+ )
239
+ return _wrap_evaluator(llm)
240
+ except ValueError as exc:
241
+ logger.warning("RAGAS evaluator: %s", exc)
242
+ raise RuntimeError(
243
+ "No LLM available for RAGAS scoring. "
244
+ "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
245
+ ) from exc
246
+
247
+
248
+ # ─── Score computation ─────────────────────────────────────────────────────
249
+
250
+
251
+ def _score_one_metric(name, sample, llm, timeout):
252
+ from ragas import metrics
253
+ from ragas.run_config import RunConfig
254
+ classes = {"context_precision": "LLMContextPrecisionWithoutReference", "faithfulness": "Faithfulness", "context_recall": "ContextRecall"}
255
+ scorer = getattr(metrics, classes[name])(llm=llm)
256
+ scorer.init(RunConfig(timeout=timeout, max_retries=1, max_wait=0, max_workers=1))
257
+ return float(scorer.single_turn_score(sample))
258
+
259
+
260
+ def _safe_metric_error(exc):
261
+ """Classify failures without exposing provider responses or credentials."""
262
+ chain = []
263
+ current = exc
264
+ while current is not None and len(chain) < 5:
265
+ chain.append(type(current).__name__.lower())
266
+ current = current.__cause__ or current.__context__
267
+ kinds = " ".join(chain)
268
+ if "timeout" in kinds:
269
+ return "timed_out", "Evaluator provider timed out. Retry or select a faster model."
270
+ if "connection" in kinds or "connecterror" in kinds:
271
+ return "failed", "Evaluator provider connection failed. Retry; check provider availability if it persists."
272
+ if "ratelimit" in kinds:
273
+ return "failed", "Evaluator provider rate limit reached. Wait or select another saved provider."
274
+ if "authentication" in kinds or "permission" in kinds:
275
+ return "failed", "Evaluator provider rejected access. Check the saved provider credentials and permissions."
276
+ return "failed", type(exc).__name__
277
+
278
+
279
+ def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None, *, metric_timeout=None, progress_callback=None):
280
+ """Run independent bounded RAGAS metrics, preserving successes and real failures.
281
+
282
+ No local embedding model is loaded. Lexical overlap is never substituted for
283
+ RAGAS. Input caps reduce judge latency and are disclosed in the report.
284
+ """
285
+ import math
286
+ import queue
287
+ from contextvars import copy_context
288
+ started = time.monotonic()
289
+ total_budget = max(1.0, float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "30")))
290
+ per_metric = max(.05, float(metric_timeout or os.getenv("OCR_RAGAS_METRIC_TIMEOUT_SECONDS", "12")))
291
+ names = ["context_precision", "faithfulness"]
292
+ if ground_truth:
293
+ names.append("context_recall")
294
+ report = {"scores": {}, "metrics": {}, "evaluation": {"engine": "RAGAS", "local_models": False, "metric_timeout_seconds": per_metric, "input_truncated": len(query) > 6000 or len(answer or "") > 4000 or len(retrieved_contexts) > 2 or any(len(c) > 4000 for c in retrieved_contexts)}}
295
+ def finish(name, status, value=None, error=None, duration=0):
296
+ report["metrics"][name] = {"status": status, "value": value, "error": error, "duration_seconds": round(duration, 3)}
297
+ if value is not None:
298
+ report["scores"][name] = value
299
+ if progress_callback:
300
+ progress_callback(report)
301
+ for name, reason in [("answer_relevancy", "Requires embeddings; local models are disabled"), ("mmr", "Extra judge calls disabled in hosted evaluation")]:
302
+ finish(name, "skipped", error=reason)
303
+ if not ground_truth:
304
+ finish("context_recall", "skipped", error="No reference answer provided")
305
+ if not answer or not retrieved_contexts:
306
+ for name in names:
307
+ finish(name, "skipped", error="A complete answer and context are required")
308
+ return report
309
+ try:
310
+ if not _check_ragas():
311
+ raise RuntimeError("RAGAS is not installed")
312
+ from ragas.dataset_schema import SingleTurnSample
313
+ sample = SingleTurnSample(user_input=query[:6000], response=answer[:4000], retrieved_contexts=[c[:4000] for c in retrieved_contexts[:2]], reference=ground_truth[:4000] if ground_truth else None)
314
+ except Exception as exc:
315
+ for name in names:
316
+ finish(name, "failed", error=type(exc).__name__)
317
+ return report
318
+ pending = {}
319
+ for name in names:
320
+ remaining = total_budget - (time.monotonic() - started) - 1
321
+ if remaining <= 0:
322
+ finish(name, "timed_out", error="Evaluation setup exhausted deadline")
323
+ continue
324
+ deadline = time.monotonic() + min(per_metric, remaining)
325
+ output = queue.Queue(maxsize=1)
326
+ def run(metric=name, target=output, limit=min(per_metric, remaining)):
327
+ metric_started = time.monotonic()
328
+ token = _metric_deadline.set(metric_started + limit)
329
+ try:
330
+ # Each metric runs its own asyncio loop. Sharing an async HTTP
331
+ # client across these threads can bind its pool to another loop.
332
+ llm = _get_evaluator_llm(endpoint=endpoint)
333
+ value = _score_one_metric(metric, sample, llm, limit)
334
+ if not math.isfinite(value) or not 0 <= value <= 1:
335
+ raise ValueError("Invalid metric value")
336
+ target.put(("completed", round(value, 4), None, time.monotonic() - metric_started))
337
+ except Exception as exc:
338
+ status, error = _safe_metric_error(exc)
339
+ logger.warning("RAGAS metric %s failed (%s)", metric, type(exc).__name__)
340
+ target.put((status, None, error, time.monotonic() - metric_started))
341
+ finally:
342
+ _metric_deadline.reset(token)
343
+ threading.Thread(target=copy_context().run, args=(run,), daemon=True).start()
344
+ pending[name] = (output, deadline)
345
+ while pending:
346
+ for name, (output, deadline) in list(pending.items()):
347
+ try:
348
+ status, value, error, duration = output.get_nowait()
349
+ except queue.Empty:
350
+ if time.monotonic() < deadline:
351
+ continue
352
+ status, value, error, duration = "timed_out", None, "Metric deadline exceeded", per_metric
353
+ finish(name, status, value, error, duration)
354
+ del pending[name]
355
+ if pending:
356
+ time.sleep(.01)
357
+ report["evaluation"]["duration_seconds"] = round(time.monotonic() - started, 3)
358
+ return report
359
+
360
+
361
+ def compute_ragas_retrieval_scores(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None):
362
+ """Compatibility mapping. Failed/skipped metrics remain None, never invented scores."""
363
+ report = compute_ragas_report(query, retrieved_contexts, ground_truth, answer, endpoint)
364
+ return {name: metric["value"] for name, metric in report["metrics"].items()}
365
+
366
+
367
+ def _create_ragas_embeddings():
368
+ """Return a lightweight embedding object compatible with RAGAS metrics.
369
+
370
+ Wraps the ChromaDB ONNX MiniLM embedding function so that metrics like
371
+ ``ResponseRelevancy`` can compute cosine similarity between embeddings.
372
+ The underlying ONNX model is cached globally and loads in <1 s.
373
+ """
374
+ if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
375
+ logger.info("Local RAGAS embeddings disabled; skipping answer relevancy")
376
+ return None
377
+ try:
378
+ from chromadb.utils import embedding_functions
379
+
380
+ if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
381
+ ef = embedding_functions.ONNXMiniLM_L6_V2()
382
+ else:
383
+ ef = embedding_functions.SentenceTransformerEmbeddingFunction(
384
+ model_name="all-MiniLM-L6-v2"
385
+ )
386
+
387
+ class _RagasEmbeddings:
388
+ def __init__(self, ef):
389
+ self._ef = ef
390
+
391
+ def embed_query(self, text: str) -> list[float]:
392
+ result = self._ef([text])[0]
393
+ return list(result) if not isinstance(result, list) else result
394
+
395
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
396
+ results = self._ef(texts)
397
+ return [list(r) if not isinstance(r, list) else r for r in results]
398
+
399
+ return _RagasEmbeddings(ef)
400
+ except Exception as exc:
401
+ logger.warning("Cannot create RAGAS embeddings: %s", exc)
402
+ return None
403
+
404
+
405
+ def _compute_mmr(
406
+ query: str,
407
+ retrieved_contexts: list[str],
408
+ llm: Any,
409
+ ) -> float:
410
+ """Compute Mean Reciprocal Rank β€” how early the first relevant chunk appears.
411
+
412
+ Uses the LLM to judge each chunk's relevance to the query in order.
413
+ The first chunk judged relevant determines the reciprocal rank:
414
+ ``1 / rank_of_first_relevant``. Returns 0.0 if none are relevant.
415
+
416
+ Parameters
417
+ ----------
418
+ query : str
419
+ The search query (PR diff).
420
+ retrieved_contexts : list[str]
421
+ Ranked list of retrieved code chunks.
422
+ llm : LangchainLLMWrapper
423
+ RAGAS-wrapped LLM for relevance judgments.
424
+
425
+ Returns
426
+ -------
427
+ float
428
+ MMR score in [0, 1]; 0.0 when chunks were judged but none were
429
+ relevant.
430
+
431
+ Raises
432
+ ------
433
+ RuntimeError
434
+ If every relevance judgment failed (e.g. LLM rate-limited) β€”
435
+ callers treat this as a failed metric rather than a fake 0.0.
436
+ """
437
+ if not retrieved_contexts:
438
+ return 0.0
439
+
440
+ # Score up to the first 5 chunks for relevance using the LLM.
441
+ # Top-5 MMR is standard β€” rank 5 yields 1/5 = 0.20, and
442
+ # anything beyond rank 5 barely changes the score anyway.
443
+ MAX_MMR_RANK = 2
444
+ top_chunks = retrieved_contexts[:MAX_MMR_RANK]
445
+
446
+ judged = 0
447
+ for rank, chunk in enumerate(top_chunks, start=1):
448
+ try:
449
+ prompt = (
450
+ f"Is the following code/document chunk relevant to the question?\n\n"
451
+ f"Question: {query[:2_000]}\n\n"
452
+ f"Chunk: {chunk[:2_000]}\n\n"
453
+ f"Answer with exactly one word: YES or NO"
454
+ )
455
+ # Use the wrapped LangChain model for fast synchronous invoke.
456
+ # LangchainLLMWrapper stores the model as .langchain_llm in ragas
457
+ # 0.4.x and as .llm in 0.3.x β€” accept both.
458
+ langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
459
+ # Space the relevance judgments too β€” this unwrapped path bypasses
460
+ # the model wrapper on some ragas versions, so sleep explicitly
461
+ # (unless the wrapper is already in the path, to avoid double-sleep).
462
+ if not isinstance(langchain_model, _ThrottledChatModel):
463
+ time.sleep(_RAGAS_INTERVAL)
464
+ raw = langchain_model.invoke(prompt)
465
+ response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
466
+ if response_text.startswith("Y"):
467
+ return 1.0 / rank
468
+ judged += 1 # judge responded β€” chunk deemed not relevant
469
+ except Exception:
470
+ continue
471
+
472
+ if judged == 0:
473
+ # Every relevance judgment failed (e.g. LLM rate-limited) β€” surface
474
+ # this as a failed metric instead of a misleading 0.0.
475
+ raise RuntimeError("all MMR relevance judgments failed")
476
+
477
+ return 0.0
478
+
479
+
480
+ def log_ragas_scores_to_langfuse(
481
+ scores: dict[str, float | None],
482
+ repo: str = "",
483
+ pr_number: int = 0,
484
+ handler: Any = None,
485
+ ) -> None:
486
+ """Log RAGAS metrics as Langfuse scores (linked to the review trace).
487
+
488
+ Parameters
489
+ ----------
490
+ scores : dict
491
+ Output of :func:`compute_ragas_retrieval_scores`.
492
+ repo : str
493
+ GitHub repository name (e.g. ``\"psf/requests\"``).
494
+ pr_number : int
495
+ Pull request number.
496
+ handler : Langfuse CallbackHandler or None
497
+ Handler from the current review run, used to link scores to the trace.
498
+ """
499
+ try:
500
+ from observability import log_langfuse_score
501
+ except ImportError:
502
+ logger.debug("observability module not available β€” skipping Langfuse")
503
+ return
504
+
505
+ for metric_name, value in scores.items():
506
+ if value is None:
507
+ continue
508
+ log_langfuse_score(
509
+ name=f"ragas_{metric_name}",
510
+ value=value,
511
+ comment=f"{repo}#{pr_number} β€” {metric_name}",
512
+ handler=handler,
513
+ )
514
+
515
+
516
+ # ─── Standalone CLI ─────────────────────────────────────────────────────────
517
+
518
+
519
+ def main() -> None:
520
+ """CLI entry point: compute RAGAS scores from a JSONL dataset.
521
+
522
+ Usage::
523
+
524
+ python eval_data/ragas_eval.py --data eval_data/prs.jsonl
525
+ """
526
+ import argparse
527
+ import json
528
+
529
+ parser = argparse.ArgumentParser(
530
+ description="Compute RAGAS retrieval quality scores on evaluation data",
531
+ )
532
+ parser.add_argument(
533
+ "--data", default=None,
534
+ help="Path to JSONL dataset (same format as evaluate.py)",
535
+ )
536
+ parser.add_argument(
537
+ "--output", default=None,
538
+ help="Path to write per-PR RAGAS scores (JSON)",
539
+ )
540
+ parser.add_argument(
541
+ "--max-prs", type=int, default=None,
542
+ help="Max PRs to process",
543
+ )
544
+ parser.add_argument(
545
+ "--log-to-observability", action="store_true",
546
+ help="Log RAGAS scores to Langfuse",
547
+ )
548
+ args = parser.parse_args()
549
+
550
+ logging.basicConfig(
551
+ level=logging.INFO,
552
+ format="%(asctime)s [%(levelname)s] %(name)s β€” %(message)s",
553
+ )
554
+
555
+ if not args.data:
556
+ # If no data file specified, try default location
557
+ default_path = os.path.join(
558
+ os.path.dirname(__file__), "prs.jsonl"
559
+ )
560
+ if os.path.exists(default_path):
561
+ args.data = default_path
562
+ else:
563
+ logger.error(
564
+ "No --data provided and default not found at %s. "
565
+ "Run eval_data/fetcher.py first.",
566
+ default_path,
567
+ )
568
+ return
569
+
570
+ with open(args.data, "r", encoding="utf-8") as f:
571
+ entries = [json.loads(line) for line in f if line.strip()]
572
+
573
+ if args.max_prs:
574
+ entries = entries[: args.max_prs]
575
+
576
+ all_scores: list[dict] = []
577
+ for entry in entries:
578
+ repo = entry.get("repo", "?")
579
+ pr = entry.get("pr_number", 0)
580
+ diff = entry.get("diff", "")
581
+ ground_truth_list = entry.get("ground_truth", [])
582
+
583
+ # Use the diff as the query, and first few human comments
584
+ # as a proxy for "what the retrieval should have found"
585
+ query = diff[:8_000] if diff else entry.get("title", "")
586
+ gt_text = (
587
+ " ".join(
588
+ g.get("comment", "")
589
+ for g in ground_truth_list[:5]
590
+ )
591
+ if ground_truth_list
592
+ else None
593
+ )
594
+
595
+ # Retrieved contexts come from the graph run, but for the CLI
596
+ # we don't re-run the graph β€” we just skip if no retrieval data
597
+ # is available in the entry.
598
+ stored_contexts = entry.get("retrieved_contexts", [])
599
+ if not stored_contexts:
600
+ logger.info(
601
+ "[%s#%d] No stored retrieval contexts β€” skipping RAGAS",
602
+ repo, pr,
603
+ )
604
+ continue
605
+
606
+ logger.info("[%s#%d] Computing RAGAS scores …", repo, pr)
607
+ try:
608
+ scores = compute_ragas_retrieval_scores(
609
+ query=query,
610
+ retrieved_contexts=stored_contexts,
611
+ ground_truth=gt_text,
612
+ )
613
+ except RuntimeError as exc:
614
+ logger.warning("[%s#%d] %s", repo, pr, exc)
615
+ break
616
+
617
+ scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
618
+ all_scores.append(scores)
619
+
620
+ if args.log_to_observability:
621
+ log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)
622
+
623
+ print(
624
+ f" {repo}#{pr}: "
625
+ + " | ".join(
626
+ f"{k}={v:.3f}" for k, v in scores.items()
627
+ if k not in ("repo", "pr_number", "id") and v is not None
628
+ )
629
+ )
630
+
631
+ # Print aggregate
632
+ if all_scores:
633
+ print()
634
+ print("=" * 60)
635
+ print(" Aggregate RAGAS scores")
636
+ print("=" * 60)
637
+ metrics = [
638
+ k for k in all_scores[0].keys()
639
+ if k not in ("repo", "pr_number", "id")
640
+ ]
641
+ for metric in metrics:
642
+ values = [
643
+ s.get(metric) for s in all_scores
644
+ if s.get(metric) is not None
645
+ ]
646
+ if not values:
647
+ print(f" {metric:30s}: n/a (no successful scores)")
648
+ continue
649
+ avg = sum(values) / len(values)
650
+ print(f" {metric:30s}: {avg:.4f} (over {len(values)} PRs)")
651
+ print()
652
+
653
+ # Save output
654
+ if args.output and all_scores:
655
+ with open(args.output, "w", encoding="utf-8") as f:
656
+ json.dump(all_scores, f, indent=2)
657
+ logger.info("Saved RAGAS scores to %s", args.output)
658
+
659
+
660
+ if __name__ == "__main__":
661
+ main()
frontend/src/main.jsx CHANGED
@@ -174,7 +174,7 @@ function App() {
174
  } catch (err) { setError(err.message); } finally { setBusy(false); }
175
  }
176
  async function decide(action) { if (!job?.id) return; setBusy(true); setError(""); setMessage(action === "approve" ? "Posting approved review…" : "Rejecting review…"); try { const r = await fetch(apiUrl(`/api/reviews/${job.id}/decision`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action }) }); const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.detail || `Decision failed (${r.status})`); setJob(data); setMessage(action === "approve" ? "Review delivery finished." : "Review rejected. Nothing was posted to GitHub."); } catch (e) { setError(e.message); } finally { setBusy(false); } }
177
- return <div className="shell"><header className="topbar"><div className="brand"><span className="brand-mark">OC</span><span>OpenCodeReview</span></div><div>{user ? <><span className="status-dot">Signed in as {user.login}</span><button className="auth-button" onClick={logout}>Sign out</button></> : <a className="status-dot" href={`${API_BASE}/api/auth/github/start`}>Sign in with GitHub</a>}<span className="status-dot">Human approval required</span><button className="theme-toggle" type="button" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label="Toggle color theme">{theme === "dark" ? "Light" : "Dark"}</button></div></header><main className="content"><section className="hero"><p className="eyebrow">Pull request intelligence</p><h1>Review changes with<br /><em>evidence before action.</em></h1><p className="lede">Parallel analysis for correctness, security, and test coverage. Nothing is posted to GitHub until you approve it.</p></section><section className="intro-band"><div className="intro-copy"><p className="eyebrow">AI code review with a human checkpoint</p><h2>Know what changed<br /><em>before it ships.</em></h2><p>OpenCodeReview traces pull requests back to the diff, checks correctness and security, then gives you the evidence to decide what reaches GitHub.</p><div className="intro-actions"><a className="primary-link" href={user ? "#new-review" : `${API_BASE}/api/auth/github/start`}>Start a review <span>&rarr;</span></a><a className="quiet-link" href="#how-it-works">See how it works</a></div></div><div className="review-preview" aria-label="Review workflow preview"><div className="preview-top"><span className="live-dot"></span><span>REVIEW PIPELINE</span><span className="preview-time">LIVE</span></div><div className="preview-row"><strong>01</strong><span><b>Read the diff</b><small>Files, lines, and context</small></span><i>done</i></div><div className="preview-row"><strong>02</strong><span><b>Cross-check findings</b><small>Evidence, severity, confidence</small></span><i>done</i></div><div className="preview-row active"><strong>03</strong><span><b>Your decision</b><small>Approve, reject, or inspect</small></span><i>waiting</i></div></div></section><section className="trust-strip" id="how-it-works"><div><strong>Evidence first</strong><span>Every finding points to code.</span></div><div><strong>Human controlled</strong><span>Nothing posts without approval.</span></div><div><strong>Measurable quality</strong><span>RAGAS scores show retrieval quality.</span></div></section>{user ? <section className="workspace" id="new-review"><nav className="workspace-tabs" aria-label="Workspace"><button type="button" className={activeTab === "review" ? "active" : ""} onClick={() => { setActiveTab("review"); setError(""); setMessage(""); }}>Review</button><button type="button" className={activeTab === "providers" ? "active" : ""} onClick={() => { setActiveTab("providers"); setError(""); setMessage(""); }}>Providers</button></nav>{activeTab === "providers" && <section className="panel provider-manager" id="providers"><div className="panel-kicker">Provider library</div><h2>Saved providers</h2><p className="provider-hint">Keep your model connections ready for future reviews.</p>{savedProviders.length ? <div className="saved-provider-list">{savedProviders.map(item => <div className="saved-provider" key={item.name}><div className="provider-entry-title"><strong>{item.name}</strong>{defaultProvider === item.name && <span className="pill">Default</span>}</div><small>{item.baseUrl || "Default API endpoint"}</small><small>{item.lastTest ? `Last successful connection: ${new Date(item.lastTest.at).toLocaleString()} Β· ${(Number(item.lastTest.latency_ms) / 1000).toFixed(1)}s Β· JSON ${item.lastTest.json_valid ? "valid" : "invalid"}` : "Connection has not been tested"}</small><div className="provider-entry-actions"><button type="button" onClick={() => editProvider(item)} aria-label={`Edit ${item.name}`}>Edit</button><button type="button" onClick={() => makeDefault(item)} disabled={defaultProvider === item.name} aria-label={`Make ${item.name} default`}>Make default</button><button type="button" onClick={() => removeProvider(item)} aria-label={`Delete ${item.name}`}>Delete</button></div></div>)}</div> : <p className="provider-hint">No providers saved yet.</p>}<div className="provider-form-heading"><h3>{editingProvider ? "Edit provider" : "Add a provider"}</h3>{editingProvider && <button type="button" onClick={resetProviderDraft}>New provider</button>}</div><p className="provider-hint">Saved on this browser. Keys are hidden from the list and sent only when a provider is tested or used.</p><label htmlFor="provider-manager-type">Provider type<select id="provider-manager-type" value={provider || "openai"} onChange={e => setProvider(e.target.value)}><option value="openai">OpenAI-compatible</option><option value="anthropic">Anthropic</option><option value="google">Google</option></select></label><label htmlFor="provider-manager-model">Model<input id="provider-manager-model" value={model} onChange={e => setModel(e.target.value)} placeholder="model-name" /></label><label htmlFor="provider-manager-key">API key<input id="provider-manager-key" type="password" value={apiKey} onChange={e => setApiKey(e.target.value)} placeholder="Used for reviews" /></label><label htmlFor="provider-manager-base">Base URL <span>(optional)</span><input id="provider-manager-base" value={baseUrl} onChange={e => setBaseUrl(e.target.value)} placeholder="https://api.example.com/v1" /></label><div className="provider-actions"><button type="button" onClick={testProvider} disabled={testingProvider}>{testingProvider ? "Testing…" : "Test speed & JSON"}</button><button type="button" onClick={addProvider}>{editingProvider ? "Save changes" : "Add provider"}<span>οΌ‹</span></button></div>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}</section>}<form className={`panel form-panel ${activeTab === "providers" ? "is-hidden" : ""}`} onSubmit={startReview} aria-busy={busy}><div className="panel-kicker">New review</div><h2>Inspect a pull request</h2><label htmlFor="repo">Repository<input id="repo" value={repo} onChange={e => setRepo(e.target.value)} placeholder="owner/repository" autoComplete="off" /></label><label htmlFor="pr">Pull request<input id="pr" value={pr} onChange={e => setPr(e.target.value)} placeholder="42" inputMode="numeric" /></label><label htmlFor="endpoint">Provider<select id="endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)}><option value="auto">Automatic fallback</option><option value="gemini">Gemini</option><option value="groq">Groq</option>{savedProviders.map(item => <option key={item.name} value={`saved:${item.name}`}>{item.name}</option>)}</select></label><fieldset className="review-mode"><legend>Review depth</legend><label><input type="radio" name="review-mode" value="fast" checked={reviewMode === "fast"} onChange={() => setReviewMode("fast")} />Fast<span>Smaller prompts and response budget</span></label><label><input type="radio" name="review-mode" value="thorough" checked={reviewMode === "thorough"} onChange={() => setReviewMode("thorough")} />Thorough<span>More context and analysis</span></label></fieldset><details className="incremental-options"><summary>Review only changes since a commit</summary><label htmlFor="baseline-sha">Previously reviewed commit SHA<input id="baseline-sha" value={baselineSha} onChange={e => setBaselineSha(e.target.value)} placeholder="40-character commit SHA (optional)" pattern="[a-fA-F0-9]{40}" autoComplete="off" /></label><p className="provider-hint">When set, this reviews only changes since that commit, not the whole pull request.</p></details><button type="submit" disabled={busy}>{busy && !job ? "Queueing review…" : "Start review"}<span aria-hidden="true">β†—</span></button>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}{job && <div className="job-card"><div><strong>Review {job.id?.slice(0, 8)}</strong><small>{job.repo} Β· PR #{job.pr_number}</small></div><span className={`pill ${job.status}`}>{pretty(job.status)}</span></div>}{job && !isTerminal && <div className="progress" role="progressbar" aria-label={`Review ${pretty(job.status)}`}><span /><small>{job.queue_position ? `Queue position: ${job.queue_position}` : `Current stage: ${pretty(job.progress?.stage || job.status)}`}</small><button type="button" className="secondary" onClick={cancelReview} disabled={busy}>Cancel review</button></div>}<div className="results"><ReviewProgress job={job} /><Verdict job={job} /><Coverage coverage={job?.review_coverage || job?.coverage} /><Ragas ragas={job?.ragas} />{job?.findings?.length > 0 && <Findings findings={job.findings} feedback={job.feedback} onFeedback={isTerminal ? saveFeedback : undefined} feedbackBusy={feedbackBusy} />}{job?.status === "awaiting_approval" && job?.findings?.length === 0 && <Findings findings={[]} />}{job?.status === "awaiting_approval" && <div className="actions"><button type="button" onClick={() => decide("approve")} disabled={busy}>Approve &amp; post</button><button type="button" className="secondary" onClick={() => decide("reject")} disabled={busy}>Reject</button></div>}<Receipt result={job?.posting_result} />{job?.error && <div className="error detail">{job.error}</div>}</div></form><aside className={`panel signal-panel ${activeTab === "providers" ? "is-hidden" : ""}`}><div className="panel-kicker">What you receive</div><div className="signal"><strong>01</strong><span><b>Evidence-grounded findings</b><small>Code locations, severity, and confidence</small></span></div><div className="signal"><strong>02</strong><span><b>Human checkpoint</b><small>Approve or reject before GitHub comments</small></span></div><div className="signal"><strong>03</strong><span><b>Delivery receipt</b><small>See exactly what reached GitHub</small></span></div></aside></section> : <section className="auth-wall"><p className="eyebrow">Private review workspace</p><h2>Sign in to inspect a pull request.</h2><p>Your GitHub identity keeps reviews tied to your account and protects the review results.</p><a className="primary-link" href={`${API_BASE}/api/auth/github/start`}>Continue with GitHub <span>&rarr;</span></a></section>}</main><footer>OpenCodeReview <span>Β·</span> React review workspace <span>Β·</span> API keys stay server-side</footer></div>;
178
  }
179
  createRoot(document.getElementById("root")).render(<App />);
180
 
 
174
  } catch (err) { setError(err.message); } finally { setBusy(false); }
175
  }
176
  async function decide(action) { if (!job?.id) return; setBusy(true); setError(""); setMessage(action === "approve" ? "Posting approved review…" : "Rejecting review…"); try { const r = await fetch(apiUrl(`/api/reviews/${job.id}/decision`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action }) }); const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.detail || `Decision failed (${r.status})`); setJob(data); setMessage(action === "approve" ? "Review delivery finished." : "Review rejected. Nothing was posted to GitHub."); } catch (e) { setError(e.message); } finally { setBusy(false); } }
177
+ return <div className="shell"><header className="topbar"><div className="brand"><span className="brand-mark">OC</span><span>OpenCodeReview</span></div><div>{user ? <><span className="status-dot">Signed in as {user.login}</span><button className="auth-button" onClick={logout}>Sign out</button></> : <a className="status-dot" href={`${API_BASE}/api/auth/github/start`}>Sign in with GitHub</a>}<span className="status-dot">Human approval required</span><button className="theme-toggle" type="button" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label="Toggle color theme">{theme === "dark" ? "Light" : "Dark"}</button></div></header><main className="content"><section className="hero"><p className="eyebrow">Pull request intelligence</p><h1>Review changes with<br /><em>evidence before action.</em></h1><p className="lede">Parallel analysis for correctness, security, and test coverage. Nothing is posted to GitHub until you approve it.</p></section><section className="intro-band"><div className="intro-copy"><p className="eyebrow">AI code review with a human checkpoint</p><h2>Know what changed<br /><em>before it ships.</em></h2><p>OpenCodeReview traces pull requests back to the diff, checks correctness and security, then gives you the evidence to decide what reaches GitHub.</p><div className="intro-actions"><a className="primary-link" href={user ? "#new-review" : `${API_BASE}/api/auth/github/start`}>Start a review <span>&rarr;</span></a><a className="quiet-link" href="#how-it-works">See how it works</a></div></div><div className="review-preview" aria-label="Review workflow preview"><div className="preview-top"><span className="live-dot"></span><span>REVIEW PIPELINE</span><span className="preview-time">LIVE</span></div><div className="preview-row"><strong>01</strong><span><b>Read the diff</b><small>Files, lines, and context</small></span><i>done</i></div><div className="preview-row"><strong>02</strong><span><b>Cross-check findings</b><small>Evidence, severity, confidence</small></span><i>done</i></div><div className="preview-row active"><strong>03</strong><span><b>Your decision</b><small>Approve, reject, or inspect</small></span><i>waiting</i></div></div></section><section className="trust-strip" id="how-it-works"><div><strong>Evidence first</strong><span>Every finding points to code.</span></div><div><strong>Human controlled</strong><span>Nothing posts without approval.</span></div><div><strong>Measurable quality</strong><span>RAGAS scores show retrieval quality.</span></div></section>{user ? <section className="workspace" id="new-review"><nav className="workspace-tabs" aria-label="Workspace"><button type="button" className={activeTab === "review" ? "active" : ""} onClick={() => { setActiveTab("review"); setError(""); setMessage(""); }}>Review</button><button type="button" className={activeTab === "providers" ? "active" : ""} onClick={() => { setActiveTab("providers"); setError(""); setMessage(""); }}>Providers</button></nav>{activeTab === "providers" && <section className="panel provider-manager" id="providers"><div className="panel-kicker">Provider library</div><h2>Saved providers</h2><p className="provider-hint">Keep your model connections ready for future reviews.</p>{savedProviders.length ? <div className="saved-provider-list">{savedProviders.map(item => <div className="saved-provider" key={item.name}><div className="provider-entry-title"><strong>{item.name}</strong>{defaultProvider === item.name && <span className="pill">Default</span>}</div><small>{item.baseUrl || "Default API endpoint"}</small><small>{item.lastTest ? `Last successful connection: ${new Date(item.lastTest.at).toLocaleString()} Β· ${(Number(item.lastTest.latency_ms) / 1000).toFixed(1)}s Β· JSON ${item.lastTest.json_valid ? "valid" : "invalid"}` : "Connection has not been tested"}</small><div className="provider-entry-actions"><button type="button" onClick={() => editProvider(item)} aria-label={`Edit ${item.name}`}>Edit</button><button type="button" onClick={() => makeDefault(item)} disabled={defaultProvider === item.name} aria-label={`Make ${item.name} default`}>Make default</button><button type="button" onClick={() => removeProvider(item)} aria-label={`Delete ${item.name}`}>Delete</button></div></div>)}</div> : <p className="provider-hint">No providers saved yet.</p>}<div className="provider-form-heading"><h3>{editingProvider ? "Edit provider" : "Add a provider"}</h3>{editingProvider && <button type="button" onClick={resetProviderDraft}>New provider</button>}</div><p className="provider-hint">Saved on this browser. Keys are hidden from the list and sent only when a provider is tested or used.</p><label htmlFor="provider-manager-type">Provider type<select id="provider-manager-type" value={provider || "openai"} onChange={e => setProvider(e.target.value)}><option value="openai">OpenAI-compatible</option><option value="anthropic">Anthropic</option><option value="google">Google</option></select></label><label htmlFor="provider-manager-model">Model<input id="provider-manager-model" value={model} onChange={e => setModel(e.target.value)} placeholder="model-name" /></label><label htmlFor="provider-manager-key">API key<input id="provider-manager-key" type="password" value={apiKey} onChange={e => setApiKey(e.target.value)} placeholder="Used for reviews" /></label><label htmlFor="provider-manager-base">Base URL <span>(optional)</span><input id="provider-manager-base" value={baseUrl} onChange={e => setBaseUrl(e.target.value)} placeholder="https://api.example.com/v1" /></label><div className="provider-actions"><button type="button" onClick={testProvider} disabled={testingProvider}>{testingProvider ? "Testing…" : "Test speed & JSON"}</button><button type="button" onClick={addProvider}>{editingProvider ? "Save changes" : "Add provider"}<span>οΌ‹</span></button></div>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}</section>}<form className={`panel form-panel ${activeTab === "providers" ? "is-hidden" : ""}`} onSubmit={startReview} aria-busy={busy}><div className="panel-kicker">New review</div><h2>Inspect a pull request</h2><label htmlFor="repo">Repository<input id="repo" value={repo} onChange={e => setRepo(e.target.value)} placeholder="owner/repository" autoComplete="off" /></label><label htmlFor="pr">Pull request<input id="pr" value={pr} onChange={e => setPr(e.target.value)} placeholder="42" inputMode="numeric" /></label><label htmlFor="endpoint">Provider<select id="endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)}><option value="auto">Automatic fallback</option><option value="gemini">Gemini</option><option value="groq">Groq</option>{savedProviders.map(item => <option key={item.name} value={`saved:${item.name}`}>{item.name}</option>)}</select></label><fieldset className="review-mode"><legend>Review depth</legend><label><input type="radio" name="review-mode" value="fast" checked={reviewMode === "fast"} onChange={() => setReviewMode("fast")} />Fast<span>Smaller prompts and response budget</span></label><label><input type="radio" name="review-mode" value="thorough" checked={reviewMode === "thorough"} onChange={() => setReviewMode("thorough")} />Thorough<span>More context and analysis</span></label></fieldset><details className="incremental-options"><summary>Review only changes since a commit</summary><label htmlFor="baseline-sha">Previously reviewed commit SHA<input id="baseline-sha" value={baselineSha} onChange={e => setBaselineSha(e.target.value)} placeholder="40-character commit SHA (optional)" pattern="[a-fA-F0-9]{40}" autoComplete="off" /></label><p className="provider-hint">When set, this reviews only changes since that commit, not the whole pull request.</p></details><button type="submit" disabled={busy}>{busy && !job ? "Queueing review…" : "Start review"}<span aria-hidden="true">β†—</span></button>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}{job && <div className="job-card"><div><strong>Review {job.id?.slice(0, 8)}</strong><small>{job.repo} Β· PR #{job.pr_number}</small></div><span className={`pill ${job.status}`}>{pretty(job.status)}</span></div>}{job && !isTerminal && <div className="progress" role="progressbar" aria-label={`Review ${pretty(job.status)}`}><span /><small>{job.queue_position ? `Queue position: ${job.queue_position}` : `Current stage: ${pretty(job.progress?.stage || job.status)}`}</small><button type="button" className="secondary" onClick={cancelReview} disabled={busy}>Cancel review</button></div>}<div className="results"><ReviewProgress job={job} /><Verdict job={job} /><Coverage coverage={job?.review_coverage || job?.coverage} /><Ragas ragas={job?.ragas} />{job?.findings?.length > 0 && <Findings findings={job.findings} feedback={job.feedback} onFeedback={isTerminal ? saveFeedback : undefined} feedbackBusy={feedbackBusy} />}{job?.status === "awaiting_approval" && job?.findings?.length === 0 && <Findings findings={[]} />}{job?.status === "awaiting_approval" && <div className="actions"><button type="button" onClick={() => decide("approve")} disabled={busy}>Approve &amp; post</button><button type="button" className="secondary" onClick={() => decide("reject")} disabled={busy}>Reject</button></div>}<Receipt result={job?.posting_result} />{job?.error && <div className="error detail">{job.error}</div>}</div></form><aside className={`panel signal-panel ${activeTab === "providers" ? "is-hidden" : ""}`}><div className="panel-kicker">What you receive</div><div className="signal"><strong>01</strong><span><b>Evidence-grounded findings</b><small>Code locations, severity, and confidence</small></span></div><div className="signal"><strong>02</strong><span><b>Human checkpoint</b><small>Approve or reject before GitHub comments</small></span></div><div className="signal"><strong>03</strong><span><b>Delivery receipt</b><small>See exactly what reached GitHub</small></span></div></aside></section> : <section className="auth-wall"><p className="eyebrow">Private review workspace</p><h2>Sign in to inspect a pull request.</h2><p>Your GitHub identity keeps reviews tied to your account and protects the review results.</p><a className="primary-link" href={`${API_BASE}/api/auth/github/start`}>Continue with GitHub <span>&rarr;</span></a></section>}</main><footer>OpenCodeReview <span>Β·</span> React review workspace <span>Β·</span> Saved keys stay in this browser</footer></div>;
178
  }
179
  createRoot(document.getElementById("root")).render(<App />);
180
 
nodes/aggregator.py CHANGED
@@ -1,291 +1,291 @@
1
- from __future__ import annotations
2
-
3
- import logging
4
- import os
5
- from pathlib import Path
6
-
7
- from llm_factory import create_llm
8
- from nodes.finding_quality import calibrate_findings, review_coverage
9
- from pydantic import BaseModel, Field
10
-
11
- from state import Finding, OpenCodeReviewState, Severity, Verdict
12
-
13
- logger = logging.getLogger(__name__)
14
-
15
- GROQ_MODEL = "llama-3.3-70b-versatile"
16
- DEFAULT_TEMPERATURE = 0.0
17
-
18
- # Prompt version β€” tied to the file on disk
19
- PROMPT_VERSION = "v1"
20
- PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"aggregator_{PROMPT_VERSION}.txt"
21
-
22
- # Findings below this confidence are dropped before the LLM step
23
- MIN_CONFIDENCE = 0.25
24
- # Files/line pairs within this many lines are considered duplicates
25
- LINE_TOLERANCE = 5
26
-
27
- # Default to rule-based aggregation (skips expensive LLM critic call).
28
- # Set AGGREGATOR_USE_LLM_CRITIC=true in env to re-enable the LLM pass.
29
- USE_LLM_CRITIC = os.environ.get("AGGREGATOR_USE_LLM_CRITIC", "").lower() in ("1", "true", "yes")
30
-
31
-
32
- # ─── Load prompt from file ──────────────────────────────────────────────────
33
-
34
-
35
- def _load_prompt() -> str:
36
- """Load the system prompt from the versioned prompt file."""
37
- try:
38
- return PROMPT_FILE.read_text(encoding="utf-8")
39
- except FileNotFoundError:
40
- logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
41
- return (
42
- "You are a senior engineer acting as a critic of a code review. "
43
- "Filter out noise, deduplicate findings, and produce a verdict. "
44
- "Return the filtered list of findings plus your verdict."
45
- )
46
-
47
-
48
- SYSTEM_PROMPT = _load_prompt()
49
-
50
-
51
- # ─── LLM output schema ──────────────────────────────────────────────────────
52
-
53
-
54
- class AggregatedReview(BaseModel):
55
- """Final, noise-filtered findings and overall verdict."""
56
- findings: list[Finding] = Field(
57
- default_factory=list,
58
- description="Deduplicated, noise-filtered findings worth a senior engineer's time.",
59
- )
60
- verdict: Verdict = Field(
61
- description="Overall PR verdict after considering all findings.",
62
- )
63
-
64
-
65
- # ─── Pre-LLM heuristic deduplication ────────────────────────────────────────
66
-
67
-
68
- def _deduplicate(findings: list[Finding]) -> list[Finding]:
69
- """Heuristic dedup: group by ``(file_path, line_start)`` with a line
70
- tolerance, keeping the highest-confidence finding per group."""
71
- if not findings:
72
- return []
73
-
74
- # Sort by (file, line_start) so we can iterate and merge neighbours
75
- sorted_fs = sorted(findings, key=lambda f: (f.file_path, f.line_start))
76
-
77
- merged: list[Finding] = []
78
- current: Finding = sorted_fs[0]
79
-
80
- for f in sorted_fs[1:]:
81
- same_file = f.file_path == current.file_path
82
- close_lines = abs(f.line_start - current.line_start) <= LINE_TOLERANCE
83
- same_claim = " ".join(f.comment.lower().split()) == " ".join(current.comment.lower().split())
84
- if same_file and close_lines and f.kind == current.kind and f.category == current.category and same_claim:
85
- # Keep the higher-confidence finding, merge comments
86
- if f.confidence > current.confidence:
87
- current = f
88
- if current.confidence < 0.9:
89
- current.confidence = round(
90
- (current.confidence + f.confidence) / 2, 2
91
- )
92
- # Prefer the specific comment over a generic one
93
- if len(f.comment) > len(current.comment):
94
- current.comment = f.comment
95
- if f.suggested_fix and not current.suggested_fix:
96
- current.suggested_fix = f.suggested_fix
97
- # Escalate severity if either finding is more severe
98
- current.severity = _more_severe(current.severity, f.severity)
99
- else:
100
- merged.append(current)
101
- current = f
102
- merged.append(current)
103
-
104
- # Drop low-confidence noise
105
- merged = [f for f in merged if f.confidence >= MIN_CONFIDENCE]
106
-
107
- return merged
108
-
109
-
110
- _SEVERITY_ORDER = {
111
- Severity.CRITICAL: 0,
112
- Severity.HIGH: 1,
113
- Severity.MEDIUM: 2,
114
- Severity.LOW: 3,
115
- Severity.INFO: 4,
116
- }
117
-
118
-
119
- def _more_severe(a: Severity, b: Severity) -> Severity:
120
- return a if _SEVERITY_ORDER.get(a, 5) < _SEVERITY_ORDER.get(b, 5) else b
121
-
122
-
123
- # ─── Rule-based fallback verdict ────────────────────────────────────────────
124
-
125
-
126
- def _rule_verdict(findings: list[Finding]) -> Verdict:
127
- """Build a verdict from deduplicated findings without an LLM call."""
128
- eligible = [f for f in findings if f.kind != "test_suggestion" and f.evidence_status == "source_grounded"]
129
- suggestions = sum(f.kind == "test_suggestion" for f in findings)
130
- unverified = sum(f.kind != "test_suggestion" and f.evidence_status != "source_grounded" for f in findings)
131
- counts = {s: 0 for s in Severity}
132
- for f in eligible:
133
- counts[f.severity] = counts.get(f.severity, 0) + 1
134
-
135
- critical = counts[Severity.CRITICAL]
136
- high = counts[Severity.HIGH]
137
-
138
- if critical > 0:
139
- recommendation = "block"
140
- approved = False
141
- elif high > 0:
142
- recommendation = "request_changes"
143
- approved = False
144
- elif eligible or suggestions or unverified:
145
- recommendation = "comment"
146
- approved = True
147
- else:
148
- recommendation = "approve"
149
- approved = True
150
-
151
- # Score: 10 - penalty based on severity
152
- score = max(0.0, min(10.0, 10.0 - critical * 4.0 - high * 2.0 - counts.get(Severity.MEDIUM, 0) * 0.5))
153
-
154
- severity_counts = {s.value: counts.get(s, 0) for s in Severity}
155
-
156
- return Verdict(
157
- summary=_rule_summary(recommendation, severity_counts) + (f" {suggestions} test suggestion(s), {unverified} unverified claim(s) are excluded from the score." if suggestions or unverified else ""),
158
- approved=approved,
159
- overall_score=round(score, 1),
160
- critical_count=critical,
161
- high_count=high,
162
- recommendation=recommendation,
163
- score_explanation="Risk estimate from source-grounded findings, not answer correctness or proof of safety. Test suggestions and claims without source grounding do not lower the score.",
164
- score_breakdown={"starting_score": 10, "critical_penalty": critical * 4, "high_penalty": high * 2,
165
- "medium_penalty": counts[Severity.MEDIUM] * .5, "scored_findings": len(eligible),
166
- "test_suggestions_excluded": suggestions, "unverified_claims_excluded": unverified},
167
- )
168
-
169
-
170
- def _rule_summary(recommendation: str, counts: dict) -> str:
171
- parts = [f"{v} {k}" for k, v in counts.items() if v > 0]
172
- if not parts:
173
- return "No source-grounded defects detected. This does not establish that the PR is safe."
174
- body = ", ".join(parts)
175
- if recommendation == "block":
176
- return f"Blocking: {body} β€” critical issues must be resolved."
177
- elif recommendation == "request_changes":
178
- return f"Changes requested: {body} β€” high-severity issues should be addressed."
179
- elif recommendation == "comment":
180
- return f"Minor concerns: {body} β€” consider addressing for best practices."
181
- return f"Approved: {body} β€” no significant issues."
182
-
183
-
184
- # ─── Prompt builder ─────────────────────────────────────────────────────────
185
-
186
-
187
- def _build_prompt(findings: list[Finding]) -> str:
188
- lines = [
189
- "Below are the raw findings from automated code reviewers "
190
- "(correctness, security, test-coverage).",
191
- "",
192
- "Filter out noise and return only the findings a senior engineer "
193
- "would actually leave on this PR.",
194
- "",
195
- "## Raw findings",
196
- ]
197
- for i, f in enumerate(findings, 1):
198
- lines.append(f"\n--- Finding {i} ---")
199
- lines.append(f" File: {f.file_path}")
200
- lines.append(f" Lines: {f.line_start}–{f.line_end}")
201
- lines.append(f" Severity: {f.severity.value}")
202
- lines.append(f" Category: {f.category}")
203
- lines.append(f" Comment: {f.comment}")
204
- lines.append(f" Confidence: {f.confidence}")
205
- if f.suggested_fix:
206
- lines.append(f" Fix: {f.suggested_fix[:200]}")
207
-
208
- lines.append("\nNow apply the deduplication, noise-filtering, and verdict rules.")
209
- return "\n".join(lines)
210
-
211
-
212
- # ─── Node ────────────────────────────────────────────────────────────────────
213
-
214
-
215
- def aggregator_node(state: OpenCodeReviewState) -> dict:
216
- """Deduplicate, filter, and aggregate all findings into a final verdict.
217
-
218
- Returns state updates for ``findings`` (overwritten with the filtered
219
- list) and ``verdict`` (set-once by this node).
220
-
221
- Two-phase approach:
222
- 1. Pre-LLM heuristic deduplication (groups by file/line proximity).
223
- 2. Rule-based verdict by default (fast, ~10ms), or optional LLM critic
224
- when ``USE_LLM_CRITIC`` is enabled.
225
- """
226
- coverage = review_coverage(state)
227
- calibrated = calibrate_findings(state.findings, state)
228
- failed = [stage for stage in state.review_stages if stage.get("status") == "failed"]
229
- if failed:
230
- names = ", ".join(stage["reviewer"] for stage in failed)
231
- return {"review_coverage": coverage, "final_findings": _deduplicate(calibrated), "verdict": Verdict(
232
- summary=f"Review incomplete: {names} failed. Findings are partial; no approval or quality score is available.",
233
- approved=False, overall_score=None, recommendation="incomplete",
234
- score_explanation="No overall risk score is available because one or more reviewers failed. Remaining findings are partial.",
235
- )}
236
- raw_findings = calibrated
237
- if not raw_findings:
238
- logger.info("No findings to aggregate β€” producing empty verdict")
239
- return {"review_coverage": coverage, "final_findings": [], "verdict": _rule_verdict([])}
240
-
241
- # -- Phase 1: Heuristic dedup --------------------------------------------
242
- deduped = _deduplicate(raw_findings)
243
- logger.info(
244
- "Dedup heuristic: %d raw β†’ %d merged",
245
- len(raw_findings), len(deduped),
246
- )
247
-
248
- # -- Phase 2: Rule-based (default, fast) or LLM critic (opt-in) ----------
249
- if USE_LLM_CRITIC:
250
- try:
251
- llm = create_llm(endpoint=state.endpoint or None)
252
- except ValueError as exc:
253
- logger.warning("LLM critic unavailable β€” using rule-based: %s", exc)
254
- llm = None
255
-
256
- if llm is not None:
257
- logger.info(
258
- "Invoking aggregator LLM critic (prompt_version=%s) …",
259
- PROMPT_VERSION,
260
- )
261
- try:
262
- structured_llm = llm.with_structured_output(AggregatedReview)
263
- messages = [
264
- {"role": "system", "content": SYSTEM_PROMPT},
265
- {"role": "user", "content": _build_prompt(deduped)},
266
- ]
267
- result: AggregatedReview = structured_llm.invoke(messages) # type: ignore[assignment]
268
- except Exception as exc:
269
- logger.warning("LLM critic failed β€” falling back to rule-based: %s", exc)
270
- result = None
271
-
272
- if result is not None:
273
- final_findings = calibrate_findings(result.findings, state)
274
- verdict = _rule_verdict(final_findings)
275
- logger.info(
276
- "LLM aggregator: %d deduped β†’ %d final, recommendation=%s",
277
- len(deduped), len(final_findings),
278
- verdict.recommendation,
279
- )
280
- return {"review_coverage": coverage, "final_findings": final_findings, "verdict": verdict}
281
-
282
- # Rule-based path (default) β€” zero LLM overhead
283
- logger.info("Using rule-based aggregation (fast path)")
284
- final_findings = deduped
285
- verdict = _rule_verdict(deduped)
286
-
287
- return {
288
- "review_coverage": coverage,
289
- "final_findings": final_findings, # plain list, overwrites
290
- "verdict": verdict, # set-once, no reducer needed
291
- }
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ from pathlib import Path
6
+
7
+ from llm_factory import create_llm
8
+ from nodes.finding_quality import calibrate_findings, review_coverage
9
+ from pydantic import BaseModel, Field
10
+
11
+ from state import Finding, OpenCodeReviewState, Severity, Verdict
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ GROQ_MODEL = "llama-3.3-70b-versatile"
16
+ DEFAULT_TEMPERATURE = 0.0
17
+
18
+ # Prompt version β€” tied to the file on disk
19
+ PROMPT_VERSION = "v1"
20
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"aggregator_{PROMPT_VERSION}.txt"
21
+
22
+ # Findings below this confidence are dropped before the LLM step
23
+ MIN_CONFIDENCE = 0.25
24
+ # Files/line pairs within this many lines are considered duplicates
25
+ LINE_TOLERANCE = 5
26
+
27
+ # Default to rule-based aggregation (skips expensive LLM critic call).
28
+ # Set AGGREGATOR_USE_LLM_CRITIC=true in env to re-enable the LLM pass.
29
+ USE_LLM_CRITIC = os.environ.get("AGGREGATOR_USE_LLM_CRITIC", "").lower() in ("1", "true", "yes")
30
+
31
+
32
+ # ─── Load prompt from file ──────────────────────────────────────────────────
33
+
34
+
35
+ def _load_prompt() -> str:
36
+ """Load the system prompt from the versioned prompt file."""
37
+ try:
38
+ return PROMPT_FILE.read_text(encoding="utf-8")
39
+ except FileNotFoundError:
40
+ logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
41
+ return (
42
+ "You are a senior engineer acting as a critic of a code review. "
43
+ "Filter out noise, deduplicate findings, and produce a verdict. "
44
+ "Return the filtered list of findings plus your verdict."
45
+ )
46
+
47
+
48
+ SYSTEM_PROMPT = _load_prompt()
49
+
50
+
51
+ # ─── LLM output schema ──────────────────────────────────────────────────────
52
+
53
+
54
+ class AggregatedReview(BaseModel):
55
+ """Final, noise-filtered findings and overall verdict."""
56
+ findings: list[Finding] = Field(
57
+ default_factory=list,
58
+ description="Deduplicated, noise-filtered findings worth a senior engineer's time.",
59
+ )
60
+ verdict: Verdict = Field(
61
+ description="Overall PR verdict after considering all findings.",
62
+ )
63
+
64
+
65
+ # ─── Pre-LLM heuristic deduplication ────────────────────────────────────────
66
+
67
+
68
+ def _deduplicate(findings: list[Finding]) -> list[Finding]:
69
+ """Heuristic dedup: group by ``(file_path, line_start)`` with a line
70
+ tolerance, keeping the highest-confidence finding per group."""
71
+ if not findings:
72
+ return []
73
+
74
+ # Sort by (file, line_start) so we can iterate and merge neighbours
75
+ sorted_fs = sorted(findings, key=lambda f: (f.file_path, f.line_start))
76
+
77
+ merged: list[Finding] = []
78
+ current: Finding = sorted_fs[0]
79
+
80
+ for f in sorted_fs[1:]:
81
+ same_file = f.file_path == current.file_path
82
+ close_lines = abs(f.line_start - current.line_start) <= LINE_TOLERANCE
83
+ same_claim = " ".join(f.comment.lower().split()) == " ".join(current.comment.lower().split())
84
+ if same_file and close_lines and f.kind == current.kind and f.category == current.category and same_claim:
85
+ # Keep the higher-confidence finding, merge comments
86
+ if f.confidence > current.confidence:
87
+ current = f
88
+ if current.confidence < 0.9:
89
+ current.confidence = round(
90
+ (current.confidence + f.confidence) / 2, 2
91
+ )
92
+ # Prefer the specific comment over a generic one
93
+ if len(f.comment) > len(current.comment):
94
+ current.comment = f.comment
95
+ if f.suggested_fix and not current.suggested_fix:
96
+ current.suggested_fix = f.suggested_fix
97
+ # Escalate severity if either finding is more severe
98
+ current.severity = _more_severe(current.severity, f.severity)
99
+ else:
100
+ merged.append(current)
101
+ current = f
102
+ merged.append(current)
103
+
104
+ # Drop low-confidence noise
105
+ merged = [f for f in merged if f.confidence >= MIN_CONFIDENCE]
106
+
107
+ return merged
108
+
109
+
110
+ _SEVERITY_ORDER = {
111
+ Severity.CRITICAL: 0,
112
+ Severity.HIGH: 1,
113
+ Severity.MEDIUM: 2,
114
+ Severity.LOW: 3,
115
+ Severity.INFO: 4,
116
+ }
117
+
118
+
119
+ def _more_severe(a: Severity, b: Severity) -> Severity:
120
+ return a if _SEVERITY_ORDER.get(a, 5) < _SEVERITY_ORDER.get(b, 5) else b
121
+
122
+
123
+ # ─── Rule-based fallback verdict ────────────────────────────────────────────
124
+
125
+
126
+ def _rule_verdict(findings: list[Finding]) -> Verdict:
127
+ """Build a verdict from deduplicated findings without an LLM call."""
128
+ eligible = [f for f in findings if f.kind != "test_suggestion" and f.evidence_status == "source_grounded"]
129
+ suggestions = sum(f.kind == "test_suggestion" for f in findings)
130
+ unverified = sum(f.kind != "test_suggestion" and f.evidence_status != "source_grounded" for f in findings)
131
+ counts = {s: 0 for s in Severity}
132
+ for f in eligible:
133
+ counts[f.severity] = counts.get(f.severity, 0) + 1
134
+
135
+ critical = counts[Severity.CRITICAL]
136
+ high = counts[Severity.HIGH]
137
+
138
+ if critical > 0:
139
+ recommendation = "block"
140
+ approved = False
141
+ elif high > 0:
142
+ recommendation = "request_changes"
143
+ approved = False
144
+ elif eligible or suggestions or unverified:
145
+ recommendation = "comment"
146
+ approved = True
147
+ else:
148
+ recommendation = "approve"
149
+ approved = True
150
+
151
+ # Score: 10 - penalty based on severity
152
+ score = max(0.0, min(10.0, 10.0 - critical * 4.0 - high * 2.0 - counts.get(Severity.MEDIUM, 0) * 0.5))
153
+
154
+ severity_counts = {s.value: counts.get(s, 0) for s in Severity}
155
+
156
+ return Verdict(
157
+ summary=_rule_summary(recommendation, severity_counts) + (f" {suggestions} test suggestion(s), {unverified} unverified claim(s) are excluded from the score." if suggestions or unverified else ""),
158
+ approved=approved,
159
+ overall_score=round(score, 1),
160
+ critical_count=critical,
161
+ high_count=high,
162
+ recommendation=recommendation,
163
+ score_explanation="Risk estimate from source-grounded findings, not answer correctness or proof of safety. Test suggestions and claims without source grounding do not lower the score.",
164
+ score_breakdown={"starting_score": 10, "critical_penalty": critical * 4, "high_penalty": high * 2,
165
+ "medium_penalty": counts[Severity.MEDIUM] * .5, "scored_findings": len(eligible),
166
+ "test_suggestions_excluded": suggestions, "unverified_claims_excluded": unverified},
167
+ )
168
+
169
+
170
+ def _rule_summary(recommendation: str, counts: dict) -> str:
171
+ parts = [f"{v} {k}" for k, v in counts.items() if v > 0]
172
+ if not parts:
173
+ return "No source-grounded defects detected. This does not establish that the PR is safe."
174
+ body = ", ".join(parts)
175
+ if recommendation == "block":
176
+ return f"Blocking: {body} β€” critical issues must be resolved."
177
+ elif recommendation == "request_changes":
178
+ return f"Changes requested: {body} β€” high-severity issues should be addressed."
179
+ elif recommendation == "comment":
180
+ return f"Minor concerns: {body} β€” consider addressing for best practices."
181
+ return f"Approved: {body} β€” no significant issues."
182
+
183
+
184
+ # ─── Prompt builder ─────────────────────────────────────────────────────────
185
+
186
+
187
+ def _build_prompt(findings: list[Finding]) -> str:
188
+ lines = [
189
+ "Below are the raw findings from automated code reviewers "
190
+ "(correctness, security, test-coverage).",
191
+ "",
192
+ "Filter out noise and return only the findings a senior engineer "
193
+ "would actually leave on this PR.",
194
+ "",
195
+ "## Raw findings",
196
+ ]
197
+ for i, f in enumerate(findings, 1):
198
+ lines.append(f"\n--- Finding {i} ---")
199
+ lines.append(f" File: {f.file_path}")
200
+ lines.append(f" Lines: {f.line_start}–{f.line_end}")
201
+ lines.append(f" Severity: {f.severity.value}")
202
+ lines.append(f" Category: {f.category}")
203
+ lines.append(f" Comment: {f.comment}")
204
+ lines.append(f" Confidence: {f.confidence}")
205
+ if f.suggested_fix:
206
+ lines.append(f" Fix: {f.suggested_fix[:200]}")
207
+
208
+ lines.append("\nNow apply the deduplication, noise-filtering, and verdict rules.")
209
+ return "\n".join(lines)
210
+
211
+
212
+ # ─── Node ────────────────────────────────────────────────────────────────────
213
+
214
+
215
+ def aggregator_node(state: OpenCodeReviewState) -> dict:
216
+ """Deduplicate, filter, and aggregate all findings into a final verdict.
217
+
218
+ Returns state updates for ``findings`` (overwritten with the filtered
219
+ list) and ``verdict`` (set-once by this node).
220
+
221
+ Two-phase approach:
222
+ 1. Pre-LLM heuristic deduplication (groups by file/line proximity).
223
+ 2. Rule-based verdict by default (fast, ~10ms), or optional LLM critic
224
+ when ``USE_LLM_CRITIC`` is enabled.
225
+ """
226
+ coverage = review_coverage(state)
227
+ calibrated = calibrate_findings(state.findings, state)
228
+ failed = [stage for stage in state.review_stages if stage.get("status") == "failed"]
229
+ if failed:
230
+ names = ", ".join(stage["reviewer"] for stage in failed)
231
+ return {"review_coverage": coverage, "final_findings": _deduplicate(calibrated), "verdict": Verdict(
232
+ summary=f"Review incomplete: {names} failed. Findings are partial; no approval or quality score is available.",
233
+ approved=False, overall_score=None, recommendation="incomplete",
234
+ score_explanation="No overall risk score is available because one or more reviewers failed. Remaining findings are partial.",
235
+ )}
236
+ raw_findings = calibrated
237
+ if not raw_findings:
238
+ logger.info("No findings to aggregate β€” producing empty verdict")
239
+ return {"review_coverage": coverage, "final_findings": [], "verdict": _rule_verdict([])}
240
+
241
+ # -- Phase 1: Heuristic dedup --------------------------------------------
242
+ deduped = _deduplicate(raw_findings)
243
+ logger.info(
244
+ "Dedup heuristic: %d raw β†’ %d merged",
245
+ len(raw_findings), len(deduped),
246
+ )
247
+
248
+ # -- Phase 2: Rule-based (default, fast) or LLM critic (opt-in) ----------
249
+ if USE_LLM_CRITIC:
250
+ try:
251
+ llm = create_llm(endpoint=state.endpoint or None)
252
+ except ValueError as exc:
253
+ logger.warning("LLM critic unavailable β€” using rule-based: %s", exc)
254
+ llm = None
255
+
256
+ if llm is not None:
257
+ logger.info(
258
+ "Invoking aggregator LLM critic (prompt_version=%s) …",
259
+ PROMPT_VERSION,
260
+ )
261
+ try:
262
+ structured_llm = llm.with_structured_output(AggregatedReview)
263
+ messages = [
264
+ {"role": "system", "content": SYSTEM_PROMPT},
265
+ {"role": "user", "content": _build_prompt(deduped)},
266
+ ]
267
+ result: AggregatedReview = structured_llm.invoke(messages) # type: ignore[assignment]
268
+ except Exception as exc:
269
+ logger.warning("LLM critic failed β€” falling back to rule-based: %s", exc)
270
+ result = None
271
+
272
+ if result is not None:
273
+ final_findings = calibrate_findings(result.findings, state)
274
+ verdict = _rule_verdict(final_findings)
275
+ logger.info(
276
+ "LLM aggregator: %d deduped β†’ %d final, recommendation=%s",
277
+ len(deduped), len(final_findings),
278
+ verdict.recommendation,
279
+ )
280
+ return {"review_coverage": coverage, "final_findings": final_findings, "verdict": verdict}
281
+
282
+ # Rule-based path (default) β€” zero LLM overhead
283
+ logger.info("Using rule-based aggregation (fast path)")
284
+ final_findings = deduped
285
+ verdict = _rule_verdict(deduped)
286
+
287
+ return {
288
+ "review_coverage": coverage,
289
+ "final_findings": final_findings, # plain list, overwrites
290
+ "verdict": verdict, # set-once, no reducer needed
291
+ }
nodes/correctness_reviewer.py CHANGED
@@ -1,200 +1,200 @@
1
- from __future__ import annotations
2
-
3
- import time
4
- import logging
5
- import os
6
- import re
7
- from pathlib import Path
8
-
9
- from llm_factory import create_llm
10
- from nodes.finding_quality import calibrate_findings
11
- from nodes.review_runtime import changed_context, invoke_review, stage_result
12
- from pydantic import BaseModel, Field
13
-
14
- from state import Finding, OpenCodeReviewState, Severity
15
-
16
- logger = logging.getLogger(__name__)
17
-
18
- # Model used on Groq β€” good at function calling / structured output
19
- GROQ_MODEL = "llama-3.3-70b-versatile"
20
- DEFAULT_TEMPERATURE = 0.0
21
-
22
- # Prompt version β€” tied to the file on disk
23
- PROMPT_VERSION = "v1"
24
- PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"correctness_{PROMPT_VERSION}.txt"
25
-
26
- # Max characters of context to include in the prompt (soft limit)
27
- MAX_CONTEXT_CHARS = 2_000
28
- # Max changed-file content to include per file
29
- MAX_FILE_CONTENT_CHARS = 600
30
- # Keep model requests below free-provider token limits. Deterministic checks
31
- # still inspect the complete diff from state.diff.
32
- MAX_DIFF_CHARS = 9_000
33
-
34
-
35
- # ─── Load prompt from file ──────────────────────────────────────────────────
36
-
37
-
38
- def _load_prompt() -> str:
39
- """Load the system prompt from the versioned prompt file."""
40
- try:
41
- return PROMPT_FILE.read_text(encoding="utf-8")
42
- except FileNotFoundError:
43
- logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
44
- return (
45
- "You are a seasoned code reviewer focused exclusively on correctness. "
46
- "Analyse the PR diff and look for logic errors, edge cases, "
47
- "off-by-one errors, missing null checks, resource mismanagement, "
48
- "and concurrency hazards. Return a list of findings."
49
- )
50
-
51
-
52
- SYSTEM_PROMPT = _load_prompt()
53
-
54
-
55
- # ─── Wrapper schema for structured output ───────────────────────────────────
56
-
57
-
58
- class CorrectnessReview(BaseModel):
59
- """A list of correctness issues found during code review.
60
-
61
- The LLM MUST populate this with every correctness-relevant finding in the
62
- diff. Return an empty list if no correctness issues are found.
63
- """
64
- findings: list[Finding] = Field(
65
- default_factory=list,
66
- description=(
67
- "Correctness issues found in the PR diff. "
68
- "Each issue must reference a specific file and line range."
69
- ),
70
- )
71
-
72
-
73
- # ─── Prompt builder ─────────────────────────────────────────────────────────
74
-
75
-
76
- def _build_prompt(state: OpenCodeReviewState) -> str:
77
- """Build the user-facing prompt from the current graph state."""
78
- lines: list[str] = []
79
-
80
- lines.append("## Diff\n```diff")
81
- diff = state.diff or ""
82
- if len(diff) > MAX_DIFF_CHARS:
83
- diff = diff[:MAX_DIFF_CHARS] + "\n… (diff truncated for model context)"
84
- lines.append(diff)
85
- lines.append("```\n")
86
-
87
- # Changed files with full content (truncated per file)
88
- if state.changed_files:
89
- lines.append("## Changed files\n")
90
- for cf in state.changed_files:
91
- header = f"### {cf.path} ({cf.status})"
92
- lines.append(header)
93
- content = changed_context(cf, state.review_mode)
94
- if len(content) > MAX_FILE_CONTENT_CHARS:
95
- content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
96
- lines.append(f"```\n{content}\n```\n")
97
-
98
- # Context chunks (truncated total)
99
- if state.context_chunks:
100
- lines.append("## Retrieved context\n")
101
- ctx_chars = 0
102
- for chunk in state.context_chunks:
103
- snippet = chunk.content
104
- if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
105
- remaining = MAX_CONTEXT_CHARS - ctx_chars
106
- if remaining > 200:
107
- lines.append(f"> {snippet[:remaining]}… (truncated)")
108
- break
109
- if chunk.source == "past_pr":
110
- lines.append(f"> [Past PR β€” {chunk.file_path}]: {snippet}")
111
- else:
112
- lines.append(f"> [{chunk.file_path}]: {snippet}")
113
- ctx_chars += len(snippet)
114
-
115
- return "\n".join(lines)
116
-
117
-
118
- # ─── Node ────────────────────────────────────────────────────────────────────
119
-
120
-
121
- def correctness_reviewer_node(state: OpenCodeReviewState) -> dict:
122
- started = time.monotonic()
123
- """Analyse the diff and context chunks for correctness issues using an LLM.
124
-
125
- Returns state updates for ``findings`` (accumulated via the ``add``
126
- reducer).
127
- """
128
- # --- Sanity checks -------------------------------------------------------
129
- if not state.diff:
130
- logger.info("No diff to review β€” skipping correctness review")
131
- return {}
132
-
133
- # A regex match cannot establish whether async side effects must be awaited.
134
- # Retain findings only when the reviewer has evaluated the surrounding code.
135
- static_findings = []
136
-
137
- # --- Build the LLM (Gemini primary β†’ Groq fallback) -----------------------
138
- try:
139
- llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
140
- except ValueError as exc:
141
- logger.warning("LLM unavailable β€” skipping correctness review: %s", exc)
142
- return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
143
-
144
- # --- Build the prompt ----------------------------------------------------
145
- user_prompt = _build_prompt(state)
146
- logger.info(
147
- "Invoking correctness reviewer (diff=%s, context=%d chunks, prompt=%s, prompt_version=%s)",
148
- _human_size(len(state.diff or "")),
149
- len(state.context_chunks),
150
- _human_size(len(user_prompt)),
151
- PROMPT_VERSION,
152
- )
153
-
154
- # --- Invoke --------------------------------------------------------------
155
- try:
156
- messages = [
157
- {"role": "system", "content": SYSTEM_PROMPT},
158
- {"role": "user", "content": user_prompt},
159
- ]
160
- result: CorrectnessReview = invoke_review(llm, CorrectnessReview, messages, mode=state.review_mode) # type: ignore[assignment]
161
- except Exception as exc:
162
- logger.warning("Correctness review LLM call failed: %s", exc)
163
- return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
164
-
165
- # Deterministic guard for a high-impact async anti-pattern that LLMs can
166
- # miss: promises created by forEach are not awaited by the caller.
167
- result.findings.extend(static_findings)
168
-
169
- # --- Log and return findings ---------------------------------------------
170
- result.findings = calibrate_findings(result.findings, state)
171
- if result and result.findings:
172
- logger.info(
173
- "Correctness review found %d issue(s)",
174
- len(result.findings),
175
- )
176
- for f in result.findings:
177
- logger.debug(
178
- " [%.2f] %s:%d–%d β€” %s",
179
- f.confidence, f.file_path, f.line_start, f.line_end,
180
- f.comment[:80],
181
- )
182
- else:
183
- logger.info("Correctness review found no issues")
184
-
185
- return {
186
- "findings": result.findings,
187
- "review_stages": [stage_result("correctness", started, llm=llm)],
188
- }
189
-
190
-
191
- # ─── Utility ─────────────────────────────────────────────────────────────────
192
-
193
-
194
- def _human_size(bytes_: int) -> str:
195
- if bytes_ < 1024:
196
- return f"{bytes_} B"
197
- elif bytes_ < 1024 * 1024:
198
- return f"{bytes_ / 1024:.1f} KiB"
199
- else:
200
- return f"{bytes_ / (1024 * 1024):.1f} MiB"
 
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ import logging
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+
9
+ from llm_factory import create_llm
10
+ from nodes.finding_quality import calibrate_findings
11
+ from nodes.review_runtime import changed_context, invoke_review, stage_result
12
+ from pydantic import BaseModel, Field
13
+
14
+ from state import Finding, OpenCodeReviewState, Severity
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # Model used on Groq β€” good at function calling / structured output
19
+ GROQ_MODEL = "llama-3.3-70b-versatile"
20
+ DEFAULT_TEMPERATURE = 0.0
21
+
22
+ # Prompt version β€” tied to the file on disk
23
+ PROMPT_VERSION = "v1"
24
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"correctness_{PROMPT_VERSION}.txt"
25
+
26
+ # Max characters of context to include in the prompt (soft limit)
27
+ MAX_CONTEXT_CHARS = 2_000
28
+ # Max changed-file content to include per file
29
+ MAX_FILE_CONTENT_CHARS = 600
30
+ # Keep model requests below free-provider token limits. Deterministic checks
31
+ # still inspect the complete diff from state.diff.
32
+ MAX_DIFF_CHARS = 9_000
33
+
34
+
35
+ # ─── Load prompt from file ──────────────────────────────────────────────────
36
+
37
+
38
+ def _load_prompt() -> str:
39
+ """Load the system prompt from the versioned prompt file."""
40
+ try:
41
+ return PROMPT_FILE.read_text(encoding="utf-8")
42
+ except FileNotFoundError:
43
+ logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
44
+ return (
45
+ "You are a seasoned code reviewer focused exclusively on correctness. "
46
+ "Analyse the PR diff and look for logic errors, edge cases, "
47
+ "off-by-one errors, missing null checks, resource mismanagement, "
48
+ "and concurrency hazards. Return a list of findings."
49
+ )
50
+
51
+
52
+ SYSTEM_PROMPT = _load_prompt()
53
+
54
+
55
+ # ─── Wrapper schema for structured output ───────────────────────────────────
56
+
57
+
58
+ class CorrectnessReview(BaseModel):
59
+ """A list of correctness issues found during code review.
60
+
61
+ The LLM MUST populate this with every correctness-relevant finding in the
62
+ diff. Return an empty list if no correctness issues are found.
63
+ """
64
+ findings: list[Finding] = Field(
65
+ default_factory=list,
66
+ description=(
67
+ "Correctness issues found in the PR diff. "
68
+ "Each issue must reference a specific file and line range."
69
+ ),
70
+ )
71
+
72
+
73
+ # ─── Prompt builder ─────────────────────────────────────────────────────────
74
+
75
+
76
+ def _build_prompt(state: OpenCodeReviewState) -> str:
77
+ """Build the user-facing prompt from the current graph state."""
78
+ lines: list[str] = []
79
+
80
+ lines.append("## Diff\n```diff")
81
+ diff = state.diff or ""
82
+ if len(diff) > MAX_DIFF_CHARS:
83
+ diff = diff[:MAX_DIFF_CHARS] + "\n… (diff truncated for model context)"
84
+ lines.append(diff)
85
+ lines.append("```\n")
86
+
87
+ # Changed files with full content (truncated per file)
88
+ if state.changed_files:
89
+ lines.append("## Changed files\n")
90
+ for cf in state.changed_files:
91
+ header = f"### {cf.path} ({cf.status})"
92
+ lines.append(header)
93
+ content = changed_context(cf, state.review_mode)
94
+ if len(content) > MAX_FILE_CONTENT_CHARS:
95
+ content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
96
+ lines.append(f"```\n{content}\n```\n")
97
+
98
+ # Context chunks (truncated total)
99
+ if state.context_chunks:
100
+ lines.append("## Retrieved context\n")
101
+ ctx_chars = 0
102
+ for chunk in state.context_chunks:
103
+ snippet = chunk.content
104
+ if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
105
+ remaining = MAX_CONTEXT_CHARS - ctx_chars
106
+ if remaining > 200:
107
+ lines.append(f"> {snippet[:remaining]}… (truncated)")
108
+ break
109
+ if chunk.source == "past_pr":
110
+ lines.append(f"> [Past PR β€” {chunk.file_path}]: {snippet}")
111
+ else:
112
+ lines.append(f"> [{chunk.file_path}]: {snippet}")
113
+ ctx_chars += len(snippet)
114
+
115
+ return "\n".join(lines)
116
+
117
+
118
+ # ─── Node ────────────────────────────────────────────────────────────────────
119
+
120
+
121
+ def correctness_reviewer_node(state: OpenCodeReviewState) -> dict:
122
+ started = time.monotonic()
123
+ """Analyse the diff and context chunks for correctness issues using an LLM.
124
+
125
+ Returns state updates for ``findings`` (accumulated via the ``add``
126
+ reducer).
127
+ """
128
+ # --- Sanity checks -------------------------------------------------------
129
+ if not state.diff:
130
+ logger.info("No diff to review β€” skipping correctness review")
131
+ return {}
132
+
133
+ # A regex match cannot establish whether async side effects must be awaited.
134
+ # Retain findings only when the reviewer has evaluated the surrounding code.
135
+ static_findings = []
136
+
137
+ # --- Build the LLM (Gemini primary β†’ Groq fallback) -----------------------
138
+ try:
139
+ llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
140
+ except ValueError as exc:
141
+ logger.warning("LLM unavailable β€” skipping correctness review: %s", exc)
142
+ return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
143
+
144
+ # --- Build the prompt ----------------------------------------------------
145
+ user_prompt = _build_prompt(state)
146
+ logger.info(
147
+ "Invoking correctness reviewer (diff=%s, context=%d chunks, prompt=%s, prompt_version=%s)",
148
+ _human_size(len(state.diff or "")),
149
+ len(state.context_chunks),
150
+ _human_size(len(user_prompt)),
151
+ PROMPT_VERSION,
152
+ )
153
+
154
+ # --- Invoke --------------------------------------------------------------
155
+ try:
156
+ messages = [
157
+ {"role": "system", "content": SYSTEM_PROMPT},
158
+ {"role": "user", "content": user_prompt},
159
+ ]
160
+ result: CorrectnessReview = invoke_review(llm, CorrectnessReview, messages, mode=state.review_mode) # type: ignore[assignment]
161
+ except Exception as exc:
162
+ logger.warning("Correctness review LLM call failed: %s", exc)
163
+ return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
164
+
165
+ # Deterministic guard for a high-impact async anti-pattern that LLMs can
166
+ # miss: promises created by forEach are not awaited by the caller.
167
+ result.findings.extend(static_findings)
168
+
169
+ # --- Log and return findings ---------------------------------------------
170
+ result.findings = calibrate_findings(result.findings, state)
171
+ if result and result.findings:
172
+ logger.info(
173
+ "Correctness review found %d issue(s)",
174
+ len(result.findings),
175
+ )
176
+ for f in result.findings:
177
+ logger.debug(
178
+ " [%.2f] %s:%d–%d β€” %s",
179
+ f.confidence, f.file_path, f.line_start, f.line_end,
180
+ f.comment[:80],
181
+ )
182
+ else:
183
+ logger.info("Correctness review found no issues")
184
+
185
+ return {
186
+ "findings": result.findings,
187
+ "review_stages": [stage_result("correctness", started, llm=llm)],
188
+ }
189
+
190
+
191
+ # ─── Utility ─────────────────────────────────────────────────────────────────
192
+
193
+
194
+ def _human_size(bytes_: int) -> str:
195
+ if bytes_ < 1024:
196
+ return f"{bytes_} B"
197
+ elif bytes_ < 1024 * 1024:
198
+ return f"{bytes_ / 1024:.1f} KiB"
199
+ else:
200
+ return f"{bytes_ / (1024 * 1024):.1f} MiB"
nodes/executor.py CHANGED
@@ -1,336 +1,336 @@
1
- from __future__ import annotations
2
-
3
- import logging
4
- import os
5
-
6
- import requests
7
- from typing import Any
8
-
9
- from github_client import GitHubSession, resolve_token
10
- from state import Finding, OpenCodeReviewState
11
-
12
- logger = logging.getLogger(__name__)
13
-
14
- GITHUB_API_BASE = "https://api.github.com"
15
-
16
- # ─── Helpers ─────────────────────────────────────────────────────────────────
17
-
18
-
19
- _GITHUB_SESSION: GitHubSession | None = None
20
- _POST_ERRORS: list[str] = []
21
-
22
-
23
- def _gh_session() -> GitHubSession:
24
- """Return a lazily-initialized :class:`GitHubSession`."""
25
- global _GITHUB_SESSION
26
- if _GITHUB_SESSION is None:
27
- _GITHUB_SESSION = GitHubSession()
28
- return _GITHUB_SESSION
29
-
30
-
31
- def _fetch_pr_head_sha(owner: str, repo: str, pr_number: int) -> str | None:
32
- """Fetch the latest head SHA of the PR so inline comments target the correct
33
- commit even if the PR was updated since ingestion."""
34
- url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}"
35
- try:
36
- resp = _gh_session().get(url, timeout=30)
37
- if resp.status_code == 200:
38
- return resp.json()["head"]["sha"]
39
- logger.warning(
40
- "Could not fetch PR metadata: HTTP %s β€” %s",
41
- resp.status_code, resp.text[:120],
42
- )
43
- return None
44
- except requests.RequestException as exc:
45
- logger.warning("Request failed while fetching PR metadata: %s", exc)
46
- return None
47
-
48
-
49
- def _post_review_comment(
50
- owner: str,
51
- repo: str,
52
- pr_number: int,
53
- commit_id: str,
54
- path: str,
55
- line: int,
56
- side: str,
57
- body: str,
58
- start_line: int | None = None,
59
- ) -> bool:
60
- """Post an inline PR review comment at the given file/line position.
61
-
62
- Uses ``POST /repos/{owner}/{repo}/pulls/{pull_number}/comments``.
63
-
64
- Parameters
65
- ----------
66
- line : int
67
- The line number in the diff. For multi-line comments this is the
68
- *last* line of the range.
69
- side : str
70
- ``"LEFT"`` or ``"RIGHT"`` β€” which side of the diff the comment
71
- targets. We always use ``"RIGHT"`` (the new/post-PR version).
72
- start_line : int | None
73
- When set, creates a multi-line comment spanning *start_line* β†’
74
- *line*.
75
- """
76
- payload: dict[str, Any] = {
77
- "body": body,
78
- "commit_id": commit_id,
79
- "path": path,
80
- "line": line,
81
- "side": side,
82
- }
83
- if start_line is not None:
84
- payload["start_line"] = start_line
85
- payload["start_side"] = side
86
-
87
- url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}/comments"
88
- try:
89
- resp = _gh_session().post(url, json=payload, timeout=30)
90
- if resp.status_code in (201, 200):
91
- logger.debug(
92
- "Inline comment posted to %s:%d (%s)", path, line, side,
93
- )
94
- return True
95
- if resp.status_code == 422:
96
- # Stale line: the line no longer exists in the latest diff.
97
- logger.info(
98
- "Line %d no longer exists in %s (422) β€” will fall back "
99
- "to issue comment", line, path,
100
- )
101
- return False
102
- logger.warning(
103
- "Failed to post inline comment: HTTP %s β€” %s",
104
- resp.status_code, resp.text[:200],
105
- )
106
- _POST_ERRORS.append(f"inline:{resp.status_code}:{resp.text[:200]}")
107
- return False
108
- except requests.RequestException as exc:
109
- logger.warning("Request failed for inline comment: %s", exc)
110
- return False
111
-
112
-
113
- def _post_issue_comment(owner: str, repo: str, pr_number: int, body: str) -> bool:
114
- """Post a general (non-inline) issue/PR comment as a fallback.
115
-
116
- Uses ``POST /repos/{owner}/{repo}/issues/{issue_number}/comments``.
117
- """
118
- url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/issues/{pr_number}/comments"
119
- try:
120
- resp = _gh_session().post(
121
- url, json={"body": body}, timeout=30,
122
- )
123
- if resp.status_code in (201, 200):
124
- logger.debug("Fallback issue comment posted")
125
- return True
126
- logger.warning(
127
- "Failed to post fallback comment: HTTP %s β€” %s",
128
- resp.status_code, resp.text[:200],
129
- )
130
- _POST_ERRORS.append(f"issue:{resp.status_code}:{resp.text[:200]}")
131
- return False
132
- except requests.RequestException as exc:
133
- logger.warning("Request failed for fallback comment: %s", exc)
134
- return False
135
-
136
-
137
- # ─── Formatting ──────────────────────────────────────────────────────────────
138
-
139
- SEVERITY_EMOJI = {
140
- "critical": "\U0001f6a8", # 🚨
141
- "high": "\u26a0\ufe0f", # ��️
142
- "medium": "\U0001f4cc", # πŸ“Œ
143
- "low": "\U0001f4a1", # πŸ’‘
144
- "info": "\u2139\ufe0f", # ℹ️
145
- }
146
- VERDICT_ICON = {
147
- "approve": "\u2705",
148
- "request_changes": "\U0001f504",
149
- "block": "\U0001f6ab",
150
- "comment": "\U0001f4ac",
151
- }
152
-
153
-
154
- def _finding_body(finding: Finding) -> str:
155
- """Format a single finding as Markdown for the comment body."""
156
- emoji = SEVERITY_EMOJI.get(finding.severity.value, "\U0001f50d")
157
- fix = ""
158
- if finding.suggested_fix:
159
- fix = f"\n\n**Suggested fix:**\n```\n{finding.suggested_fix}\n```"
160
- return (
161
- f"{emoji} **{finding.severity.value.upper()}** β€” "
162
- f"*{finding.category}* \n"
163
- f"**Model confidence (uncalibrated):** {finding.confidence:.0%} \n"
164
- f"**Evidence:** {finding.evidence_status} β€” source location checked; behavior not independently reproduced. \n\n"
165
- f"{finding.comment}{fix}"
166
- )
167
-
168
-
169
- def _finding_fallback_body(finding: Finding) -> str:
170
- """Format a finding for a fallback issue comment when the line is stale."""
171
- return (
172
- f"*(This comment refers to a previous version of the code β€” "
173
- f"the line may no longer exist in the latest diff.)*\n\n"
174
- f"{_finding_body(finding)}\n\n"
175
- f"**Original location:** `{finding.file_path}` "
176
- f"(lines {finding.line_start}\u2013{finding.line_end})"
177
- )
178
-
179
-
180
- def _verdict_body(verdict_dict: dict) -> str:
181
- """Format the overall verdict as a Markdown PR comment."""
182
- emoji = VERDICT_ICON.get(verdict_dict.get("recommendation", ""), "\U0001f4cb")
183
- summary = verdict_dict.get("summary", "")
184
- score = verdict_dict.get("overall_score", 0)
185
- return (
186
- f"## OpenCodeReview \u2014 {emoji} "
187
- f"{verdict_dict['recommendation'].upper()}\n\n"
188
- f"**Risk estimate:** {score}/10 (not answer correctness) \n"
189
- f"**Summary:** {summary}\n"
190
- )
191
-
192
-
193
- # ─── Node ────────────────────────────────────────────────────────────────────
194
-
195
-
196
- def executor_node(state: OpenCodeReviewState) -> dict:
197
- """Post approved findings as GitHub **PR review comments** at the correct
198
- file/line positions.
199
-
200
- Workflow
201
- --------
202
- 1. Only runs if ``state.human_approved is True``.
203
- 2. Fetches the latest PR head SHA every time (handles PR updates).
204
- 3. For each finding:
205
- a. Try ``POST /pulls/{pr}/comments`` (inline review comment).
206
- b. On **422** (stale line): fall back to
207
- ``POST /issues/{pr}/comments`` (general comment).
208
- 4. Posts the verdict as a general issue comment.
209
-
210
- Requires ``GITHUB_TOKEN`` to post. Without it, logs what it *would*
211
- have posted.
212
- """
213
- if state.verdict and state.verdict.recommendation == "incomplete":
214
- return {"posting_result": {"status": "skipped", "reason": "incomplete_review"}}
215
- if not state.human_approved:
216
- logger.info("Not approved \u2014 skipping executor")
217
- return {"posting_result": {"status": "skipped", "reason": "not_approved"}}
218
-
219
- postable_findings = [finding for finding in state.final_findings if finding.evidence_status == "source_grounded"]
220
- withheld = len(state.final_findings) - len(postable_findings)
221
- _POST_ERRORS.clear()
222
-
223
- parts = state.repo.split("/")
224
- if len(parts) != 2:
225
- logger.warning("Cannot post results: invalid repo '%s'", state.repo)
226
- return {"posting_result": {"status": "failed", "reason": "invalid_repo"}}
227
- owner, repo_name = parts
228
- pr_number = state.pr_number
229
-
230
- gh_token = os.environ.get("GITHUB_TOKEN", "").strip()
231
- if not gh_token:
232
- gh_token = resolve_token() or ""
233
- if not gh_token:
234
- logger.warning(
235
- "No GitHub token available \u2014 cannot post to %s/%s#%d. "
236
- "Run 'opencodereview auth login' or set GITHUB_TOKEN.",
237
- owner, repo_name, pr_number,
238
- )
239
- if state.verdict:
240
- logger.info("[WOULD POST] Verdict: %s", state.verdict.summary)
241
- for f in postable_findings:
242
- logger.info(
243
- "[WOULD POST] %s:%d\u2013%d %s \u2014 %s",
244
- f.file_path, f.line_start, f.line_end,
245
- f.severity.value, f.comment[:60],
246
- )
247
- return {"posting_result": {"status": "dry_run", "inline_posted": 0, "fallback_posted": 0, "failed": len(state.final_findings)}}
248
-
249
- # ── 1. Fetch latest head SHA ─────────────────────────────────────────
250
- commit_id = _fetch_pr_head_sha(owner, repo_name, pr_number)
251
- if commit_id is None:
252
- logger.warning(
253
- "Could not fetch PR head SHA \u2014 cannot post inline "
254
- "comments. Falling back to issue-level comments."
255
- )
256
-
257
- # ── 2. Post each finding ─��───────────────────────────────────────────
258
- inline_ok = 0
259
- inline_failed = 0
260
- fallback_ok = 0
261
-
262
- for f in postable_findings:
263
- body = _finding_body(f)
264
-
265
- if commit_id:
266
- # Try inline review comment
267
- if f.line_start == f.line_end:
268
- ok = _post_review_comment(
269
- owner, repo_name, pr_number,
270
- commit_id, f.file_path, f.line_start, "RIGHT", body,
271
- )
272
- else:
273
- # Multi-line: end_line is the "line" param, start_line
274
- # marks the range start.
275
- ok = _post_review_comment(
276
- owner, repo_name, pr_number,
277
- commit_id, f.file_path, f.line_end, "RIGHT", body,
278
- start_line=f.line_start,
279
- )
280
-
281
- if ok:
282
- inline_ok += 1
283
- continue
284
- inline_failed += 1
285
-
286
- # Fallback: issue-level comment with stale-line context
287
- fallback_body = (
288
- _finding_fallback_body(f) if commit_id else body
289
- )
290
- if _post_issue_comment(owner, repo_name, pr_number, fallback_body):
291
- fallback_ok += 1
292
-
293
- # ── 3. Post the verdict ──────────────────────────────────────────────
294
- verdict_posted = False
295
- if state.verdict:
296
- verdict_body = _verdict_body(state.verdict.model_dump())
297
- verdict_posted = _post_issue_comment(owner, repo_name, pr_number, verdict_body)
298
-
299
- total = len(postable_findings)
300
- logger.info(
301
- "Executor: %d/%d inline, %d/%d fallback, verdict %s \u2014 "
302
- "%s/%s#%d",
303
- inline_ok, total, fallback_ok, total - inline_ok,
304
- "posted" if state.verdict else "skipped",
305
- owner, repo_name, pr_number,
306
- )
307
- finding_failed = total - inline_ok - fallback_ok
308
- verdict_failed = int(state.verdict is not None and not verdict_posted)
309
- failed = finding_failed + verdict_failed
310
- # A review is fully posted only when every finding and the verdict were
311
- # accepted by GitHub. Keep the per-part counts so the API/UI can explain a
312
- # partial result instead of reporting a misleading success.
313
- successful_parts = inline_ok + fallback_ok + int(verdict_posted)
314
- expected_parts = total + int(state.verdict is not None)
315
- if expected_parts == 0:
316
- status = "posted"
317
- elif successful_parts == expected_parts:
318
- status = "posted"
319
- elif successful_parts:
320
- status = "partially_posted"
321
- else:
322
- status = "post_failed"
323
- if withheld and status == "posted":
324
- status = "partially_posted"
325
- return {"posting_result": {
326
- "status": status,
327
- "withheld_unverified": withheld,
328
- "total_findings": total,
329
- "inline_posted": inline_ok,
330
- "fallback_posted": fallback_ok,
331
- "failed": failed,
332
- "finding_failed": finding_failed,
333
- "verdict_failed": verdict_failed,
334
- "verdict_posted": verdict_posted,
335
- "errors": list(_POST_ERRORS),
336
- }}
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+
6
+ import requests
7
+ from typing import Any
8
+
9
+ from github_client import GitHubSession, resolve_token
10
+ from state import Finding, OpenCodeReviewState
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ GITHUB_API_BASE = "https://api.github.com"
15
+
16
+ # ─── Helpers ─────────────────────────────────────────────────────────────────
17
+
18
+
19
+ _GITHUB_SESSION: GitHubSession | None = None
20
+ _POST_ERRORS: list[str] = []
21
+
22
+
23
+ def _gh_session() -> GitHubSession:
24
+ """Return a lazily-initialized :class:`GitHubSession`."""
25
+ global _GITHUB_SESSION
26
+ if _GITHUB_SESSION is None:
27
+ _GITHUB_SESSION = GitHubSession()
28
+ return _GITHUB_SESSION
29
+
30
+
31
+ def _fetch_pr_head_sha(owner: str, repo: str, pr_number: int) -> str | None:
32
+ """Fetch the latest head SHA of the PR so inline comments target the correct
33
+ commit even if the PR was updated since ingestion."""
34
+ url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}"
35
+ try:
36
+ resp = _gh_session().get(url, timeout=30)
37
+ if resp.status_code == 200:
38
+ return resp.json()["head"]["sha"]
39
+ logger.warning(
40
+ "Could not fetch PR metadata: HTTP %s β€” %s",
41
+ resp.status_code, resp.text[:120],
42
+ )
43
+ return None
44
+ except requests.RequestException as exc:
45
+ logger.warning("Request failed while fetching PR metadata: %s", exc)
46
+ return None
47
+
48
+
49
+ def _post_review_comment(
50
+ owner: str,
51
+ repo: str,
52
+ pr_number: int,
53
+ commit_id: str,
54
+ path: str,
55
+ line: int,
56
+ side: str,
57
+ body: str,
58
+ start_line: int | None = None,
59
+ ) -> bool:
60
+ """Post an inline PR review comment at the given file/line position.
61
+
62
+ Uses ``POST /repos/{owner}/{repo}/pulls/{pull_number}/comments``.
63
+
64
+ Parameters
65
+ ----------
66
+ line : int
67
+ The line number in the diff. For multi-line comments this is the
68
+ *last* line of the range.
69
+ side : str
70
+ ``"LEFT"`` or ``"RIGHT"`` β€” which side of the diff the comment
71
+ targets. We always use ``"RIGHT"`` (the new/post-PR version).
72
+ start_line : int | None
73
+ When set, creates a multi-line comment spanning *start_line* β†’
74
+ *line*.
75
+ """
76
+ payload: dict[str, Any] = {
77
+ "body": body,
78
+ "commit_id": commit_id,
79
+ "path": path,
80
+ "line": line,
81
+ "side": side,
82
+ }
83
+ if start_line is not None:
84
+ payload["start_line"] = start_line
85
+ payload["start_side"] = side
86
+
87
+ url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}/comments"
88
+ try:
89
+ resp = _gh_session().post(url, json=payload, timeout=30)
90
+ if resp.status_code in (201, 200):
91
+ logger.debug(
92
+ "Inline comment posted to %s:%d (%s)", path, line, side,
93
+ )
94
+ return True
95
+ if resp.status_code == 422:
96
+ # Stale line: the line no longer exists in the latest diff.
97
+ logger.info(
98
+ "Line %d no longer exists in %s (422) β€” will fall back "
99
+ "to issue comment", line, path,
100
+ )
101
+ return False
102
+ logger.warning(
103
+ "Failed to post inline comment: HTTP %s β€” %s",
104
+ resp.status_code, resp.text[:200],
105
+ )
106
+ _POST_ERRORS.append(f"inline:{resp.status_code}:{resp.text[:200]}")
107
+ return False
108
+ except requests.RequestException as exc:
109
+ logger.warning("Request failed for inline comment: %s", exc)
110
+ return False
111
+
112
+
113
+ def _post_issue_comment(owner: str, repo: str, pr_number: int, body: str) -> bool:
114
+ """Post a general (non-inline) issue/PR comment as a fallback.
115
+
116
+ Uses ``POST /repos/{owner}/{repo}/issues/{issue_number}/comments``.
117
+ """
118
+ url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/issues/{pr_number}/comments"
119
+ try:
120
+ resp = _gh_session().post(
121
+ url, json={"body": body}, timeout=30,
122
+ )
123
+ if resp.status_code in (201, 200):
124
+ logger.debug("Fallback issue comment posted")
125
+ return True
126
+ logger.warning(
127
+ "Failed to post fallback comment: HTTP %s β€” %s",
128
+ resp.status_code, resp.text[:200],
129
+ )
130
+ _POST_ERRORS.append(f"issue:{resp.status_code}:{resp.text[:200]}")
131
+ return False
132
+ except requests.RequestException as exc:
133
+ logger.warning("Request failed for fallback comment: %s", exc)
134
+ return False
135
+
136
+
137
+ # ─── Formatting ──────────────────────────────────────────────────────────────
138
+
139
+ SEVERITY_EMOJI = {
140
+ "critical": "\U0001f6a8", # 🚨
141
+ "high": "\u26a0\ufe0f", # ⚠️
142
+ "medium": "\U0001f4cc", # πŸ“Œ
143
+ "low": "\U0001f4a1", # πŸ’‘
144
+ "info": "\u2139\ufe0f", # ℹ️
145
+ }
146
+ VERDICT_ICON = {
147
+ "approve": "\u2705",
148
+ "request_changes": "\U0001f504",
149
+ "block": "\U0001f6ab",
150
+ "comment": "\U0001f4ac",
151
+ }
152
+
153
+
154
+ def _finding_body(finding: Finding) -> str:
155
+ """Format a single finding as Markdown for the comment body."""
156
+ emoji = SEVERITY_EMOJI.get(finding.severity.value, "\U0001f50d")
157
+ fix = ""
158
+ if finding.suggested_fix:
159
+ fix = f"\n\n**Suggested fix:**\n```\n{finding.suggested_fix}\n```"
160
+ return (
161
+ f"{emoji} **{finding.severity.value.upper()}** β€” "
162
+ f"*{finding.category}* \n"
163
+ f"**Model confidence (uncalibrated):** {finding.confidence:.0%} \n"
164
+ f"**Evidence:** {finding.evidence_status} β€” source location checked; behavior not independently reproduced. \n\n"
165
+ f"{finding.comment}{fix}"
166
+ )
167
+
168
+
169
+ def _finding_fallback_body(finding: Finding) -> str:
170
+ """Format a finding for a fallback issue comment when the line is stale."""
171
+ return (
172
+ f"*(This comment refers to a previous version of the code β€” "
173
+ f"the line may no longer exist in the latest diff.)*\n\n"
174
+ f"{_finding_body(finding)}\n\n"
175
+ f"**Original location:** `{finding.file_path}` "
176
+ f"(lines {finding.line_start}\u2013{finding.line_end})"
177
+ )
178
+
179
+
180
+ def _verdict_body(verdict_dict: dict) -> str:
181
+ """Format the overall verdict as a Markdown PR comment."""
182
+ emoji = VERDICT_ICON.get(verdict_dict.get("recommendation", ""), "\U0001f4cb")
183
+ summary = verdict_dict.get("summary", "")
184
+ score = verdict_dict.get("overall_score", 0)
185
+ return (
186
+ f"## OpenCodeReview \u2014 {emoji} "
187
+ f"{verdict_dict['recommendation'].upper()}\n\n"
188
+ f"**Risk estimate:** {score}/10 (not answer correctness) \n"
189
+ f"**Summary:** {summary}\n"
190
+ )
191
+
192
+
193
+ # ─── Node ────────────────────────────────────────────────────────────────────
194
+
195
+
196
+ def executor_node(state: OpenCodeReviewState) -> dict:
197
+ """Post approved findings as GitHub **PR review comments** at the correct
198
+ file/line positions.
199
+
200
+ Workflow
201
+ --------
202
+ 1. Only runs if ``state.human_approved is True``.
203
+ 2. Fetches the latest PR head SHA every time (handles PR updates).
204
+ 3. For each finding:
205
+ a. Try ``POST /pulls/{pr}/comments`` (inline review comment).
206
+ b. On **422** (stale line): fall back to
207
+ ``POST /issues/{pr}/comments`` (general comment).
208
+ 4. Posts the verdict as a general issue comment.
209
+
210
+ Requires ``GITHUB_TOKEN`` to post. Without it, logs what it *would*
211
+ have posted.
212
+ """
213
+ if state.verdict and state.verdict.recommendation == "incomplete":
214
+ return {"posting_result": {"status": "skipped", "reason": "incomplete_review"}}
215
+ if not state.human_approved:
216
+ logger.info("Not approved \u2014 skipping executor")
217
+ return {"posting_result": {"status": "skipped", "reason": "not_approved"}}
218
+
219
+ postable_findings = [finding for finding in state.final_findings if finding.evidence_status == "source_grounded"]
220
+ withheld = len(state.final_findings) - len(postable_findings)
221
+ _POST_ERRORS.clear()
222
+
223
+ parts = state.repo.split("/")
224
+ if len(parts) != 2:
225
+ logger.warning("Cannot post results: invalid repo '%s'", state.repo)
226
+ return {"posting_result": {"status": "failed", "reason": "invalid_repo"}}
227
+ owner, repo_name = parts
228
+ pr_number = state.pr_number
229
+
230
+ gh_token = os.environ.get("GITHUB_TOKEN", "").strip()
231
+ if not gh_token:
232
+ gh_token = resolve_token() or ""
233
+ if not gh_token:
234
+ logger.warning(
235
+ "No GitHub token available \u2014 cannot post to %s/%s#%d. "
236
+ "Run 'opencodereview auth login' or set GITHUB_TOKEN.",
237
+ owner, repo_name, pr_number,
238
+ )
239
+ if state.verdict:
240
+ logger.info("[WOULD POST] Verdict: %s", state.verdict.summary)
241
+ for f in postable_findings:
242
+ logger.info(
243
+ "[WOULD POST] %s:%d\u2013%d %s \u2014 %s",
244
+ f.file_path, f.line_start, f.line_end,
245
+ f.severity.value, f.comment[:60],
246
+ )
247
+ return {"posting_result": {"status": "dry_run", "inline_posted": 0, "fallback_posted": 0, "failed": len(state.final_findings)}}
248
+
249
+ # ── 1. Fetch latest head SHA ─────────────────────────────────────────
250
+ commit_id = _fetch_pr_head_sha(owner, repo_name, pr_number)
251
+ if commit_id is None:
252
+ logger.warning(
253
+ "Could not fetch PR head SHA \u2014 cannot post inline "
254
+ "comments. Falling back to issue-level comments."
255
+ )
256
+
257
+ # ── 2. Post each finding ─────────────────────────────────────────────
258
+ inline_ok = 0
259
+ inline_failed = 0
260
+ fallback_ok = 0
261
+
262
+ for f in postable_findings:
263
+ body = _finding_body(f)
264
+
265
+ if commit_id:
266
+ # Try inline review comment
267
+ if f.line_start == f.line_end:
268
+ ok = _post_review_comment(
269
+ owner, repo_name, pr_number,
270
+ commit_id, f.file_path, f.line_start, "RIGHT", body,
271
+ )
272
+ else:
273
+ # Multi-line: end_line is the "line" param, start_line
274
+ # marks the range start.
275
+ ok = _post_review_comment(
276
+ owner, repo_name, pr_number,
277
+ commit_id, f.file_path, f.line_end, "RIGHT", body,
278
+ start_line=f.line_start,
279
+ )
280
+
281
+ if ok:
282
+ inline_ok += 1
283
+ continue
284
+ inline_failed += 1
285
+
286
+ # Fallback: issue-level comment with stale-line context
287
+ fallback_body = (
288
+ _finding_fallback_body(f) if commit_id else body
289
+ )
290
+ if _post_issue_comment(owner, repo_name, pr_number, fallback_body):
291
+ fallback_ok += 1
292
+
293
+ # ── 3. Post the verdict ──────────────────────────────────────────────
294
+ verdict_posted = False
295
+ if state.verdict:
296
+ verdict_body = _verdict_body(state.verdict.model_dump())
297
+ verdict_posted = _post_issue_comment(owner, repo_name, pr_number, verdict_body)
298
+
299
+ total = len(postable_findings)
300
+ logger.info(
301
+ "Executor: %d/%d inline, %d/%d fallback, verdict %s \u2014 "
302
+ "%s/%s#%d",
303
+ inline_ok, total, fallback_ok, total - inline_ok,
304
+ "posted" if state.verdict else "skipped",
305
+ owner, repo_name, pr_number,
306
+ )
307
+ finding_failed = total - inline_ok - fallback_ok
308
+ verdict_failed = int(state.verdict is not None and not verdict_posted)
309
+ failed = finding_failed + verdict_failed
310
+ # A review is fully posted only when every finding and the verdict were
311
+ # accepted by GitHub. Keep the per-part counts so the API/UI can explain a
312
+ # partial result instead of reporting a misleading success.
313
+ successful_parts = inline_ok + fallback_ok + int(verdict_posted)
314
+ expected_parts = total + int(state.verdict is not None)
315
+ if expected_parts == 0:
316
+ status = "posted"
317
+ elif successful_parts == expected_parts:
318
+ status = "posted"
319
+ elif successful_parts:
320
+ status = "partially_posted"
321
+ else:
322
+ status = "post_failed"
323
+ if withheld and status == "posted":
324
+ status = "partially_posted"
325
+ return {"posting_result": {
326
+ "status": status,
327
+ "withheld_unverified": withheld,
328
+ "total_findings": total,
329
+ "inline_posted": inline_ok,
330
+ "fallback_posted": fallback_ok,
331
+ "failed": failed,
332
+ "finding_failed": finding_failed,
333
+ "verdict_failed": verdict_failed,
334
+ "verdict_posted": verdict_posted,
335
+ "errors": list(_POST_ERRORS),
336
+ }}
nodes/human_approval.py CHANGED
@@ -1,95 +1,95 @@
1
- from __future__ import annotations
2
-
3
- import logging
4
- from typing import Literal
5
-
6
- from langgraph.types import interrupt
7
-
8
- from state import OpenCodeReviewState
9
-
10
- logger = logging.getLogger(__name__)
11
-
12
-
13
- # ─── Approval result that the human returns when resuming ────────────────────
14
-
15
- ApprovalAction = Literal["approve", "reject", "edit"]
16
-
17
-
18
- # ─── Node ────────────────────────────────────────────────────────────────────
19
-
20
-
21
- def human_approval_node(state: OpenCodeReviewState) -> dict:
22
- """Pause graph execution and wait for a human to approve or reject the
23
- review findings before anything is posted to GitHub.
24
-
25
- The value passed to ``interrupt()`` is returned to the caller (the CLI
26
- or frontend). The caller must resume with ``Command(resume=...)`` whose
27
- value becomes the return value of ``interrupt()``.
28
- """
29
- verdict = state.verdict
30
- findings = state.final_findings
31
- repo = state.repo
32
- pr_number = state.pr_number
33
-
34
- logger.info("=== HUMAN APPROVAL REQUIRED ===")
35
- logger.info("Repo: %s | PR #%d", repo, pr_number)
36
-
37
- if verdict:
38
- logger.info(
39
- "Verdict: %s (score=%s, approved=%s)",
40
- verdict.recommendation, verdict.overall_score, verdict.approved,
41
- )
42
- logger.info("Summary: %s", verdict.summary)
43
-
44
- logger.info("Filtered findings: %d", len(findings))
45
- for f in findings:
46
- logger.info(
47
- " [%.2f] %s %s:%d–%d β€” %s",
48
- f.confidence, f.severity.value, f.file_path,
49
- f.line_start, f.line_end, f.comment[:80],
50
- )
51
-
52
- # ── Interrupt: pause here until the human resumes ─────────────────────
53
- interrupt_payload = {
54
- "type": "human_approval",
55
- "repo": repo,
56
- "pr_number": pr_number,
57
- "verdict": verdict.model_dump() if verdict else None,
58
- "findings_count": len(findings),
59
- "findings": [
60
- {
61
- "file_path": f.file_path,
62
- "line_start": f.line_start,
63
- "line_end": f.line_end,
64
- "severity": f.severity.value,
65
- "category": f.category,
66
- "comment": f.comment,
67
- "confidence": f.confidence,
68
- "suggested_fix": f.suggested_fix,
69
- "kind": f.kind,
70
- "evidence_status": f.evidence_status,
71
- "evidence_excerpt": f.evidence_excerpt,
72
- "calibration_note": f.calibration_note,
73
- }
74
- for f in findings
75
- ],
76
- }
77
-
78
- # This call blocks the graph until the human provides input via resume.
79
- # The return value is whatever was passed to `Command(resume=...)`.
80
- human_input: dict = interrupt(interrupt_payload)
81
-
82
- action: ApprovalAction = human_input.get("action", "reject")
83
- logger.info("Human decision: %s", action)
84
-
85
- if action == "reject":
86
- logger.info("Review rejected by human β€” no comments will be posted.")
87
-
88
- if action == "edit":
89
- edited_findings_raw = human_input.get("findings")
90
- if edited_findings_raw:
91
- logger.info("Human edited %d findings before approval.", len(edited_findings_raw))
92
-
93
- return {
94
- "human_approved": (action in {"approve", "edit"}) and not (verdict and verdict.recommendation == "incomplete"),
95
- }
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import Literal
5
+
6
+ from langgraph.types import interrupt
7
+
8
+ from state import OpenCodeReviewState
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ # ─── Approval result that the human returns when resuming ────────────────────
14
+
15
+ ApprovalAction = Literal["approve", "reject", "edit"]
16
+
17
+
18
+ # ─── Node ────────────────────────────────────────────────────────────────────
19
+
20
+
21
+ def human_approval_node(state: OpenCodeReviewState) -> dict:
22
+ """Pause graph execution and wait for a human to approve or reject the
23
+ review findings before anything is posted to GitHub.
24
+
25
+ The value passed to ``interrupt()`` is returned to the caller (the CLI
26
+ or frontend). The caller must resume with ``Command(resume=...)`` whose
27
+ value becomes the return value of ``interrupt()``.
28
+ """
29
+ verdict = state.verdict
30
+ findings = state.final_findings
31
+ repo = state.repo
32
+ pr_number = state.pr_number
33
+
34
+ logger.info("=== HUMAN APPROVAL REQUIRED ===")
35
+ logger.info("Repo: %s | PR #%d", repo, pr_number)
36
+
37
+ if verdict:
38
+ logger.info(
39
+ "Verdict: %s (score=%s, approved=%s)",
40
+ verdict.recommendation, verdict.overall_score, verdict.approved,
41
+ )
42
+ logger.info("Summary: %s", verdict.summary)
43
+
44
+ logger.info("Filtered findings: %d", len(findings))
45
+ for f in findings:
46
+ logger.info(
47
+ " [%.2f] %s %s:%d–%d β€” %s",
48
+ f.confidence, f.severity.value, f.file_path,
49
+ f.line_start, f.line_end, f.comment[:80],
50
+ )
51
+
52
+ # ── Interrupt: pause here until the human resumes ─────────────────────
53
+ interrupt_payload = {
54
+ "type": "human_approval",
55
+ "repo": repo,
56
+ "pr_number": pr_number,
57
+ "verdict": verdict.model_dump() if verdict else None,
58
+ "findings_count": len(findings),
59
+ "findings": [
60
+ {
61
+ "file_path": f.file_path,
62
+ "line_start": f.line_start,
63
+ "line_end": f.line_end,
64
+ "severity": f.severity.value,
65
+ "category": f.category,
66
+ "comment": f.comment,
67
+ "confidence": f.confidence,
68
+ "suggested_fix": f.suggested_fix,
69
+ "kind": f.kind,
70
+ "evidence_status": f.evidence_status,
71
+ "evidence_excerpt": f.evidence_excerpt,
72
+ "calibration_note": f.calibration_note,
73
+ }
74
+ for f in findings
75
+ ],
76
+ }
77
+
78
+ # This call blocks the graph until the human provides input via resume.
79
+ # The return value is whatever was passed to `Command(resume=...)`.
80
+ human_input: dict = interrupt(interrupt_payload)
81
+
82
+ action: ApprovalAction = human_input.get("action", "reject")
83
+ logger.info("Human decision: %s", action)
84
+
85
+ if action == "reject":
86
+ logger.info("Review rejected by human β€” no comments will be posted.")
87
+
88
+ if action == "edit":
89
+ edited_findings_raw = human_input.get("findings")
90
+ if edited_findings_raw:
91
+ logger.info("Human edited %d findings before approval.", len(edited_findings_raw))
92
+
93
+ return {
94
+ "human_approved": (action in {"approve", "edit"}) and not (verdict and verdict.recommendation == "incomplete"),
95
+ }
nodes/security_reviewer.py CHANGED
@@ -1,145 +1,145 @@
1
- from __future__ import annotations
2
-
3
- import time
4
- import logging
5
- import os
6
- from pathlib import Path
7
-
8
- from llm_factory import create_llm
9
- from nodes.finding_quality import calibrate_findings
10
- from nodes.review_runtime import changed_context, invoke_review, stage_result
11
- from pydantic import BaseModel, Field
12
-
13
- from state import Finding, OpenCodeReviewState
14
-
15
- logger = logging.getLogger(__name__)
16
-
17
- GROQ_MODEL = "llama-3.3-70b-versatile"
18
- DEFAULT_TEMPERATURE = 0.0
19
- MAX_CONTEXT_CHARS = 6_000
20
- MAX_FILE_CONTENT_CHARS = 4_000
21
-
22
- # Prompt version β€” tied to the file on disk
23
- PROMPT_VERSION = "v1"
24
- PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"security_{PROMPT_VERSION}.txt"
25
-
26
-
27
- # ─── Load prompt from file ──────────────────────────────────────────────────
28
-
29
-
30
- def _load_prompt() -> str:
31
- """Load the system prompt from the versioned prompt file."""
32
- try:
33
- return PROMPT_FILE.read_text(encoding="utf-8")
34
- except FileNotFoundError:
35
- logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
36
- return (
37
- "You are a security-focused code reviewer. "
38
- "Analyse the PR diff for security vulnerabilities: injection, "
39
- "secrets, unsafe deserialisation, auth issues, input validation, "
40
- "cryptographic misuse, and information disclosure. "
41
- "Return a list of findings."
42
- )
43
-
44
-
45
- SYSTEM_PROMPT = _load_prompt()
46
-
47
-
48
- # ─── Wrapper schema ──────────────────────────────────────────────────────────
49
-
50
-
51
- class SecurityReview(BaseModel):
52
- """Security issues found during code review."""
53
- findings: list[Finding] = Field(
54
- default_factory=list,
55
- description="Security issues found in the PR diff.",
56
- )
57
-
58
-
59
- # ─── Prompt builder ─────────────────────────────────────────────────────────
60
-
61
-
62
- def _build_prompt(state: OpenCodeReviewState) -> str:
63
- lines: list[str] = []
64
-
65
- lines.append("## Diff\n```diff")
66
- lines.append(state.diff or "")
67
- lines.append("```\n")
68
-
69
- if state.changed_files:
70
- lines.append("## Changed files\n")
71
- for cf in state.changed_files:
72
- lines.append(f"### {cf.path} ({cf.status})")
73
- content = changed_context(cf, state.review_mode)
74
- if len(content) > MAX_FILE_CONTENT_CHARS:
75
- content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
76
- lines.append(f"```\n{content}\n```\n")
77
-
78
- if state.context_chunks:
79
- lines.append("## Retrieved context\n")
80
- ctx_chars = 0
81
- for chunk in state.context_chunks:
82
- snippet = chunk.content
83
- if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
84
- remaining = MAX_CONTEXT_CHARS - ctx_chars
85
- if remaining > 200:
86
- lines.append(f"> {snippet[:remaining]}… (truncated)")
87
- break
88
- prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
89
- lines.append(f"> [{prefix}]: {snippet}")
90
- ctx_chars += len(snippet)
91
-
92
- return "\n".join(lines)
93
-
94
-
95
- # ─── Node ────────────────────────────────────────────────────────────────────
96
-
97
-
98
- def security_reviewer_node(state: OpenCodeReviewState) -> dict:
99
- started = time.monotonic()
100
- if not state.diff:
101
- logger.info("No diff to review β€” skipping security review")
102
- return {}
103
-
104
- try:
105
- llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
106
- except ValueError as exc:
107
- logger.warning("LLM unavailable β€” skipping security review: %s", exc)
108
- return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
109
-
110
- user_prompt = _build_prompt(state)
111
- logger.info(
112
- "Invoking security reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
113
- _human_size(len(state.diff or "")),
114
- len(state.context_chunks),
115
- PROMPT_VERSION,
116
- )
117
-
118
- try:
119
- messages = [
120
- {"role": "system", "content": SYSTEM_PROMPT},
121
- {"role": "user", "content": user_prompt},
122
- ]
123
- result: SecurityReview = invoke_review(llm, SecurityReview, messages, mode=state.review_mode) # type: ignore[assignment]
124
- except Exception as exc:
125
- logger.warning("Security review LLM call failed: %s", exc)
126
- return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
127
-
128
- result.findings = calibrate_findings(result.findings, state)
129
- if result.findings:
130
- logger.info("Security review found %d issue(s)", len(result.findings))
131
- for f in result.findings:
132
- logger.debug(" [%.2f] %s:%d–%d β€” %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
133
- else:
134
- logger.info("Security review found no issues")
135
-
136
- return {"findings": result.findings, "review_stages": [stage_result("security", started, llm=llm)]}
137
-
138
-
139
- def _human_size(bytes_: int) -> str:
140
- if bytes_ < 1024:
141
- return f"{bytes_} B"
142
- elif bytes_ < 1024 * 1024:
143
- return f"{bytes_ / 1024:.1f} KiB"
144
- else:
145
- return f"{bytes_ / (1024 * 1024):.1f} MiB"
 
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ import logging
5
+ import os
6
+ from pathlib import Path
7
+
8
+ from llm_factory import create_llm
9
+ from nodes.finding_quality import calibrate_findings
10
+ from nodes.review_runtime import changed_context, invoke_review, stage_result
11
+ from pydantic import BaseModel, Field
12
+
13
+ from state import Finding, OpenCodeReviewState
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ GROQ_MODEL = "llama-3.3-70b-versatile"
18
+ DEFAULT_TEMPERATURE = 0.0
19
+ MAX_CONTEXT_CHARS = 6_000
20
+ MAX_FILE_CONTENT_CHARS = 4_000
21
+
22
+ # Prompt version β€” tied to the file on disk
23
+ PROMPT_VERSION = "v1"
24
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"security_{PROMPT_VERSION}.txt"
25
+
26
+
27
+ # ─── Load prompt from file ──────────────────────────────────────────────────
28
+
29
+
30
+ def _load_prompt() -> str:
31
+ """Load the system prompt from the versioned prompt file."""
32
+ try:
33
+ return PROMPT_FILE.read_text(encoding="utf-8")
34
+ except FileNotFoundError:
35
+ logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
36
+ return (
37
+ "You are a security-focused code reviewer. "
38
+ "Analyse the PR diff for security vulnerabilities: injection, "
39
+ "secrets, unsafe deserialisation, auth issues, input validation, "
40
+ "cryptographic misuse, and information disclosure. "
41
+ "Return a list of findings."
42
+ )
43
+
44
+
45
+ SYSTEM_PROMPT = _load_prompt()
46
+
47
+
48
+ # ─── Wrapper schema ──────────────────────────────────────────────────────────
49
+
50
+
51
+ class SecurityReview(BaseModel):
52
+ """Security issues found during code review."""
53
+ findings: list[Finding] = Field(
54
+ default_factory=list,
55
+ description="Security issues found in the PR diff.",
56
+ )
57
+
58
+
59
+ # ─── Prompt builder ─────────────────────────────────────────────────────────
60
+
61
+
62
+ def _build_prompt(state: OpenCodeReviewState) -> str:
63
+ lines: list[str] = []
64
+
65
+ lines.append("## Diff\n```diff")
66
+ lines.append(state.diff or "")
67
+ lines.append("```\n")
68
+
69
+ if state.changed_files:
70
+ lines.append("## Changed files\n")
71
+ for cf in state.changed_files:
72
+ lines.append(f"### {cf.path} ({cf.status})")
73
+ content = changed_context(cf, state.review_mode)
74
+ if len(content) > MAX_FILE_CONTENT_CHARS:
75
+ content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
76
+ lines.append(f"```\n{content}\n```\n")
77
+
78
+ if state.context_chunks:
79
+ lines.append("## Retrieved context\n")
80
+ ctx_chars = 0
81
+ for chunk in state.context_chunks:
82
+ snippet = chunk.content
83
+ if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
84
+ remaining = MAX_CONTEXT_CHARS - ctx_chars
85
+ if remaining > 200:
86
+ lines.append(f"> {snippet[:remaining]}… (truncated)")
87
+ break
88
+ prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
89
+ lines.append(f"> [{prefix}]: {snippet}")
90
+ ctx_chars += len(snippet)
91
+
92
+ return "\n".join(lines)
93
+
94
+
95
+ # ─── Node ────────────────────────────────────────────────────────────────────
96
+
97
+
98
+ def security_reviewer_node(state: OpenCodeReviewState) -> dict:
99
+ started = time.monotonic()
100
+ if not state.diff:
101
+ logger.info("No diff to review β€” skipping security review")
102
+ return {}
103
+
104
+ try:
105
+ llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
106
+ except ValueError as exc:
107
+ logger.warning("LLM unavailable β€” skipping security review: %s", exc)
108
+ return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
109
+
110
+ user_prompt = _build_prompt(state)
111
+ logger.info(
112
+ "Invoking security reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
113
+ _human_size(len(state.diff or "")),
114
+ len(state.context_chunks),
115
+ PROMPT_VERSION,
116
+ )
117
+
118
+ try:
119
+ messages = [
120
+ {"role": "system", "content": SYSTEM_PROMPT},
121
+ {"role": "user", "content": user_prompt},
122
+ ]
123
+ result: SecurityReview = invoke_review(llm, SecurityReview, messages, mode=state.review_mode) # type: ignore[assignment]
124
+ except Exception as exc:
125
+ logger.warning("Security review LLM call failed: %s", exc)
126
+ return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
127
+
128
+ result.findings = calibrate_findings(result.findings, state)
129
+ if result.findings:
130
+ logger.info("Security review found %d issue(s)", len(result.findings))
131
+ for f in result.findings:
132
+ logger.debug(" [%.2f] %s:%d–%d β€” %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
133
+ else:
134
+ logger.info("Security review found no issues")
135
+
136
+ return {"findings": result.findings, "review_stages": [stage_result("security", started, llm=llm)]}
137
+
138
+
139
+ def _human_size(bytes_: int) -> str:
140
+ if bytes_ < 1024:
141
+ return f"{bytes_} B"
142
+ elif bytes_ < 1024 * 1024:
143
+ return f"{bytes_ / 1024:.1f} KiB"
144
+ else:
145
+ return f"{bytes_ / (1024 * 1024):.1f} MiB"
nodes/test_coverage_reviewer.py CHANGED
@@ -1,152 +1,152 @@
1
- from __future__ import annotations
2
-
3
- import time
4
- import logging
5
- import os
6
- from pathlib import Path
7
-
8
- from llm_factory import create_llm
9
- from nodes.finding_quality import calibrate_findings
10
- from nodes.review_runtime import changed_context, invoke_review, stage_result
11
- from pydantic import BaseModel, Field
12
-
13
- from state import Finding, OpenCodeReviewState
14
-
15
- logger = logging.getLogger(__name__)
16
-
17
- GROQ_MODEL = "llama-3.3-70b-versatile"
18
- DEFAULT_TEMPERATURE = 0.0
19
- MAX_CONTEXT_CHARS = 6_000
20
- MAX_FILE_CONTENT_CHARS = 4_000
21
-
22
- # Prompt version β€” tied to the file on disk
23
- PROMPT_VERSION = "v1"
24
- PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"test_coverage_{PROMPT_VERSION}.txt"
25
-
26
-
27
- # ─── Load prompt from file ──────────────────────────────────────────────────
28
-
29
-
30
- def _load_prompt() -> str:
31
- """Load the system prompt from the versioned prompt file."""
32
- try:
33
- return PROMPT_FILE.read_text(encoding="utf-8")
34
- except FileNotFoundError:
35
- logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
36
- return (
37
- "You are a code reviewer focused on test coverage. "
38
- "Analyse the PR diff and determine whether the changed logic "
39
- "has adequate test coverage. Return a list of findings."
40
- )
41
-
42
-
43
- SYSTEM_PROMPT = _load_prompt()
44
-
45
-
46
- # ─── Wrapper schema ──────────────────────────────────────────────────────────
47
-
48
-
49
- class TestCoverageReview(BaseModel):
50
- """Test-coverage gaps found during code review."""
51
- findings: list[Finding] = Field(
52
- default_factory=list,
53
- description="Test-coverage issues found in the PR diff.",
54
- )
55
-
56
-
57
- # ─── Prompt builder ─────────────────────────────────────────────────────────
58
-
59
-
60
- def _build_prompt(state: OpenCodeReviewState) -> str:
61
- lines: list[str] = []
62
-
63
- lines.append("## Diff\n```diff")
64
- lines.append(state.diff or "")
65
- lines.append("```\n")
66
-
67
- if state.changed_files:
68
- lines.append("## Changed files\n")
69
- for cf in state.changed_files:
70
- lines.append(f"### {cf.path} ({cf.status})")
71
- content = changed_context(cf, state.review_mode)
72
- if len(content) > MAX_FILE_CONTENT_CHARS:
73
- content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
74
- lines.append(f"```\n{content}\n```\n")
75
-
76
- if state.context_chunks:
77
- lines.append("## Retrieved context\n")
78
- ctx_chars = 0
79
- for chunk in state.context_chunks:
80
- snippet = chunk.content
81
- if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
82
- remaining = MAX_CONTEXT_CHARS - ctx_chars
83
- if remaining > 200:
84
- lines.append(f"> {snippet[:remaining]}… (truncated)")
85
- break
86
- prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
87
- lines.append(f"> [{prefix}]: {snippet}")
88
- ctx_chars += len(snippet)
89
-
90
- return "\n".join(lines)
91
-
92
-
93
- # ─── Node ────────────────────────────────────────────────────────────────────
94
-
95
-
96
- def test_coverage_reviewer_node(state: OpenCodeReviewState) -> dict:
97
- started = time.monotonic()
98
- if not state.diff:
99
- logger.info("No diff to review β€” skipping test-coverage review")
100
- return {}
101
-
102
- # Fast mode avoids a test specialist for documentation-only changes.
103
- # Security and correctness still run; executable/config/unknown files
104
- # always retain all reviewers, as does Thorough mode.
105
- if state.review_mode == 'fast' and state.changed_files and all(
106
- cf.path.lower().endswith(('.md', '.rst', '.txt')) for cf in state.changed_files
107
- ):
108
- return {'review_stages': [{'reviewer': 'test_coverage', 'status': 'skipped',
109
- 'reason': 'Fast mode: documentation-only changes', 'duration_seconds': 0.0, 'model': ''}]}
110
-
111
- try:
112
- llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
113
- except ValueError as exc:
114
- logger.warning("LLM unavailable β€” skipping test-coverage review: %s", exc)
115
- return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
116
-
117
- user_prompt = _build_prompt(state)
118
- logger.info(
119
- "Invoking test-coverage reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
120
- _human_size(len(state.diff or "")),
121
- len(state.context_chunks),
122
- PROMPT_VERSION,
123
- )
124
-
125
- try:
126
- messages = [
127
- {"role": "system", "content": SYSTEM_PROMPT},
128
- {"role": "user", "content": user_prompt},
129
- ]
130
- result: TestCoverageReview = invoke_review(llm, TestCoverageReview, messages, mode=state.review_mode) # type: ignore[assignment]
131
- except Exception as exc:
132
- logger.warning("Test-coverage review LLM call failed: %s", exc)
133
- return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
134
-
135
- result.findings = calibrate_findings(result.findings, state)
136
- if result.findings:
137
- logger.info("Test-coverage review found %d issue(s)", len(result.findings))
138
- for f in result.findings:
139
- logger.debug(" [%.2f] %s:%d–%d β€” %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
140
- else:
141
- logger.info("Test-coverage review found no issues")
142
-
143
- return {"findings": result.findings, "review_stages": [stage_result("test_coverage", started, llm=llm)]}
144
-
145
-
146
- def _human_size(bytes_: int) -> str:
147
- if bytes_ < 1024:
148
- return f"{bytes_} B"
149
- elif bytes_ < 1024 * 1024:
150
- return f"{bytes_ / 1024:.1f} KiB"
151
- else:
152
- return f"{bytes_ / (1024 * 1024):.1f} MiB"
 
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ import logging
5
+ import os
6
+ from pathlib import Path
7
+
8
+ from llm_factory import create_llm
9
+ from nodes.finding_quality import calibrate_findings
10
+ from nodes.review_runtime import changed_context, invoke_review, stage_result
11
+ from pydantic import BaseModel, Field
12
+
13
+ from state import Finding, OpenCodeReviewState
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ GROQ_MODEL = "llama-3.3-70b-versatile"
18
+ DEFAULT_TEMPERATURE = 0.0
19
+ MAX_CONTEXT_CHARS = 6_000
20
+ MAX_FILE_CONTENT_CHARS = 4_000
21
+
22
+ # Prompt version β€” tied to the file on disk
23
+ PROMPT_VERSION = "v1"
24
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"test_coverage_{PROMPT_VERSION}.txt"
25
+
26
+
27
+ # ─── Load prompt from file ──────────────────────────────────────────────────
28
+
29
+
30
+ def _load_prompt() -> str:
31
+ """Load the system prompt from the versioned prompt file."""
32
+ try:
33
+ return PROMPT_FILE.read_text(encoding="utf-8")
34
+ except FileNotFoundError:
35
+ logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
36
+ return (
37
+ "You are a code reviewer focused on test coverage. "
38
+ "Analyse the PR diff and determine whether the changed logic "
39
+ "has adequate test coverage. Return a list of findings."
40
+ )
41
+
42
+
43
+ SYSTEM_PROMPT = _load_prompt()
44
+
45
+
46
+ # ─── Wrapper schema ──────────────────────────────────────────────────────────
47
+
48
+
49
+ class TestCoverageReview(BaseModel):
50
+ """Test-coverage gaps found during code review."""
51
+ findings: list[Finding] = Field(
52
+ default_factory=list,
53
+ description="Test-coverage issues found in the PR diff.",
54
+ )
55
+
56
+
57
+ # ─── Prompt builder ─────────────────────────────────────────────────────────
58
+
59
+
60
+ def _build_prompt(state: OpenCodeReviewState) -> str:
61
+ lines: list[str] = []
62
+
63
+ lines.append("## Diff\n```diff")
64
+ lines.append(state.diff or "")
65
+ lines.append("```\n")
66
+
67
+ if state.changed_files:
68
+ lines.append("## Changed files\n")
69
+ for cf in state.changed_files:
70
+ lines.append(f"### {cf.path} ({cf.status})")
71
+ content = changed_context(cf, state.review_mode)
72
+ if len(content) > MAX_FILE_CONTENT_CHARS:
73
+ content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
74
+ lines.append(f"```\n{content}\n```\n")
75
+
76
+ if state.context_chunks:
77
+ lines.append("## Retrieved context\n")
78
+ ctx_chars = 0
79
+ for chunk in state.context_chunks:
80
+ snippet = chunk.content
81
+ if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
82
+ remaining = MAX_CONTEXT_CHARS - ctx_chars
83
+ if remaining > 200:
84
+ lines.append(f"> {snippet[:remaining]}… (truncated)")
85
+ break
86
+ prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
87
+ lines.append(f"> [{prefix}]: {snippet}")
88
+ ctx_chars += len(snippet)
89
+
90
+ return "\n".join(lines)
91
+
92
+
93
+ # ─── Node ────────────────────────────────────────────────────────────────────
94
+
95
+
96
+ def test_coverage_reviewer_node(state: OpenCodeReviewState) -> dict:
97
+ started = time.monotonic()
98
+ if not state.diff:
99
+ logger.info("No diff to review β€” skipping test-coverage review")
100
+ return {}
101
+
102
+ # Fast mode avoids a test specialist for documentation-only changes.
103
+ # Security and correctness still run; executable/config/unknown files
104
+ # always retain all reviewers, as does Thorough mode.
105
+ if state.review_mode == 'fast' and state.changed_files and all(
106
+ cf.path.lower().endswith(('.md', '.rst', '.txt')) for cf in state.changed_files
107
+ ):
108
+ return {'review_stages': [{'reviewer': 'test_coverage', 'status': 'skipped',
109
+ 'reason': 'Fast mode: documentation-only changes', 'duration_seconds': 0.0, 'model': ''}]}
110
+
111
+ try:
112
+ llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
113
+ except ValueError as exc:
114
+ logger.warning("LLM unavailable β€” skipping test-coverage review: %s", exc)
115
+ return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
116
+
117
+ user_prompt = _build_prompt(state)
118
+ logger.info(
119
+ "Invoking test-coverage reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
120
+ _human_size(len(state.diff or "")),
121
+ len(state.context_chunks),
122
+ PROMPT_VERSION,
123
+ )
124
+
125
+ try:
126
+ messages = [
127
+ {"role": "system", "content": SYSTEM_PROMPT},
128
+ {"role": "user", "content": user_prompt},
129
+ ]
130
+ result: TestCoverageReview = invoke_review(llm, TestCoverageReview, messages, mode=state.review_mode) # type: ignore[assignment]
131
+ except Exception as exc:
132
+ logger.warning("Test-coverage review LLM call failed: %s", exc)
133
+ return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
134
+
135
+ result.findings = calibrate_findings(result.findings, state)
136
+ if result.findings:
137
+ logger.info("Test-coverage review found %d issue(s)", len(result.findings))
138
+ for f in result.findings:
139
+ logger.debug(" [%.2f] %s:%d–%d β€” %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
140
+ else:
141
+ logger.info("Test-coverage review found no issues")
142
+
143
+ return {"findings": result.findings, "review_stages": [stage_result("test_coverage", started, llm=llm)]}
144
+
145
+
146
+ def _human_size(bytes_: int) -> str:
147
+ if bytes_ < 1024:
148
+ return f"{bytes_} B"
149
+ elif bytes_ < 1024 * 1024:
150
+ return f"{bytes_ / 1024:.1f} KiB"
151
+ else:
152
+ return f"{bytes_ / (1024 * 1024):.1f} MiB"
observability.py CHANGED
@@ -1,797 +1,797 @@
1
- #!/usr/bin/env python3
2
- """Observability & monitoring for OpenCodeReview.
3
-
4
- Provides a single-entry-point module for all tracing, cost tracking,
5
- metadata attribution, health checks, and alerting concerns.
6
-
7
- Backends
8
- --------
9
- * **LangSmith** β€” automatic via ``LANGSMITH_API_KEY`` / ``LANGSMITH_PROJECT``
10
- (also accepts legacy ``LANGCHAIN_API_KEY`` for back-compat) env vars.
11
- LangGraph/LangChain reads these at import time and starts tracing
12
- without any per-call code.
13
- * **Langfuse** β€” explicit ``CallbackHandler`` instantiated only when
14
- ``LANGFUSE_PUBLIC_KEY`` and ``LANGFUSE_SECRET_KEY`` are set.
15
-
16
- Usage
17
- -----
18
- from observability import get_langfuse_handler, build_run_metadata
19
-
20
- handler = get_langfuse_handler()
21
- metadata = build_run_metadata(source="cli", repo="org/repo", pr_number=42)
22
- config = {"configurable": {"thread_id": "..."}, "metadata": metadata}
23
- if handler:
24
- config["callbacks"] = [handler]
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- import logging
30
- import os
31
- import platform
32
- import time
33
- import uuid
34
- from contextlib import contextmanager
35
- from datetime import datetime, timezone
36
- from typing import Any, Generator, Optional
37
-
38
- logger = logging.getLogger(__name__)
39
-
40
- # ─── LangSmith (automatic, env-var-driven) ──────────────────────────────────
41
-
42
-
43
- def is_langsmith_enabled() -> bool:
44
- """Return True if LangSmith tracing is configured via env vars.
45
-
46
- Checks both the new ``LANGSMITH_API_KEY`` (preferred) and legacy
47
- ``LANGCHAIN_API_KEY`` env vars for backward compatibility.
48
- """
49
- return bool(
50
- os.environ.get("LANGSMITH_API_KEY", "").strip()
51
- or os.environ.get("LANGCHAIN_API_KEY", "").strip()
52
- )
53
-
54
-
55
- def enable_langsmith(api_key: str, project: str = "") -> None:
56
- """Set the environment variables that LangSmith reads at runtime.
57
-
58
- Per the official LangSmith docs (https://docs.langchain.com/langsmith/trace-with-langgraph):
59
- the modern env vars are ``LANGSMITH_TRACING`` and ``LANGSMITH_API_KEY``.
60
- We also set the legacy ``LANGCHAIN_*`` vars for backward compatibility
61
- with older LangChain versions.
62
-
63
- Call this at startup **before** any LangChain/LangGraph imports so that
64
- the tracing is active from the first call.
65
- """
66
- # Modern env vars (required by langsmith-sdk >= 0.7)
67
- os.environ["LANGSMITH_TRACING"] = "true"
68
- os.environ["LANGSMITH_ENDPOINT"] = os.environ.get(
69
- "LANGSMITH_ENDPOINT", "https://api.smith.langchain.com"
70
- )
71
- os.environ["LANGSMITH_API_KEY"] = api_key
72
- # Legacy env vars (backward compat with older LangChain)
73
- os.environ["LANGCHAIN_TRACING_V2"] = "true"
74
- os.environ["LANGCHAIN_API_KEY"] = api_key
75
- if project:
76
- os.environ["LANGSMITH_PROJECT"] = project
77
- os.environ["LANGCHAIN_PROJECT"] = project
78
- logger.info(
79
- "LangSmith tracing enabled (project=%s)",
80
- project or os.environ.get("LANGSMITH_PROJECT", "default"),
81
- )
82
-
83
-
84
- def disable_langsmith() -> None:
85
- """Remove LangSmith env vars so tracing stops."""
86
- # Modern vars
87
- os.environ.pop("LANGSMITH_TRACING", None)
88
- os.environ.pop("LANGSMITH_ENDPOINT", None)
89
- os.environ.pop("LANGSMITH_API_KEY", None)
90
- # Legacy vars
91
- os.environ.pop("LANGCHAIN_TRACING_V2", None)
92
- os.environ.pop("LANGCHAIN_API_KEY", None)
93
- # Keep project name in case user wants to set it separately
94
-
95
-
96
- # ─── Langfuse (explicit callback) ──────────────────────────────────────────
97
-
98
-
99
- def is_langfuse_enabled() -> bool:
100
- """Return True if Langfuse keys are present in the environment."""
101
- pk = os.environ.get("LANGFUSE_PUBLIC_KEY", "").strip()
102
- sk = os.environ.get("LANGFUSE_SECRET_KEY", "").strip()
103
- return bool(pk and sk)
104
-
105
-
106
- def get_langfuse_handler():
107
- """Return a bare Langfuse ``CallbackHandler`` if keys are configured, else None.
108
-
109
- In langfuse v4+ the ``CallbackHandler`` constructor only accepts
110
- ``public_key`` and ``trace_context`` β€” trace-level metadata (name, tags,
111
- user_id, session_id, metadata) is set via the ``propagate_attributes()``
112
- context manager instead. Use :func:`langfuse_trace` to wrap your graph
113
- execution with proper trace attributes.
114
- """
115
- if not is_langfuse_enabled():
116
- return None
117
-
118
- try:
119
- from langfuse.langchain import CallbackHandler
120
-
121
- # CallbackHandler reads env vars automatically in v4+.
122
- # No trace metadata params are passed β€” those go through
123
- # propagate_attributes() instead.
124
- return CallbackHandler()
125
- except ImportError:
126
- logger.warning(
127
- "langfuse not available β€” skipping tracing",
128
- exc_info=True,
129
- )
130
- return None
131
- except Exception as exc:
132
- logger.warning(
133
- "Failed to initialise Langfuse handler: %s",
134
- exc,
135
- exc_info=True,
136
- )
137
- return None
138
-
139
-
140
- @contextmanager
141
- def langfuse_trace(
142
- trace_name: str = "opencodereview",
143
- tags: Optional[list[str]] = None,
144
- user_id: Optional[str] = None,
145
- session_id: Optional[str] = None,
146
- metadata: Optional[dict[str, Any]] = None,
147
- ) -> Generator[Any, None, None]:
148
- """Context manager that wraps a LangGraph execution block in Langfuse trace attributes.
149
-
150
- In langfuse v4+, trace-level metadata (name, tags, user_id, session_id,
151
- metadata) must be set via the ``propagate_attributes()`` context manager
152
- rather than passed to ``CallbackHandler()``. This helper creates the
153
- handler and the ``propagate_attributes`` wrapper in one step.
154
-
155
- Usage
156
- -----
157
- with langfuse_trace(
158
- trace_name="opencodereview/review/psf/requests#42",
159
- tags=["gradio_ui", "psf/requests"],
160
- session_id=thread_id,
161
- metadata={"repo": "psf/requests", "pr_number": 42},
162
- ) as handler:
163
- if handler:
164
- config["callbacks"].append(handler)
165
- graph.stream(initial_state, config)
166
- """
167
- handler = None
168
- if not is_langfuse_enabled():
169
- yield None
170
- return
171
-
172
- try:
173
- from langfuse.langchain import CallbackHandler
174
-
175
- handler = CallbackHandler()
176
- except Exception:
177
- yield None
178
- return
179
-
180
- # Build propagate_attributes kwargs
181
- attrs: dict[str, Any] = {}
182
- if trace_name:
183
- attrs["trace_name"] = trace_name
184
- if tags:
185
- attrs["tags"] = tags
186
- if user_id:
187
- attrs["user_id"] = user_id
188
- if session_id:
189
- attrs["session_id"] = session_id
190
- if metadata:
191
- attrs["metadata"] = metadata
192
-
193
- if attrs:
194
- try:
195
- from langfuse import propagate_attributes as _propagate_attributes
196
- except Exception as exc:
197
- logger.debug(
198
- "propagate_attributes not available β€” yielding bare handler: %s",
199
- exc,
200
- )
201
- yield handler
202
- return
203
-
204
- # yield is OUTSIDE try/except so user-code exceptions propagate
205
- with _propagate_attributes(**attrs):
206
- yield handler
207
- else:
208
- yield handler
209
-
210
-
211
- # ─── Run metadata ──────────────────────────────────────────────────────────
212
-
213
-
214
- def build_run_metadata(
215
- source: str = "cli",
216
- repo: str = "",
217
- pr_number: int = 0,
218
- session_id: Optional[str] = None,
219
- user_id: Optional[str] = None,
220
- prompt_versions: Optional[dict[str, str]] = None,
221
- extra: Optional[dict[str, Any]] = None,
222
- ) -> dict[str, Any]:
223
- """Build a metadata dict attached to every trace/span.
224
-
225
- Parameters
226
- ----------
227
- source : str
228
- ``"cli"`` or ``"gradio_ui"``.
229
- repo : str
230
- GitHub repository being reviewed (e.g. ``"psf/requests"``).
231
- pr_number : int
232
- PR number being reviewed.
233
- session_id : str or None
234
- Unique session / thread identifier.
235
- user_id : str or None
236
- GitHub username (CLI) or anonymised token (Gradio).
237
- prompt_versions : dict or None
238
- Map of reviewer name β†’ prompt file version (e.g.
239
- ``{"correctness": "v1", "security": "v1"}``).
240
- extra : dict or None
241
- Any additional key-value pairs to attach.
242
-
243
- Returns
244
- -------
245
- dict
246
- Flat metadata dict suitable for ``config["metadata"]``.
247
- """
248
- meta: dict[str, Any] = {
249
- "source": source,
250
- "app": "opencodereview",
251
- "host": platform.node(),
252
- "timestamp": datetime.now(timezone.utc).isoformat(),
253
- }
254
-
255
- if repo:
256
- meta["repo"] = repo
257
- if pr_number:
258
- meta["pr_number"] = pr_number
259
- if session_id:
260
- meta["session_id"] = session_id
261
- if user_id:
262
- meta["user_id"] = user_id
263
- if prompt_versions:
264
- meta["prompt_versions"] = prompt_versions
265
- if extra:
266
- meta.update(extra)
267
-
268
- return meta
269
-
270
-
271
- # ─── Cost tracking ─────────────────────────────────────────────────────────
272
-
273
-
274
- # Per-1M-token pricing (USD), keyed by model name.
275
- # Groq source: https://console.groq.com/docs/pricing (as of 2025-07)
276
- # NOTE: Gemini rates below are APPROXIMATE published per-1M-token rates
277
- # (USD) and may drift over time β€” verify against Google's pricing page
278
- # before relying on them for billing reconciliation.
279
- MODEL_PRICING: dict[str, dict[str, float]] = {
280
- # ── Groq ──────────────────────────────────────────────────���───────
281
- "llama-3.3-70b-versatile": {"input": 0.59, "output": 0.79},
282
- # ── Google Gemini ─────────────────────────────────────────────────
283
- # Approximate published per-1M-token rates (USD) for Gemini Flash-Lite.
284
- "gemini-3.1-flash-lite": {"input": 0.10, "output": 0.40},
285
- # Fallback for unknown models β€” pessimistic estimate
286
- "__default__": {"input": 1.00, "output": 1.00},
287
- }
288
-
289
- # Backward-compatible alias β€” previously Groq-only; now the shared table
290
- # so any external references keep resolving.
291
- GROQ_PRICING = MODEL_PRICING
292
-
293
-
294
- def estimate_model_cost(
295
- model: str,
296
- input_tokens: int,
297
- output_tokens: int,
298
- ) -> float | None:
299
- """Estimate the USD cost of an LLM call by looking up ``MODEL_PRICING``.
300
-
301
- Parameters
302
- ----------
303
- model : str
304
- Model name. Unknown models return None; free-suffix models have a
305
- zero catalog estimate, never a claimed billing charge.
306
- input_tokens : int
307
- Number of tokens in the prompt (system + user messages).
308
- output_tokens : int
309
- Number of tokens in the completion.
310
-
311
- Returns
312
- -------
313
- float
314
- Estimated cost in USD, or None when no known price is available.
315
- """
316
- if model.endswith(":free"):
317
- return 0.0
318
- pricing = MODEL_PRICING.get(model)
319
- if pricing is None:
320
- return None
321
- input_cost = (input_tokens / 1_000_000) * pricing["input"]
322
- output_cost = (output_tokens / 1_000_000) * pricing["output"]
323
- return round(input_cost + output_cost, 6)
324
-
325
-
326
- def estimate_groq_cost(
327
- model: str,
328
- input_tokens: int,
329
- output_tokens: int,
330
- ) -> float | None:
331
- """Estimate the USD cost of a Groq LLM call (backward-compatible).
332
-
333
- Thin wrapper around :func:`estimate_model_cost`. Kept so existing
334
- callers (``app.py``, ``main.py``, :class:`TokenCostCallback`) keep
335
- working unchanged β€” it now also prices Gemini and any other model in
336
- :data:`MODEL_PRICING` correctly instead of using the Groq-only table.
337
- """
338
- return estimate_model_cost(model, input_tokens, output_tokens)
339
-
340
-
341
- def format_cost(cost_usd: float) -> str:
342
- """Format a USD cost for human-readable display."""
343
- if cost_usd < 0.001:
344
- return f"${cost_usd * 1000:.2f}β€―mΒ’"
345
- return f"${cost_usd:.4f}"
346
-
347
-
348
- # ─── Health check helpers ──────────────────────────────────────────────────
349
-
350
-
351
- class HealthStatus:
352
- """Aggregate health of the observability and API connectivity."""
353
-
354
- def __init__(self) -> None:
355
- self.langsmith: bool = is_langsmith_enabled()
356
- self.langfuse: bool = is_langfuse_enabled()
357
- self.groq: bool = bool(os.environ.get("GROQ_API_KEY", "").strip())
358
- self.github: bool = bool(os.environ.get("GITHUB_TOKEN", "").strip())
359
-
360
- @property
361
- def any_tracing(self) -> bool:
362
- return self.langsmith or self.langfuse
363
-
364
- def summary(self) -> dict[str, str]:
365
- """Return a dict of component β†’ status string."""
366
- return {
367
- "LangSmith": "βœ… Active" if self.langsmith else "β›” Not configured",
368
- "Langfuse": "βœ… Active" if self.langfuse else "β›” Not configured",
369
- "Groq API": "βœ… Key set" if self.groq else "β›” No key",
370
- "GitHub API": "βœ… Token set" if self.github else "β›” No token",
371
- }
372
-
373
-
374
- def check_groq_connectivity() -> tuple[bool, str]:
375
- """Lightweight Groq connectivity check β€” does not consume quota.
376
-
377
- Uses ``urllib.request`` from stdlib (no extra dependencies).
378
-
379
- Returns ``(ok, message)``.
380
- """
381
- import json as _json
382
- import urllib.error as _urlerror
383
- import urllib.request as _urlreq
384
-
385
- api_key = os.environ.get("GROQ_API_KEY", "").strip()
386
- if not api_key:
387
- return False, "No GROQ_API_KEY set"
388
-
389
- try:
390
- req = _urlreq.Request(
391
- "https://api.groq.com/openai/v1/models",
392
- headers={
393
- "Authorization": f"Bearer {api_key}",
394
- "Content-Type": "application/json",
395
- },
396
- method="GET",
397
- )
398
- with _urlreq.urlopen(req, timeout=10) as resp:
399
- if resp.status == 200:
400
- data = _json.loads(resp.read().decode("utf-8"))
401
- models = data.get("data", [])
402
- count = len(models)
403
- return True, f"Reachable β€” {count} models available"
404
- else:
405
- return False, f"HTTP {resp.status}"
406
- except _urlerror.HTTPError as exc:
407
- if exc.code == 401:
408
- return False, "Invalid API key (401)"
409
- return False, f"HTTP {exc.code}"
410
- except Exception as exc:
411
- return False, str(exc)
412
-
413
-
414
- def check_langfuse_connectivity() -> tuple[bool, str]:
415
- """Lightweight Langfuse connectivity check.
416
-
417
- Returns ``(ok, message)``.
418
- """
419
- if not is_langfuse_enabled():
420
- return False, "Not configured"
421
-
422
- try:
423
- from langfuse import Langfuse
424
-
425
- lf = Langfuse()
426
- lf.auth_check()
427
- return True, "Connected"
428
- except Exception as exc:
429
- return False, str(exc)
430
-
431
-
432
- # ─── Token cost callback (accumulates LLM usage across a run) ────────────
433
-
434
-
435
- class TokenCostCallback:
436
- """Accumulates per-model token usage & TTFT from LangChain LLM calls.
437
-
438
- Also tracks **TTFT** (Time to First Token) by recording a timestamp
439
- at ``on_chat_model_start`` and computing elapsed time at ``on_llm_end``.
440
- For non-streaming LLM calls this is effectively the full request duration;
441
- for streaming it would be the time to the first chunk.
442
-
443
- Lazily imports ``BaseCallbackHandler`` so that ``observability.py`` can
444
- be imported even when ``langchain-core`` has version incompatibilities
445
- (e.g. on Hugging Face Spaces). Only ``on_llm_end`` is overridden;
446
- all other lifecycle events are ignored.
447
-
448
- Usage
449
- -----
450
- counter = TokenCostCallback()
451
- config["callbacks"] = [counter, langfuse_handler] # if langfuse
452
- ... run graph ...
453
- print(counter.summary())
454
- """
455
-
456
- raise_error: bool = False
457
- ignore_llm: bool = False
458
- ignore_chain: bool = False
459
- ignore_agent: bool = False
460
- ignore_retriever: bool = False
461
- ignore_chat_model: bool = False
462
- ignore_custom_event: bool = False
463
- ignore_retry: bool = False
464
- run_inline: bool = False
465
-
466
- def __init__(self) -> None:
467
- self.usage: list[dict[str, Any]] = []
468
- self._start_times: dict[str, float] = {} # run_id -> timestamp
469
-
470
- @property
471
- def total_input_tokens(self) -> int:
472
- return sum(u.get("input_tokens", 0) for u in self.usage)
473
-
474
- @property
475
- def total_output_tokens(self) -> int:
476
- return sum(u.get("output_tokens", 0) for u in self.usage)
477
-
478
- @property
479
- def total_cost(self) -> float:
480
- return sum(u.get("cost") or 0.0 for u in self.usage)
481
-
482
- @property
483
- def total_ttft(self) -> float:
484
- """Total TTFT across all LLM calls, in seconds."""
485
- ttfts = [u.get("ttft_seconds", 0.0) for u in self.usage if u.get("ttft_seconds") is not None]
486
- return sum(ttfts)
487
-
488
- @property
489
- def avg_ttft(self) -> Optional[float]:
490
- """Average TTFT across all LLM calls, in seconds (None if no calls)."""
491
- ttfts = [u.get("ttft_seconds", 0.0) for u in self.usage if u.get("ttft_seconds") is not None]
492
- if not ttfts:
493
- return None
494
- return sum(ttfts) / len(ttfts)
495
-
496
- def on_chain_start(self, *args, **kwargs) -> None:
497
- pass
498
-
499
- def on_chain_end(self, *args, **kwargs) -> None:
500
- pass
501
-
502
- def on_chat_model_start(self, *args, **kwargs) -> None:
503
- """Record start timestamp for TTFT measurement.
504
-
505
- ``**kwargs`` contains ``run_id`` which we use as the key.
506
- """
507
- run_id = kwargs.get("run_id")
508
- if run_id:
509
- self._start_times[str(run_id)] = time.time()
510
-
511
- def on_llm_start(self, *args, **kwargs) -> None:
512
- """Fallback: record start timestamp if ``on_chat_model_start`` wasn't called."""
513
- run_id = kwargs.get("run_id")
514
- if run_id and str(run_id) not in self._start_times:
515
- self._start_times[str(run_id)] = time.time()
516
-
517
- def on_llm_error(self, error, **kwargs) -> None:
518
- self._cleanup_run(kwargs.get("run_id"))
519
-
520
- def on_chain_error(self, error, **kwargs) -> None:
521
- pass
522
-
523
- def on_tool_error(self, error, **kwargs) -> None:
524
- pass
525
-
526
- def on_retriever_error(self, error, **kwargs) -> None:
527
- pass
528
-
529
- def on_llm_end(self, response, **kwargs) -> None:
530
- """LangChain callback β€” called after each LLM invocation.
531
-
532
- Computes TTFT from the recorded start time and captures token usage.
533
- ``**kwargs`` absorbs ``run_id``, ``parent_run_id``, and other
534
- metadata that LangChain passes to callback handlers.
535
- """
536
- try:
537
- run_key = str(kwargs.get("run_id", ""))
538
-
539
- # Compute TTFT (time from start to first token / completion)
540
- ttft: Optional[float] = None
541
- if run_key in self._start_times:
542
- ttft = round(time.time() - self._start_times.pop(run_key), 3)
543
-
544
- usage = response.llm_output or {}
545
- token_usage = usage.get("token_usage", {}) or {}
546
- model = usage.get("model_name", "") or ""
547
-
548
- input_tokens = token_usage.get("prompt_tokens", 0) or 0
549
- output_tokens = token_usage.get("completion_tokens", 0) or 0
550
-
551
- if input_tokens > 0 or output_tokens > 0:
552
- reported = token_usage.get("cost", usage.get("cost"))
553
- if isinstance(reported, (int, float)) and not isinstance(reported, bool) and reported >= 0:
554
- cost, cost_source = float(reported), "provider_reported"
555
- else:
556
- cost = estimate_model_cost(model, input_tokens, output_tokens)
557
- cost_source = "free_model_estimate" if model.endswith(":free") else "estimated" if cost is not None else "unknown"
558
- entry: dict[str, Any] = {
559
- "model": model,
560
- "input_tokens": input_tokens,
561
- "output_tokens": output_tokens,
562
- "cost": cost,
563
- "cost_source": cost_source,
564
- }
565
- if ttft is not None:
566
- entry["ttft_seconds"] = ttft
567
- self.usage.append(entry)
568
- else:
569
- self._cleanup_run(run_key)
570
- except Exception:
571
- self._cleanup_run(run_key)
572
- pass # Best-effort β€” don't let cost tracking crash the run
573
-
574
- def _cleanup_run(self, run_id: Any) -> None:
575
- """Remove a run_id from the start times map (cleanup on error)."""
576
- if run_id:
577
- self._start_times.pop(str(run_id), None)
578
-
579
- def details(self) -> dict:
580
- sources = {item.get("cost_source", "estimated") for item in self.usage}
581
- complete = bool(self.usage) and "unknown" not in sources
582
- source = next(iter(sources)) if len(sources) == 1 else "mixed" if sources else "unknown"
583
- return {"amount": self.total_cost if complete else None, "currency": "USD", "source": source,
584
- "complete": complete, "calls": len(self.usage), "input_tokens": self.total_input_tokens,
585
- "output_tokens": self.total_output_tokens, "model_response_seconds": round(self.total_ttft, 3)}
586
-
587
- def summary(self) -> str:
588
- """Human-readable attribution; estimates never imply a provider charge."""
589
- details = self.details()
590
- calls = details["calls"]
591
- if not calls:
592
- return "Usage unavailable (no successful model usage captured)"
593
- labels = {"provider_reported": "Provider-reported cost", "free_model_estimate": "Free-model estimate (not billing)",
594
- "estimated": "Estimated cost (not billing)", "mixed": "Mixed measured/estimated cost"}
595
- cost = f"{labels.get(details['source'], 'Cost')}: {format_cost(details['amount'])}" if details['complete'] else "Cost unknown (provider did not report a charge; no matching price)"
596
- parts = [cost, f"{calls} LLM call(s)", f"{self.total_input_tokens:,} in / {self.total_output_tokens:,} out tokens"]
597
- avg = self.avg_ttft
598
- if avg is not None:
599
- parts.append(f"Model response time: {avg:.2f}s avg")
600
- return " Β· ".join(parts)
601
-
602
- def reset(self) -> None:
603
- self.usage.clear()
604
- self._start_times.clear()
605
-
606
-
607
- # ─── Error event logging ─────────────────────────────────────────────────--
608
-
609
-
610
- # ─── Score logging ──────────────────────────────────────────────────────────
611
-
612
-
613
- def _resolve_langfuse_trace_id(handler: Any) -> Optional[str]:
614
- """Resolve the current Langfuse trace ID from handler or context.
615
-
616
- Tries, in order:
617
- 1. ``handler.trace_id`` (langfuse v3-style β€” likely None on v4+)
618
- 2. ``handler.last_trace_id`` (langfuse v4+)
619
- 3. ``Langfuse().get_current_trace_id()`` (langfuse v4+, works
620
- inside ``propagate_attributes`` context)
621
- """
622
- if handler is not None:
623
- try:
624
- tid = getattr(handler, "trace_id", None)
625
- if tid:
626
- return tid
627
- except Exception:
628
- pass
629
- try:
630
- tid = getattr(handler, "last_trace_id", None)
631
- if tid:
632
- return tid
633
- except Exception:
634
- pass
635
-
636
- try:
637
- from opentelemetry import trace
638
- context = trace.get_current_span().get_span_context()
639
- if context.is_valid:
640
- return format(context.trace_id, "032x")
641
- except Exception:
642
- pass
643
-
644
- return None
645
-
646
-
647
- def flush_langfuse() -> None:
648
- """Flush the shared Langfuse client's pending events once per run.
649
-
650
- In langfuse v4+ ``get_client()`` returns a process-wide singleton; callers
651
- (e.g. ``main.py`` after the RAGAS block, ``app.py`` after streaming) should
652
- call this once at the end of a run so queued scores/traces are shipped
653
- before the process exits β€” instead of flushing inside every
654
- :func:`log_langfuse_score` call.
655
-
656
- Set ``OCR_OBSERVABILITY_STRICT=1`` to surface flush failures as exceptions.
657
- """
658
- if not is_langfuse_enabled():
659
- return
660
- try:
661
- from langfuse import get_client # v4 singleton β€” one shared client
662
-
663
- get_client().flush()
664
- except ImportError:
665
- # Missing SDK degrades gracefully β€” tracing is optional.
666
- logger.debug("langfuse SDK not installed β€” flush skipped")
667
- except Exception as exc:
668
- if os.environ.get("OCR_OBSERVABILITY_STRICT") == "1":
669
- raise
670
- logger.error("Failed to flush Langfuse client: %s", exc)
671
-
672
-
673
- def log_langfuse_score(
674
- name: str,
675
- value: float,
676
- comment: Optional[str] = None,
677
- trace_id: Optional[str] = None,
678
- handler: Optional[Any] = None,
679
- ) -> None:
680
- """Log a numeric score to Langfuse, linked to a specific trace.
681
-
682
- Requires Langfuse to be enabled (keys in environment). The score is
683
- associated with a trace by ``trace_id``. If neither ``trace_id`` nor
684
- a resolvable handler is provided, the score is logged without a trace
685
- link (appears in the Scores tab but not on the trace detail page).
686
-
687
- Parameters
688
- ----------
689
- name : str
690
- Score name (e.g. ``"verdict_score"``, ``"findings_count"``).
691
- value : float
692
- Numeric score value.
693
- comment : str or None
694
- Optional human-readable comment.
695
- trace_id : str or None
696
- Explicit trace ID. If ``None``, attempts to resolve via handler.
697
- handler : Langfuse CallbackHandler or None
698
- Langfuse ``CallbackHandler`` from which to extract the trace ID.
699
- """
700
- if not is_langfuse_enabled():
701
- return
702
-
703
- resolved_trace_id = trace_id or _resolve_langfuse_trace_id(handler)
704
- if not resolved_trace_id:
705
- logger.warning("Score %s was not logged: no captured trace ID", name)
706
- return
707
-
708
- # Visibility log: lets you confirm the score will land on the right
709
- # trace (or spot a None that would create an orphaned score).
710
- logger.info("Langfuse trace_id resolved: %s", resolved_trace_id)
711
-
712
- try:
713
- from langfuse import get_client # v4 singleton β€” one shared client
714
-
715
- lf = get_client()
716
- kwargs: dict[str, Any] = {
717
- "name": name,
718
- "value": value,
719
- }
720
- if resolved_trace_id:
721
- kwargs["trace_id"] = resolved_trace_id
722
- if comment:
723
- kwargs["comment"] = comment
724
-
725
- lf.create_score(**kwargs)
726
- # NOTE: do not flush here β€” flushing once per run via
727
- # flush_langfuse() at run-end (called by app.py/main.py owners).
728
- except ImportError:
729
- # Missing SDK degrades gracefully β€” tracing is optional.
730
- logger.debug(
731
- "langfuse SDK not installed β€” score '%s' not logged", name
732
- )
733
- except Exception as exc:
734
- if os.environ.get("OCR_OBSERVABILITY_STRICT") == "1":
735
- raise
736
- logger.error(
737
- "Failed to log Langfuse score '%s'=%.4f (trace_id=%s, comment=%s): %s",
738
- name, value, resolved_trace_id, comment, exc,
739
- )
740
-
741
-
742
- def update_langfuse_trace(
743
- trace_name: Optional[str] = None,
744
- tags: Optional[list[str]] = None,
745
- metadata: Optional[dict[str, Any]] = None,
746
- trace_id: Optional[str] = None,
747
- handler: Optional[Any] = None,
748
- ) -> None:
749
- """No-op in langfuse v4+ β€” trace attributes must be set upfront
750
- via ``propagate_attributes()`` (see :func:`langfuse_trace`).
751
-
752
- In langfuse v4 the trace API no longer supports ``update_trace``.
753
- Trace-level metadata (name, tags, user_id, session_id, metadata)
754
- must be provided at trace creation time via ``propagate_attributes``.
755
- Use :func:`log_langfuse_score` instead for post-hoc annotations
756
- like verdict score or findings count.
757
- """
758
- if resolved_trace_id := (trace_id or _resolve_langfuse_trace_id(handler)):
759
- logger.debug(
760
- "update_langfuse_trace is a no-op in langfuse v4 (trace=%s). "
761
- "Set attributes upfront via langfuse_trace() instead.",
762
- resolved_trace_id,
763
- )
764
- # Dedicated score logging is handled by log_langfuse_score() β€” nothing
765
- # to do here.
766
-
767
-
768
- def log_error_to_backends(
769
- error: Exception,
770
- context: Optional[dict[str, Any]] = None,
771
- ) -> None:
772
- """Log an error event to whichever observability backend(s) are active.
773
-
774
- For LangSmith: logs via LangChain's callback system (automatic).
775
- For Langfuse: creates an identifyable error event via the SDK.
776
-
777
- This function primarily logs to ``logger`` with full traceback and
778
- enriches the log record with context that the tracing backends pick up.
779
-
780
- Parameters
781
- ----------
782
- error : Exception
783
- The exception that occurred.
784
- context : dict or None
785
- Additional context about where/when the error happened.
786
- """
787
- extras = ""
788
- if context:
789
- extras = f" [{', '.join(f'{k}={v}' for k, v in context.items())}]"
790
-
791
- logger.exception(
792
- "OBSERVABILITY-ERROR%s: %s: %s",
793
- extras,
794
- type(error).__name__,
795
- error,
796
- exc_info=error,
797
- )
 
1
+ #!/usr/bin/env python3
2
+ """Observability & monitoring for OpenCodeReview.
3
+
4
+ Provides a single-entry-point module for all tracing, cost tracking,
5
+ metadata attribution, health checks, and alerting concerns.
6
+
7
+ Backends
8
+ --------
9
+ * **LangSmith** β€” automatic via ``LANGSMITH_API_KEY`` / ``LANGSMITH_PROJECT``
10
+ (also accepts legacy ``LANGCHAIN_API_KEY`` for back-compat) env vars.
11
+ LangGraph/LangChain reads these at import time and starts tracing
12
+ without any per-call code.
13
+ * **Langfuse** β€” explicit ``CallbackHandler`` instantiated only when
14
+ ``LANGFUSE_PUBLIC_KEY`` and ``LANGFUSE_SECRET_KEY`` are set.
15
+
16
+ Usage
17
+ -----
18
+ from observability import get_langfuse_handler, build_run_metadata
19
+
20
+ handler = get_langfuse_handler()
21
+ metadata = build_run_metadata(source="cli", repo="org/repo", pr_number=42)
22
+ config = {"configurable": {"thread_id": "..."}, "metadata": metadata}
23
+ if handler:
24
+ config["callbacks"] = [handler]
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import logging
30
+ import os
31
+ import platform
32
+ import time
33
+ import uuid
34
+ from contextlib import contextmanager
35
+ from datetime import datetime, timezone
36
+ from typing import Any, Generator, Optional
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ # ─── LangSmith (automatic, env-var-driven) ──────────────────────────────────
41
+
42
+
43
+ def is_langsmith_enabled() -> bool:
44
+ """Return True if LangSmith tracing is configured via env vars.
45
+
46
+ Checks both the new ``LANGSMITH_API_KEY`` (preferred) and legacy
47
+ ``LANGCHAIN_API_KEY`` env vars for backward compatibility.
48
+ """
49
+ return bool(
50
+ os.environ.get("LANGSMITH_API_KEY", "").strip()
51
+ or os.environ.get("LANGCHAIN_API_KEY", "").strip()
52
+ )
53
+
54
+
55
+ def enable_langsmith(api_key: str, project: str = "") -> None:
56
+ """Set the environment variables that LangSmith reads at runtime.
57
+
58
+ Per the official LangSmith docs (https://docs.langchain.com/langsmith/trace-with-langgraph):
59
+ the modern env vars are ``LANGSMITH_TRACING`` and ``LANGSMITH_API_KEY``.
60
+ We also set the legacy ``LANGCHAIN_*`` vars for backward compatibility
61
+ with older LangChain versions.
62
+
63
+ Call this at startup **before** any LangChain/LangGraph imports so that
64
+ the tracing is active from the first call.
65
+ """
66
+ # Modern env vars (required by langsmith-sdk >= 0.7)
67
+ os.environ["LANGSMITH_TRACING"] = "true"
68
+ os.environ["LANGSMITH_ENDPOINT"] = os.environ.get(
69
+ "LANGSMITH_ENDPOINT", "https://api.smith.langchain.com"
70
+ )
71
+ os.environ["LANGSMITH_API_KEY"] = api_key
72
+ # Legacy env vars (backward compat with older LangChain)
73
+ os.environ["LANGCHAIN_TRACING_V2"] = "true"
74
+ os.environ["LANGCHAIN_API_KEY"] = api_key
75
+ if project:
76
+ os.environ["LANGSMITH_PROJECT"] = project
77
+ os.environ["LANGCHAIN_PROJECT"] = project
78
+ logger.info(
79
+ "LangSmith tracing enabled (project=%s)",
80
+ project or os.environ.get("LANGSMITH_PROJECT", "default"),
81
+ )
82
+
83
+
84
+ def disable_langsmith() -> None:
85
+ """Remove LangSmith env vars so tracing stops."""
86
+ # Modern vars
87
+ os.environ.pop("LANGSMITH_TRACING", None)
88
+ os.environ.pop("LANGSMITH_ENDPOINT", None)
89
+ os.environ.pop("LANGSMITH_API_KEY", None)
90
+ # Legacy vars
91
+ os.environ.pop("LANGCHAIN_TRACING_V2", None)
92
+ os.environ.pop("LANGCHAIN_API_KEY", None)
93
+ # Keep project name in case user wants to set it separately
94
+
95
+
96
+ # ─── Langfuse (explicit callback) ──────────────────────────────────────────
97
+
98
+
99
+ def is_langfuse_enabled() -> bool:
100
+ """Return True if Langfuse keys are present in the environment."""
101
+ pk = os.environ.get("LANGFUSE_PUBLIC_KEY", "").strip()
102
+ sk = os.environ.get("LANGFUSE_SECRET_KEY", "").strip()
103
+ return bool(pk and sk)
104
+
105
+
106
+ def get_langfuse_handler():
107
+ """Return a bare Langfuse ``CallbackHandler`` if keys are configured, else None.
108
+
109
+ In langfuse v4+ the ``CallbackHandler`` constructor only accepts
110
+ ``public_key`` and ``trace_context`` β€” trace-level metadata (name, tags,
111
+ user_id, session_id, metadata) is set via the ``propagate_attributes()``
112
+ context manager instead. Use :func:`langfuse_trace` to wrap your graph
113
+ execution with proper trace attributes.
114
+ """
115
+ if not is_langfuse_enabled():
116
+ return None
117
+
118
+ try:
119
+ from langfuse.langchain import CallbackHandler
120
+
121
+ # CallbackHandler reads env vars automatically in v4+.
122
+ # No trace metadata params are passed β€” those go through
123
+ # propagate_attributes() instead.
124
+ return CallbackHandler()
125
+ except ImportError:
126
+ logger.warning(
127
+ "langfuse not available β€” skipping tracing",
128
+ exc_info=True,
129
+ )
130
+ return None
131
+ except Exception as exc:
132
+ logger.warning(
133
+ "Failed to initialise Langfuse handler: %s",
134
+ exc,
135
+ exc_info=True,
136
+ )
137
+ return None
138
+
139
+
140
+ @contextmanager
141
+ def langfuse_trace(
142
+ trace_name: str = "opencodereview",
143
+ tags: Optional[list[str]] = None,
144
+ user_id: Optional[str] = None,
145
+ session_id: Optional[str] = None,
146
+ metadata: Optional[dict[str, Any]] = None,
147
+ ) -> Generator[Any, None, None]:
148
+ """Context manager that wraps a LangGraph execution block in Langfuse trace attributes.
149
+
150
+ In langfuse v4+, trace-level metadata (name, tags, user_id, session_id,
151
+ metadata) must be set via the ``propagate_attributes()`` context manager
152
+ rather than passed to ``CallbackHandler()``. This helper creates the
153
+ handler and the ``propagate_attributes`` wrapper in one step.
154
+
155
+ Usage
156
+ -----
157
+ with langfuse_trace(
158
+ trace_name="opencodereview/review/psf/requests#42",
159
+ tags=["gradio_ui", "psf/requests"],
160
+ session_id=thread_id,
161
+ metadata={"repo": "psf/requests", "pr_number": 42},
162
+ ) as handler:
163
+ if handler:
164
+ config["callbacks"].append(handler)
165
+ graph.stream(initial_state, config)
166
+ """
167
+ handler = None
168
+ if not is_langfuse_enabled():
169
+ yield None
170
+ return
171
+
172
+ try:
173
+ from langfuse.langchain import CallbackHandler
174
+
175
+ handler = CallbackHandler()
176
+ except Exception:
177
+ yield None
178
+ return
179
+
180
+ # Build propagate_attributes kwargs
181
+ attrs: dict[str, Any] = {}
182
+ if trace_name:
183
+ attrs["trace_name"] = trace_name
184
+ if tags:
185
+ attrs["tags"] = tags
186
+ if user_id:
187
+ attrs["user_id"] = user_id
188
+ if session_id:
189
+ attrs["session_id"] = session_id
190
+ if metadata:
191
+ attrs["metadata"] = metadata
192
+
193
+ if attrs:
194
+ try:
195
+ from langfuse import propagate_attributes as _propagate_attributes
196
+ except Exception as exc:
197
+ logger.debug(
198
+ "propagate_attributes not available β€” yielding bare handler: %s",
199
+ exc,
200
+ )
201
+ yield handler
202
+ return
203
+
204
+ # yield is OUTSIDE try/except so user-code exceptions propagate
205
+ with _propagate_attributes(**attrs):
206
+ yield handler
207
+ else:
208
+ yield handler
209
+
210
+
211
+ # ─── Run metadata ──────────────────────────────────────────────────────────
212
+
213
+
214
+ def build_run_metadata(
215
+ source: str = "cli",
216
+ repo: str = "",
217
+ pr_number: int = 0,
218
+ session_id: Optional[str] = None,
219
+ user_id: Optional[str] = None,
220
+ prompt_versions: Optional[dict[str, str]] = None,
221
+ extra: Optional[dict[str, Any]] = None,
222
+ ) -> dict[str, Any]:
223
+ """Build a metadata dict attached to every trace/span.
224
+
225
+ Parameters
226
+ ----------
227
+ source : str
228
+ ``"cli"`` or ``"gradio_ui"``.
229
+ repo : str
230
+ GitHub repository being reviewed (e.g. ``"psf/requests"``).
231
+ pr_number : int
232
+ PR number being reviewed.
233
+ session_id : str or None
234
+ Unique session / thread identifier.
235
+ user_id : str or None
236
+ GitHub username (CLI) or anonymised token (Gradio).
237
+ prompt_versions : dict or None
238
+ Map of reviewer name β†’ prompt file version (e.g.
239
+ ``{"correctness": "v1", "security": "v1"}``).
240
+ extra : dict or None
241
+ Any additional key-value pairs to attach.
242
+
243
+ Returns
244
+ -------
245
+ dict
246
+ Flat metadata dict suitable for ``config["metadata"]``.
247
+ """
248
+ meta: dict[str, Any] = {
249
+ "source": source,
250
+ "app": "opencodereview",
251
+ "host": platform.node(),
252
+ "timestamp": datetime.now(timezone.utc).isoformat(),
253
+ }
254
+
255
+ if repo:
256
+ meta["repo"] = repo
257
+ if pr_number:
258
+ meta["pr_number"] = pr_number
259
+ if session_id:
260
+ meta["session_id"] = session_id
261
+ if user_id:
262
+ meta["user_id"] = user_id
263
+ if prompt_versions:
264
+ meta["prompt_versions"] = prompt_versions
265
+ if extra:
266
+ meta.update(extra)
267
+
268
+ return meta
269
+
270
+
271
+ # ─── Cost tracking ─────────────────────────────────────────────────────────
272
+
273
+
274
+ # Per-1M-token pricing (USD), keyed by model name.
275
+ # Groq source: https://console.groq.com/docs/pricing (as of 2025-07)
276
+ # NOTE: Gemini rates below are APPROXIMATE published per-1M-token rates
277
+ # (USD) and may drift over time β€” verify against Google's pricing page
278
+ # before relying on them for billing reconciliation.
279
+ MODEL_PRICING: dict[str, dict[str, float]] = {
280
+ # ── Groq ──────────────────────────────────────────────────────────
281
+ "llama-3.3-70b-versatile": {"input": 0.59, "output": 0.79},
282
+ # ── Google Gemini ─────────────────────────────────────────────────
283
+ # Approximate published per-1M-token rates (USD) for Gemini Flash-Lite.
284
+ "gemini-3.1-flash-lite": {"input": 0.10, "output": 0.40},
285
+ # Fallback for unknown models β€” pessimistic estimate
286
+ "__default__": {"input": 1.00, "output": 1.00},
287
+ }
288
+
289
+ # Backward-compatible alias β€” previously Groq-only; now the shared table
290
+ # so any external references keep resolving.
291
+ GROQ_PRICING = MODEL_PRICING
292
+
293
+
294
+ def estimate_model_cost(
295
+ model: str,
296
+ input_tokens: int,
297
+ output_tokens: int,
298
+ ) -> float | None:
299
+ """Estimate the USD cost of an LLM call by looking up ``MODEL_PRICING``.
300
+
301
+ Parameters
302
+ ----------
303
+ model : str
304
+ Model name. Unknown models return None; free-suffix models have a
305
+ zero catalog estimate, never a claimed billing charge.
306
+ input_tokens : int
307
+ Number of tokens in the prompt (system + user messages).
308
+ output_tokens : int
309
+ Number of tokens in the completion.
310
+
311
+ Returns
312
+ -------
313
+ float
314
+ Estimated cost in USD, or None when no known price is available.
315
+ """
316
+ if model.endswith(":free"):
317
+ return 0.0
318
+ pricing = MODEL_PRICING.get(model)
319
+ if pricing is None:
320
+ return None
321
+ input_cost = (input_tokens / 1_000_000) * pricing["input"]
322
+ output_cost = (output_tokens / 1_000_000) * pricing["output"]
323
+ return round(input_cost + output_cost, 6)
324
+
325
+
326
+ def estimate_groq_cost(
327
+ model: str,
328
+ input_tokens: int,
329
+ output_tokens: int,
330
+ ) -> float | None:
331
+ """Estimate the USD cost of a Groq LLM call (backward-compatible).
332
+
333
+ Thin wrapper around :func:`estimate_model_cost`. Kept so existing
334
+ callers (``app.py``, ``main.py``, :class:`TokenCostCallback`) keep
335
+ working unchanged β€” it now also prices Gemini and any other model in
336
+ :data:`MODEL_PRICING` correctly instead of using the Groq-only table.
337
+ """
338
+ return estimate_model_cost(model, input_tokens, output_tokens)
339
+
340
+
341
+ def format_cost(cost_usd: float) -> str:
342
+ """Format a USD cost for human-readable display."""
343
+ if cost_usd < 0.001:
344
+ return f"${cost_usd * 1000:.2f}β€―mΒ’"
345
+ return f"${cost_usd:.4f}"
346
+
347
+
348
+ # ─── Health check helpers ──────────────────────────────────────────────────
349
+
350
+
351
+ class HealthStatus:
352
+ """Aggregate health of the observability and API connectivity."""
353
+
354
+ def __init__(self) -> None:
355
+ self.langsmith: bool = is_langsmith_enabled()
356
+ self.langfuse: bool = is_langfuse_enabled()
357
+ self.groq: bool = bool(os.environ.get("GROQ_API_KEY", "").strip())
358
+ self.github: bool = bool(os.environ.get("GITHUB_TOKEN", "").strip())
359
+
360
+ @property
361
+ def any_tracing(self) -> bool:
362
+ return self.langsmith or self.langfuse
363
+
364
+ def summary(self) -> dict[str, str]:
365
+ """Return a dict of component β†’ status string."""
366
+ return {
367
+ "LangSmith": "βœ… Active" if self.langsmith else "β›” Not configured",
368
+ "Langfuse": "βœ… Active" if self.langfuse else "β›” Not configured",
369
+ "Groq API": "βœ… Key set" if self.groq else "β›” No key",
370
+ "GitHub API": "βœ… Token set" if self.github else "β›” No token",
371
+ }
372
+
373
+
374
+ def check_groq_connectivity() -> tuple[bool, str]:
375
+ """Lightweight Groq connectivity check β€” does not consume quota.
376
+
377
+ Uses ``urllib.request`` from stdlib (no extra dependencies).
378
+
379
+ Returns ``(ok, message)``.
380
+ """
381
+ import json as _json
382
+ import urllib.error as _urlerror
383
+ import urllib.request as _urlreq
384
+
385
+ api_key = os.environ.get("GROQ_API_KEY", "").strip()
386
+ if not api_key:
387
+ return False, "No GROQ_API_KEY set"
388
+
389
+ try:
390
+ req = _urlreq.Request(
391
+ "https://api.groq.com/openai/v1/models",
392
+ headers={
393
+ "Authorization": f"Bearer {api_key}",
394
+ "Content-Type": "application/json",
395
+ },
396
+ method="GET",
397
+ )
398
+ with _urlreq.urlopen(req, timeout=10) as resp:
399
+ if resp.status == 200:
400
+ data = _json.loads(resp.read().decode("utf-8"))
401
+ models = data.get("data", [])
402
+ count = len(models)
403
+ return True, f"Reachable β€” {count} models available"
404
+ else:
405
+ return False, f"HTTP {resp.status}"
406
+ except _urlerror.HTTPError as exc:
407
+ if exc.code == 401:
408
+ return False, "Invalid API key (401)"
409
+ return False, f"HTTP {exc.code}"
410
+ except Exception as exc:
411
+ return False, str(exc)
412
+
413
+
414
+ def check_langfuse_connectivity() -> tuple[bool, str]:
415
+ """Lightweight Langfuse connectivity check.
416
+
417
+ Returns ``(ok, message)``.
418
+ """
419
+ if not is_langfuse_enabled():
420
+ return False, "Not configured"
421
+
422
+ try:
423
+ from langfuse import Langfuse
424
+
425
+ lf = Langfuse()
426
+ lf.auth_check()
427
+ return True, "Connected"
428
+ except Exception as exc:
429
+ return False, str(exc)
430
+
431
+
432
+ # ─── Token cost callback (accumulates LLM usage across a run) ────────────
433
+
434
+
435
+ class TokenCostCallback:
436
+ """Accumulates per-model token usage & TTFT from LangChain LLM calls.
437
+
438
+ Also tracks **TTFT** (Time to First Token) by recording a timestamp
439
+ at ``on_chat_model_start`` and computing elapsed time at ``on_llm_end``.
440
+ For non-streaming LLM calls this is effectively the full request duration;
441
+ for streaming it would be the time to the first chunk.
442
+
443
+ Lazily imports ``BaseCallbackHandler`` so that ``observability.py`` can
444
+ be imported even when ``langchain-core`` has version incompatibilities
445
+ (e.g. on Hugging Face Spaces). Only ``on_llm_end`` is overridden;
446
+ all other lifecycle events are ignored.
447
+
448
+ Usage
449
+ -----
450
+ counter = TokenCostCallback()
451
+ config["callbacks"] = [counter, langfuse_handler] # if langfuse
452
+ ... run graph ...
453
+ print(counter.summary())
454
+ """
455
+
456
+ raise_error: bool = False
457
+ ignore_llm: bool = False
458
+ ignore_chain: bool = False
459
+ ignore_agent: bool = False
460
+ ignore_retriever: bool = False
461
+ ignore_chat_model: bool = False
462
+ ignore_custom_event: bool = False
463
+ ignore_retry: bool = False
464
+ run_inline: bool = False
465
+
466
+ def __init__(self) -> None:
467
+ self.usage: list[dict[str, Any]] = []
468
+ self._start_times: dict[str, float] = {} # run_id -> timestamp
469
+
470
+ @property
471
+ def total_input_tokens(self) -> int:
472
+ return sum(u.get("input_tokens", 0) for u in self.usage)
473
+
474
+ @property
475
+ def total_output_tokens(self) -> int:
476
+ return sum(u.get("output_tokens", 0) for u in self.usage)
477
+
478
+ @property
479
+ def total_cost(self) -> float:
480
+ return sum(u.get("cost") or 0.0 for u in self.usage)
481
+
482
+ @property
483
+ def total_ttft(self) -> float:
484
+ """Total TTFT across all LLM calls, in seconds."""
485
+ ttfts = [u.get("ttft_seconds", 0.0) for u in self.usage if u.get("ttft_seconds") is not None]
486
+ return sum(ttfts)
487
+
488
+ @property
489
+ def avg_ttft(self) -> Optional[float]:
490
+ """Average TTFT across all LLM calls, in seconds (None if no calls)."""
491
+ ttfts = [u.get("ttft_seconds", 0.0) for u in self.usage if u.get("ttft_seconds") is not None]
492
+ if not ttfts:
493
+ return None
494
+ return sum(ttfts) / len(ttfts)
495
+
496
+ def on_chain_start(self, *args, **kwargs) -> None:
497
+ pass
498
+
499
+ def on_chain_end(self, *args, **kwargs) -> None:
500
+ pass
501
+
502
+ def on_chat_model_start(self, *args, **kwargs) -> None:
503
+ """Record start timestamp for TTFT measurement.
504
+
505
+ ``**kwargs`` contains ``run_id`` which we use as the key.
506
+ """
507
+ run_id = kwargs.get("run_id")
508
+ if run_id:
509
+ self._start_times[str(run_id)] = time.time()
510
+
511
+ def on_llm_start(self, *args, **kwargs) -> None:
512
+ """Fallback: record start timestamp if ``on_chat_model_start`` wasn't called."""
513
+ run_id = kwargs.get("run_id")
514
+ if run_id and str(run_id) not in self._start_times:
515
+ self._start_times[str(run_id)] = time.time()
516
+
517
+ def on_llm_error(self, error, **kwargs) -> None:
518
+ self._cleanup_run(kwargs.get("run_id"))
519
+
520
+ def on_chain_error(self, error, **kwargs) -> None:
521
+ pass
522
+
523
+ def on_tool_error(self, error, **kwargs) -> None:
524
+ pass
525
+
526
+ def on_retriever_error(self, error, **kwargs) -> None:
527
+ pass
528
+
529
+ def on_llm_end(self, response, **kwargs) -> None:
530
+ """LangChain callback β€” called after each LLM invocation.
531
+
532
+ Computes TTFT from the recorded start time and captures token usage.
533
+ ``**kwargs`` absorbs ``run_id``, ``parent_run_id``, and other
534
+ metadata that LangChain passes to callback handlers.
535
+ """
536
+ try:
537
+ run_key = str(kwargs.get("run_id", ""))
538
+
539
+ # Compute TTFT (time from start to first token / completion)
540
+ ttft: Optional[float] = None
541
+ if run_key in self._start_times:
542
+ ttft = round(time.time() - self._start_times.pop(run_key), 3)
543
+
544
+ usage = response.llm_output or {}
545
+ token_usage = usage.get("token_usage", {}) or {}
546
+ model = usage.get("model_name", "") or ""
547
+
548
+ input_tokens = token_usage.get("prompt_tokens", 0) or 0
549
+ output_tokens = token_usage.get("completion_tokens", 0) or 0
550
+
551
+ if input_tokens > 0 or output_tokens > 0:
552
+ reported = token_usage.get("cost", usage.get("cost"))
553
+ if isinstance(reported, (int, float)) and not isinstance(reported, bool) and reported >= 0:
554
+ cost, cost_source = float(reported), "provider_reported"
555
+ else:
556
+ cost = estimate_model_cost(model, input_tokens, output_tokens)
557
+ cost_source = "free_model_estimate" if model.endswith(":free") else "estimated" if cost is not None else "unknown"
558
+ entry: dict[str, Any] = {
559
+ "model": model,
560
+ "input_tokens": input_tokens,
561
+ "output_tokens": output_tokens,
562
+ "cost": cost,
563
+ "cost_source": cost_source,
564
+ }
565
+ if ttft is not None:
566
+ entry["ttft_seconds"] = ttft
567
+ self.usage.append(entry)
568
+ else:
569
+ self._cleanup_run(run_key)
570
+ except Exception:
571
+ self._cleanup_run(run_key)
572
+ pass # Best-effort β€” don't let cost tracking crash the run
573
+
574
+ def _cleanup_run(self, run_id: Any) -> None:
575
+ """Remove a run_id from the start times map (cleanup on error)."""
576
+ if run_id:
577
+ self._start_times.pop(str(run_id), None)
578
+
579
+ def details(self) -> dict:
580
+ sources = {item.get("cost_source", "estimated") for item in self.usage}
581
+ complete = bool(self.usage) and "unknown" not in sources
582
+ source = next(iter(sources)) if len(sources) == 1 else "mixed" if sources else "unknown"
583
+ return {"amount": self.total_cost if complete else None, "currency": "USD", "source": source,
584
+ "complete": complete, "calls": len(self.usage), "input_tokens": self.total_input_tokens,
585
+ "output_tokens": self.total_output_tokens, "model_response_seconds": round(self.total_ttft, 3)}
586
+
587
+ def summary(self) -> str:
588
+ """Human-readable attribution; estimates never imply a provider charge."""
589
+ details = self.details()
590
+ calls = details["calls"]
591
+ if not calls:
592
+ return "Usage unavailable (no successful model usage captured)"
593
+ labels = {"provider_reported": "Provider-reported cost", "free_model_estimate": "Free-model estimate (not billing)",
594
+ "estimated": "Estimated cost (not billing)", "mixed": "Mixed measured/estimated cost"}
595
+ cost = f"{labels.get(details['source'], 'Cost')}: {format_cost(details['amount'])}" if details['complete'] else "Cost unknown (provider did not report a charge; no matching price)"
596
+ parts = [cost, f"{calls} LLM call(s)", f"{self.total_input_tokens:,} in / {self.total_output_tokens:,} out tokens"]
597
+ avg = self.avg_ttft
598
+ if avg is not None:
599
+ parts.append(f"Model response time: {avg:.2f}s avg")
600
+ return " Β· ".join(parts)
601
+
602
+ def reset(self) -> None:
603
+ self.usage.clear()
604
+ self._start_times.clear()
605
+
606
+
607
+ # ─── Error event logging ─────────────────────────────────────────────────--
608
+
609
+
610
+ # ─── Score logging ──────────────────────────────────────────────────────────
611
+
612
+
613
+ def _resolve_langfuse_trace_id(handler: Any) -> Optional[str]:
614
+ """Resolve the current Langfuse trace ID from handler or context.
615
+
616
+ Tries, in order:
617
+ 1. ``handler.trace_id`` (langfuse v3-style β€” likely None on v4+)
618
+ 2. ``handler.last_trace_id`` (langfuse v4+)
619
+ 3. ``Langfuse().get_current_trace_id()`` (langfuse v4+, works
620
+ inside ``propagate_attributes`` context)
621
+ """
622
+ if handler is not None:
623
+ try:
624
+ tid = getattr(handler, "trace_id", None)
625
+ if tid:
626
+ return tid
627
+ except Exception:
628
+ pass
629
+ try:
630
+ tid = getattr(handler, "last_trace_id", None)
631
+ if tid:
632
+ return tid
633
+ except Exception:
634
+ pass
635
+
636
+ try:
637
+ from opentelemetry import trace
638
+ context = trace.get_current_span().get_span_context()
639
+ if context.is_valid:
640
+ return format(context.trace_id, "032x")
641
+ except Exception:
642
+ pass
643
+
644
+ return None
645
+
646
+
647
+ def flush_langfuse() -> None:
648
+ """Flush the shared Langfuse client's pending events once per run.
649
+
650
+ In langfuse v4+ ``get_client()`` returns a process-wide singleton; callers
651
+ (e.g. ``main.py`` after the RAGAS block, ``app.py`` after streaming) should
652
+ call this once at the end of a run so queued scores/traces are shipped
653
+ before the process exits β€” instead of flushing inside every
654
+ :func:`log_langfuse_score` call.
655
+
656
+ Set ``OCR_OBSERVABILITY_STRICT=1`` to surface flush failures as exceptions.
657
+ """
658
+ if not is_langfuse_enabled():
659
+ return
660
+ try:
661
+ from langfuse import get_client # v4 singleton β€” one shared client
662
+
663
+ get_client().flush()
664
+ except ImportError:
665
+ # Missing SDK degrades gracefully β€” tracing is optional.
666
+ logger.debug("langfuse SDK not installed β€” flush skipped")
667
+ except Exception as exc:
668
+ if os.environ.get("OCR_OBSERVABILITY_STRICT") == "1":
669
+ raise
670
+ logger.error("Failed to flush Langfuse client: %s", exc)
671
+
672
+
673
+ def log_langfuse_score(
674
+ name: str,
675
+ value: float,
676
+ comment: Optional[str] = None,
677
+ trace_id: Optional[str] = None,
678
+ handler: Optional[Any] = None,
679
+ ) -> None:
680
+ """Log a numeric score to Langfuse, linked to a specific trace.
681
+
682
+ Requires Langfuse to be enabled (keys in environment). The score is
683
+ associated with a trace by ``trace_id``. If neither ``trace_id`` nor
684
+ a resolvable handler is provided, the score is logged without a trace
685
+ link (appears in the Scores tab but not on the trace detail page).
686
+
687
+ Parameters
688
+ ----------
689
+ name : str
690
+ Score name (e.g. ``"verdict_score"``, ``"findings_count"``).
691
+ value : float
692
+ Numeric score value.
693
+ comment : str or None
694
+ Optional human-readable comment.
695
+ trace_id : str or None
696
+ Explicit trace ID. If ``None``, attempts to resolve via handler.
697
+ handler : Langfuse CallbackHandler or None
698
+ Langfuse ``CallbackHandler`` from which to extract the trace ID.
699
+ """
700
+ if not is_langfuse_enabled():
701
+ return
702
+
703
+ resolved_trace_id = trace_id or _resolve_langfuse_trace_id(handler)
704
+ if not resolved_trace_id:
705
+ logger.warning("Score %s was not logged: no captured trace ID", name)
706
+ return
707
+
708
+ # Visibility log: lets you confirm the score will land on the right
709
+ # trace (or spot a None that would create an orphaned score).
710
+ logger.info("Langfuse trace_id resolved: %s", resolved_trace_id)
711
+
712
+ try:
713
+ from langfuse import get_client # v4 singleton β€” one shared client
714
+
715
+ lf = get_client()
716
+ kwargs: dict[str, Any] = {
717
+ "name": name,
718
+ "value": value,
719
+ }
720
+ if resolved_trace_id:
721
+ kwargs["trace_id"] = resolved_trace_id
722
+ if comment:
723
+ kwargs["comment"] = comment
724
+
725
+ lf.create_score(**kwargs)
726
+ # NOTE: do not flush here β€” flushing once per run via
727
+ # flush_langfuse() at run-end (called by app.py/main.py owners).
728
+ except ImportError:
729
+ # Missing SDK degrades gracefully β€” tracing is optional.
730
+ logger.debug(
731
+ "langfuse SDK not installed β€” score '%s' not logged", name
732
+ )
733
+ except Exception as exc:
734
+ if os.environ.get("OCR_OBSERVABILITY_STRICT") == "1":
735
+ raise
736
+ logger.error(
737
+ "Failed to log Langfuse score '%s'=%.4f (trace_id=%s, comment=%s): %s",
738
+ name, value, resolved_trace_id, comment, exc,
739
+ )
740
+
741
+
742
+ def update_langfuse_trace(
743
+ trace_name: Optional[str] = None,
744
+ tags: Optional[list[str]] = None,
745
+ metadata: Optional[dict[str, Any]] = None,
746
+ trace_id: Optional[str] = None,
747
+ handler: Optional[Any] = None,
748
+ ) -> None:
749
+ """No-op in langfuse v4+ β€” trace attributes must be set upfront
750
+ via ``propagate_attributes()`` (see :func:`langfuse_trace`).
751
+
752
+ In langfuse v4 the trace API no longer supports ``update_trace``.
753
+ Trace-level metadata (name, tags, user_id, session_id, metadata)
754
+ must be provided at trace creation time via ``propagate_attributes``.
755
+ Use :func:`log_langfuse_score` instead for post-hoc annotations
756
+ like verdict score or findings count.
757
+ """
758
+ if resolved_trace_id := (trace_id or _resolve_langfuse_trace_id(handler)):
759
+ logger.debug(
760
+ "update_langfuse_trace is a no-op in langfuse v4 (trace=%s). "
761
+ "Set attributes upfront via langfuse_trace() instead.",
762
+ resolved_trace_id,
763
+ )
764
+ # Dedicated score logging is handled by log_langfuse_score() β€” nothing
765
+ # to do here.
766
+
767
+
768
+ def log_error_to_backends(
769
+ error: Exception,
770
+ context: Optional[dict[str, Any]] = None,
771
+ ) -> None:
772
+ """Log an error event to whichever observability backend(s) are active.
773
+
774
+ For LangSmith: logs via LangChain's callback system (automatic).
775
+ For Langfuse: creates an identifyable error event via the SDK.
776
+
777
+ This function primarily logs to ``logger`` with full traceback and
778
+ enriches the log record with context that the tracing backends pick up.
779
+
780
+ Parameters
781
+ ----------
782
+ error : Exception
783
+ The exception that occurred.
784
+ context : dict or None
785
+ Additional context about where/when the error happened.
786
+ """
787
+ extras = ""
788
+ if context:
789
+ extras = f" [{', '.join(f'{k}={v}' for k, v in context.items())}]"
790
+
791
+ logger.exception(
792
+ "OBSERVABILITY-ERROR%s: %s: %s",
793
+ extras,
794
+ type(error).__name__,
795
+ error,
796
+ exc_info=error,
797
+ )
prompts/correctness_v1.txt CHANGED
@@ -1,46 +1,46 @@
1
- You are a seasoned code reviewer focused exclusively on **correctness**.
2
-
3
- Analyse the PR diff and changed files below. Look ONLY for:
4
-
5
- 1. **Logic errors** β€” incorrect boolean conditions, wrong operators, inverted
6
- if/else branches, incorrect variable shadowing, wrong function calls.
7
- 2. **Missed edge cases** β€” empty collections, None/null values, zero-length
8
- inputs, singleton lists, boundary values, negative numbers, overflow.
9
- 3. **Off-by-one errors** β€” loop bounds, slice indices, fencepost mistakes.
10
- 4. **Missing null/None checks** β€” unchecked return values, unchecked
11
- parameters that can be None, missing `is None` / `is not None` guards.
12
- 5. **Resource / state mismanagement** β€” unclosed handles, leaked connections,
13
- double-close, use-after-free, invalidated iterators.
14
- 6. **Concurrency hazards in the diff** β€” shared-mutation without locks, race
15
- windows, incorrect locking order.
16
- 7. **Async control-flow hazards** β€” `forEach(async ...)` or other
17
- fire-and-forget callbacks whose promises are not awaited, missing
18
- `Promise.all`/sequential loops, and errors that cannot reach surrounding
19
- `try/catch` blocks. Treat these as correctness issues because they can
20
- cause incomplete work, races, and unhandled rejections.
21
-
22
- **Do NOT** comment on:
23
- - Code style, formatting, naming conventions, or readability.
24
- - Performance (unless it's a correctness issue like an infinite loop).
25
- - Security (that is handled by a separate reviewer).
26
- - Tests being absent (unless the diff itself adds broken tests).
27
-
28
- For each issue return a `Finding` with:
29
- - `file_path`: the file the issue is in.
30
- - `line_start` / `line_end`: the relevant line range (best guess from the diff).
31
- - `severity`: `critical` (will definitely break), `high` (very likely to break),
32
- `medium` (edge-case bug), `low` (minor, unlikely to trigger), or `info`
33
- (informational).
34
- - `category`: always `"correctness"`.
35
- - `comment`: a concise, specific explanation of the bug.
36
- - `confidence`: 0.0–1.0 reflecting how sure you are.
37
- - `suggested_fix`: a concrete code snippet of how to fix it, if applicable.
38
-
39
- If you find NO correctness issues, return an empty findings list.
40
-
41
- Evidence and uncertainty rules:
42
- - Cite exact changed file/line locations and include a short evidence_excerpt from supplied code.
43
- - Do not invent absent repository context or claim tests/compiler execution. Model confidence is not measured correctness.
44
- - Distinguish observed code patterns from demonstrated runtime defects. Explain the concrete trigger and impact; omit claims that depend on unknown assumptions.
45
- - A TypeScript useState([]) declaration alone does not prove a build failure: response.json() commonly returns any. Without actual compiler diagnostics, phrase compiler concerns as requiring verification.
46
- - Do not claim missing tests repository-wide from a partial diff; say the supplied context does not demonstrate coverage.
 
1
+ You are a seasoned code reviewer focused exclusively on **correctness**.
2
+
3
+ Analyse the PR diff and changed files below. Look ONLY for:
4
+
5
+ 1. **Logic errors** β€” incorrect boolean conditions, wrong operators, inverted
6
+ if/else branches, incorrect variable shadowing, wrong function calls.
7
+ 2. **Missed edge cases** β€” empty collections, None/null values, zero-length
8
+ inputs, singleton lists, boundary values, negative numbers, overflow.
9
+ 3. **Off-by-one errors** β€” loop bounds, slice indices, fencepost mistakes.
10
+ 4. **Missing null/None checks** β€” unchecked return values, unchecked
11
+ parameters that can be None, missing `is None` / `is not None` guards.
12
+ 5. **Resource / state mismanagement** β€” unclosed handles, leaked connections,
13
+ double-close, use-after-free, invalidated iterators.
14
+ 6. **Concurrency hazards in the diff** β€” shared-mutation without locks, race
15
+ windows, incorrect locking order.
16
+ 7. **Async control-flow hazards** β€” `forEach(async ...)` or other
17
+ fire-and-forget callbacks whose promises are not awaited, missing
18
+ `Promise.all`/sequential loops, and errors that cannot reach surrounding
19
+ `try/catch` blocks. Treat these as correctness issues because they can
20
+ cause incomplete work, races, and unhandled rejections.
21
+
22
+ **Do NOT** comment on:
23
+ - Code style, formatting, naming conventions, or readability.
24
+ - Performance (unless it's a correctness issue like an infinite loop).
25
+ - Security (that is handled by a separate reviewer).
26
+ - Tests being absent (unless the diff itself adds broken tests).
27
+
28
+ For each issue return a `Finding` with:
29
+ - `file_path`: the file the issue is in.
30
+ - `line_start` / `line_end`: the relevant line range (best guess from the diff).
31
+ - `severity`: `critical` (will definitely break), `high` (very likely to break),
32
+ `medium` (edge-case bug), `low` (minor, unlikely to trigger), or `info`
33
+ (informational).
34
+ - `category`: always `"correctness"`.
35
+ - `comment`: a concise, specific explanation of the bug.
36
+ - `confidence`: 0.0–1.0 reflecting how sure you are.
37
+ - `suggested_fix`: a concrete code snippet of how to fix it, if applicable.
38
+
39
+ If you find NO correctness issues, return an empty findings list.
40
+
41
+ Evidence and uncertainty rules:
42
+ - Cite exact changed file/line locations and include a short evidence_excerpt from supplied code.
43
+ - Do not invent absent repository context or claim tests/compiler execution. Model confidence is not measured correctness.
44
+ - Distinguish observed code patterns from demonstrated runtime defects. Explain the concrete trigger and impact; omit claims that depend on unknown assumptions.
45
+ - A TypeScript useState([]) declaration alone does not prove a build failure: response.json() commonly returns any. Without actual compiler diagnostics, phrase compiler concerns as requiring verification.
46
+ - Do not claim missing tests repository-wide from a partial diff; say the supplied context does not demonstrate coverage.
prompts/security_v1.txt CHANGED
@@ -1,41 +1,41 @@
1
- You are a security-focused code reviewer. Analyse the PR diff and
2
- changed files for security vulnerabilities ONLY. Look for:
3
-
4
- 1. **Injection** β€” SQL, NoSQL, command, template (SSTI), LDAP, XSS, path
5
- traversal via unsanitized user input.
6
- 2. **Secrets / credentials** β€” hardcoded API keys, tokens, passwords, or
7
- connection strings that should use environment variables or a secret store.
8
- 3. **Unsafe deserialization** β€” `pickle.loads`, `yaml.load(…)` without
9
- SafeLoader, `eval`, `exec`, or `marshal` on untrusted data.
10
- 4. **Authentication / authorisation** β€” missing or broken access control
11
- checks, privilege escalation paths, session fixation, weak password hashing.
12
- 5. **Input validation** β€” missing or insufficient validation of user-supplied
13
- data that could lead to buffer overflows, integer overflows, or format-string
14
- bugs.
15
- 6. **Cryptographic misuse** β€” weak algorithms (MD5, SHA1 for signatures),
16
- hardcoded IVs/nonces, ECB mode, insufficient key lengths, missing TLS.
17
- 7. **Information disclosure** β€” stack traces leaked to users, verbose error
18
- messages exposing internals, debug endpoints left enabled.
19
-
20
- **Do NOT** comment on:
21
- - Code style, formatting, naming conventions.
22
- - Performance (unless it creates a denial-of-service vector).
23
- - General logic errors or edge cases (handled by correctness reviewer).
24
-
25
- For each issue return a `Finding` with:
26
- - `file_path`, `line_start`, `line_end`: location in the diff.
27
- - `severity`: `critical` (remotely exploitable), `high` (privilege escalation),
28
- `medium` (information disclosure), `low` (defence in depth), or `info`.
29
- - `category`: always `"security"`.
30
- - `comment`: concise, actionable explanation.
31
- - `confidence`: 0.0–1.0.
32
- - `suggested_fix`: concrete code snippet if applicable.
33
-
34
- Return an empty findings list if no security issues are found.
35
-
36
- Evidence and uncertainty rules:
37
- - Cite exact changed file/line locations and include a short evidence_excerpt from supplied code.
38
- - Do not invent absent repository context or claim tests/compiler execution. Model confidence is not measured correctness.
39
- - Distinguish observed code patterns from demonstrated runtime defects. Explain the concrete trigger and impact; omit claims that depend on unknown assumptions.
40
- - A TypeScript useState([]) declaration alone does not prove a build failure: response.json() commonly returns any. Without actual compiler diagnostics, phrase compiler concerns as requiring verification.
41
- - Do not claim missing tests repository-wide from a partial diff; say the supplied context does not demonstrate coverage.
 
1
+ You are a security-focused code reviewer. Analyse the PR diff and
2
+ changed files for security vulnerabilities ONLY. Look for:
3
+
4
+ 1. **Injection** β€” SQL, NoSQL, command, template (SSTI), LDAP, XSS, path
5
+ traversal via unsanitized user input.
6
+ 2. **Secrets / credentials** β€” hardcoded API keys, tokens, passwords, or
7
+ connection strings that should use environment variables or a secret store.
8
+ 3. **Unsafe deserialization** β€” `pickle.loads`, `yaml.load(…)` without
9
+ SafeLoader, `eval`, `exec`, or `marshal` on untrusted data.
10
+ 4. **Authentication / authorisation** β€” missing or broken access control
11
+ checks, privilege escalation paths, session fixation, weak password hashing.
12
+ 5. **Input validation** β€” missing or insufficient validation of user-supplied
13
+ data that could lead to buffer overflows, integer overflows, or format-string
14
+ bugs.
15
+ 6. **Cryptographic misuse** β€” weak algorithms (MD5, SHA1 for signatures),
16
+ hardcoded IVs/nonces, ECB mode, insufficient key lengths, missing TLS.
17
+ 7. **Information disclosure** β€” stack traces leaked to users, verbose error
18
+ messages exposing internals, debug endpoints left enabled.
19
+
20
+ **Do NOT** comment on:
21
+ - Code style, formatting, naming conventions.
22
+ - Performance (unless it creates a denial-of-service vector).
23
+ - General logic errors or edge cases (handled by correctness reviewer).
24
+
25
+ For each issue return a `Finding` with:
26
+ - `file_path`, `line_start`, `line_end`: location in the diff.
27
+ - `severity`: `critical` (remotely exploitable), `high` (privilege escalation),
28
+ `medium` (information disclosure), `low` (defence in depth), or `info`.
29
+ - `category`: always `"security"`.
30
+ - `comment`: concise, actionable explanation.
31
+ - `confidence`: 0.0–1.0.
32
+ - `suggested_fix`: concrete code snippet if applicable.
33
+
34
+ Return an empty findings list if no security issues are found.
35
+
36
+ Evidence and uncertainty rules:
37
+ - Cite exact changed file/line locations and include a short evidence_excerpt from supplied code.
38
+ - Do not invent absent repository context or claim tests/compiler execution. Model confidence is not measured correctness.
39
+ - Distinguish observed code patterns from demonstrated runtime defects. Explain the concrete trigger and impact; omit claims that depend on unknown assumptions.
40
+ - A TypeScript useState([]) declaration alone does not prove a build failure: response.json() commonly returns any. Without actual compiler diagnostics, phrase compiler concerns as requiring verification.
41
+ - Do not claim missing tests repository-wide from a partial diff; say the supplied context does not demonstrate coverage.
prompts/test_coverage_v1.txt CHANGED
@@ -1,45 +1,45 @@
1
- You are a code reviewer focused on **test coverage**. Analyse the
2
- PR diff and determine whether the changed logic has adequate test coverage.
3
-
4
- Look for:
5
-
6
- 1. **New logic without tests** β€” new functions, classes, or modules added in
7
- this diff that have no corresponding test file or test function.
8
- 2. **Modified behaviour without updated assertions** β€” existing logic that was
9
- changed in a semantically meaningful way (not just refactoring) but the
10
- corresponding tests were left unchanged, meaning they now pass vacuously or
11
- no longer cover the modified path.
12
- 3. **Edge-case branches left untested** β€” new `if`/`elif` branches, `try`/
13
- `except` handlers, or `match`/`case` arms that are not exercised by any
14
- test in the diff.
15
- 4. **Error / failure paths** β€” new error-return or exception-throwing paths
16
- that have no test asserting the error behaviour.
17
- 5. **Configuration / environment changes** β€” changes to config files,
18
- environment variables, or feature flags that affect behaviour but are not
19
- validated in tests.
20
-
21
- For each gap return a `Finding` with:
22
- - `file_path`: the source file with the gap (not the test file).
23
- - `line_start` / `line_end`: best guess of the affected lines.
24
- - `severity`: `low` or `info`. Missing tests are suggestions, not demonstrated production bugs.
25
- - `category`: always `"test_coverage"`.
26
- - `comment`: explain what changed and why it needs a test.
27
- - `confidence`: 0.0–1.0.
28
- - `suggested_fix`: what a good test should cover (not full code, just
29
- the scenario to test).
30
-
31
- **Do NOT** comment on:
32
- - Purely cosmetic or refactoring changes (rename, extract method).
33
- - Third-party dependencies or generated files.
34
- - Changes to test files themselves (they are the solution, not the problem).
35
- - Correctness of the logic itself (handled by correctness reviewer).
36
-
37
- Return an empty findings list if every changed path has adequate test coverage.
38
-
39
- Evidence and uncertainty rules:
40
- - Cite exact changed file/line locations and include a short evidence_excerpt from supplied code.
41
- - Do not invent absent repository context or claim tests/compiler execution. Model confidence is not measured correctness.
42
- - Distinguish observed code patterns from demonstrated runtime defects. Explain the concrete trigger and impact; omit claims that depend on unknown assumptions.
43
- - A TypeScript useState([]) declaration alone does not prove a build failure: response.json() commonly returns any. Without actual compiler diagnostics, phrase compiler concerns as requiring verification.
44
- - Do not claim missing tests repository-wide from a partial diff; say the supplied context does not demonstrate coverage.
45
- - Set kind to "test_suggestion". Group related coverage gaps into concise test scenarios instead of emitting one high-severity finding per component.
 
1
+ You are a code reviewer focused on **test coverage**. Analyse the
2
+ PR diff and determine whether the changed logic has adequate test coverage.
3
+
4
+ Look for:
5
+
6
+ 1. **New logic without tests** β€” new functions, classes, or modules added in
7
+ this diff that have no corresponding test file or test function.
8
+ 2. **Modified behaviour without updated assertions** β€” existing logic that was
9
+ changed in a semantically meaningful way (not just refactoring) but the
10
+ corresponding tests were left unchanged, meaning they now pass vacuously or
11
+ no longer cover the modified path.
12
+ 3. **Edge-case branches left untested** β€” new `if`/`elif` branches, `try`/
13
+ `except` handlers, or `match`/`case` arms that are not exercised by any
14
+ test in the diff.
15
+ 4. **Error / failure paths** β€” new error-return or exception-throwing paths
16
+ that have no test asserting the error behaviour.
17
+ 5. **Configuration / environment changes** β€” changes to config files,
18
+ environment variables, or feature flags that affect behaviour but are not
19
+ validated in tests.
20
+
21
+ For each gap return a `Finding` with:
22
+ - `file_path`: the source file with the gap (not the test file).
23
+ - `line_start` / `line_end`: best guess of the affected lines.
24
+ - `severity`: `low` or `info`. Missing tests are suggestions, not demonstrated production bugs.
25
+ - `category`: always `"test_coverage"`.
26
+ - `comment`: explain what changed and why it needs a test.
27
+ - `confidence`: 0.0–1.0.
28
+ - `suggested_fix`: what a good test should cover (not full code, just
29
+ the scenario to test).
30
+
31
+ **Do NOT** comment on:
32
+ - Purely cosmetic or refactoring changes (rename, extract method).
33
+ - Third-party dependencies or generated files.
34
+ - Changes to test files themselves (they are the solution, not the problem).
35
+ - Correctness of the logic itself (handled by correctness reviewer).
36
+
37
+ Return an empty findings list if every changed path has adequate test coverage.
38
+
39
+ Evidence and uncertainty rules:
40
+ - Cite exact changed file/line locations and include a short evidence_excerpt from supplied code.
41
+ - Do not invent absent repository context or claim tests/compiler execution. Model confidence is not measured correctness.
42
+ - Distinguish observed code patterns from demonstrated runtime defects. Explain the concrete trigger and impact; omit claims that depend on unknown assumptions.
43
+ - A TypeScript useState([]) declaration alone does not prove a build failure: response.json() commonly returns any. Without actual compiler diagnostics, phrase compiler concerns as requiring verification.
44
+ - Do not claim missing tests repository-wide from a partial diff; say the supplied context does not demonstrate coverage.
45
+ - Set kind to "test_suggestion". Group related coverage gaps into concise test scenarios instead of emitting one high-severity finding per component.
state.py CHANGED
@@ -1,102 +1,102 @@
1
- from __future__ import annotations
2
-
3
- import enum
4
- from operator import add
5
- from typing import Annotated, Literal, Optional
6
-
7
- from pydantic import BaseModel, Field
8
-
9
-
10
- # ─── Sub-models ──────────────────────────────────────────────────────────────
11
-
12
-
13
- class ChangedFile(BaseModel):
14
- """A single file modified in the PR."""
15
- path: str
16
- status: str # "added" | "modified" | "removed" | "renamed"
17
- content: str # Full file content after the PR
18
- diff_hunk: str # The unified-diff hunk for this file
19
-
20
-
21
- class ContextChunk(BaseModel):
22
- """A chunk of relevant context retrieved from the repo's codebase or past PRs."""
23
- source: str # "codebase" | "past_pr"
24
- file_path: str # Where the chunk came from
25
- content: str # The relevant code/text
26
- relevance_score: float = Field(default=0.0, ge=0.0, le=1.0)
27
-
28
-
29
- class Severity(str, enum.Enum):
30
- CRITICAL = "critical"
31
- HIGH = "high"
32
- MEDIUM = "medium"
33
- LOW = "low"
34
- INFO = "info"
35
-
36
-
37
- class Finding(BaseModel):
38
- """A single issue found during review."""
39
- file_path: str
40
- line_start: int
41
- line_end: int
42
- severity: Severity
43
- category: str # "logic" | "security" | "style" | "performance" | "correctness"
44
- comment: str # Human-readable explanation
45
- confidence: float = Field(default=0.5, ge=0.0, le=1.0)
46
- suggested_fix: Optional[str] = None
47
- kind: Literal["bug", "security_concern", "test_suggestion"] = "bug"
48
- evidence_status: Literal["source_grounded", "needs_verification", "outside_diff"] = "needs_verification"
49
- evidence_excerpt: str = ""
50
- calibration_note: str = ""
51
-
52
-
53
- class Verdict(BaseModel):
54
- """Aggregated final verdict across all findings."""
55
- summary: str
56
- approved: bool
57
- overall_score: Optional[float] = Field(default=None, ge=0.0, le=10.0)
58
- critical_count: int = 0
59
- high_count: int = 0
60
- recommendation: str # "approve" | "request_changes" | "block"
61
- score_explanation: str = ""
62
- score_breakdown: dict = Field(default_factory=dict)
63
-
64
-
65
- # ─── Graph State ─────────────────────────────────────────────────────────────
66
-
67
-
68
- class OpenCodeReviewState(BaseModel):
69
- """Shared state for the OpenCodeReview LangGraph agent."""
70
-
71
- # PR metadata: set-once, single values
72
- repo: str = ""
73
- pr_number: int = 0
74
- head_sha: str = ""
75
- incremental_base_sha: str = ""
76
- base_sha: str = "" # SHA of the base branch (used as vector-store cache key)
77
- diff: Optional[str] = None
78
- changed_files: list[ChangedFile] = Field(default_factory=list)
79
-
80
- # Custom LLM endpoint chosen for this run (name from OCR_ENDPOINT_* env
81
- # configs). Empty string means "use the built-in default provider".
82
- endpoint: str = ""
83
- review_mode: str = "thorough"
84
-
85
- # Retrieved context: accumulated across parallel retrieval nodes
86
- context_chunks: Annotated[list[ContextChunk], add] = Field(default_factory=list)
87
-
88
- # Review findings: accumulated across parallel review agents
89
- findings: Annotated[list[Finding], add] = Field(default_factory=list)
90
-
91
- review_stages: Annotated[list[dict], add] = Field(default_factory=list)
92
- review_coverage: dict = Field(default_factory=dict)
93
-
94
- # Aggregated (deduped, noise-filtered) findings: set-once by aggregator
95
- final_findings: list[Finding] = Field(default_factory=list)
96
-
97
- # Final verdict: set-once by the aggregation node
98
- verdict: Optional[Verdict] = None
99
-
100
- # Human-in-the-loop: set by the human_approval node
101
- human_approved: bool = False
102
- posting_result: Optional[dict] = None
 
1
+ from __future__ import annotations
2
+
3
+ import enum
4
+ from operator import add
5
+ from typing import Annotated, Literal, Optional
6
+
7
+ from pydantic import BaseModel, Field
8
+
9
+
10
+ # ─── Sub-models ──────────────────────────────────────────────────────────────
11
+
12
+
13
+ class ChangedFile(BaseModel):
14
+ """A single file modified in the PR."""
15
+ path: str
16
+ status: str # "added" | "modified" | "removed" | "renamed"
17
+ content: str # Full file content after the PR
18
+ diff_hunk: str # The unified-diff hunk for this file
19
+
20
+
21
+ class ContextChunk(BaseModel):
22
+ """A chunk of relevant context retrieved from the repo's codebase or past PRs."""
23
+ source: str # "codebase" | "past_pr"
24
+ file_path: str # Where the chunk came from
25
+ content: str # The relevant code/text
26
+ relevance_score: float = Field(default=0.0, ge=0.0, le=1.0)
27
+
28
+
29
+ class Severity(str, enum.Enum):
30
+ CRITICAL = "critical"
31
+ HIGH = "high"
32
+ MEDIUM = "medium"
33
+ LOW = "low"
34
+ INFO = "info"
35
+
36
+
37
+ class Finding(BaseModel):
38
+ """A single issue found during review."""
39
+ file_path: str
40
+ line_start: int
41
+ line_end: int
42
+ severity: Severity
43
+ category: str # "logic" | "security" | "style" | "performance" | "correctness"
44
+ comment: str # Human-readable explanation
45
+ confidence: float = Field(default=0.5, ge=0.0, le=1.0)
46
+ suggested_fix: Optional[str] = None
47
+ kind: Literal["bug", "security_concern", "test_suggestion"] = "bug"
48
+ evidence_status: Literal["source_grounded", "needs_verification", "outside_diff"] = "needs_verification"
49
+ evidence_excerpt: str = ""
50
+ calibration_note: str = ""
51
+
52
+
53
+ class Verdict(BaseModel):
54
+ """Aggregated final verdict across all findings."""
55
+ summary: str
56
+ approved: bool
57
+ overall_score: Optional[float] = Field(default=None, ge=0.0, le=10.0)
58
+ critical_count: int = 0
59
+ high_count: int = 0
60
+ recommendation: str # "approve" | "request_changes" | "block"
61
+ score_explanation: str = ""
62
+ score_breakdown: dict = Field(default_factory=dict)
63
+
64
+
65
+ # ─── Graph State ─────────────────────────────────────────────────────────────
66
+
67
+
68
+ class OpenCodeReviewState(BaseModel):
69
+ """Shared state for the OpenCodeReview LangGraph agent."""
70
+
71
+ # PR metadata: set-once, single values
72
+ repo: str = ""
73
+ pr_number: int = 0
74
+ head_sha: str = ""
75
+ incremental_base_sha: str = ""
76
+ base_sha: str = "" # SHA of the base branch (used as vector-store cache key)
77
+ diff: Optional[str] = None
78
+ changed_files: list[ChangedFile] = Field(default_factory=list)
79
+
80
+ # Custom LLM endpoint chosen for this run (name from OCR_ENDPOINT_* env
81
+ # configs). Empty string means "use the built-in default provider".
82
+ endpoint: str = ""
83
+ review_mode: str = "thorough"
84
+
85
+ # Retrieved context: accumulated across parallel retrieval nodes
86
+ context_chunks: Annotated[list[ContextChunk], add] = Field(default_factory=list)
87
+
88
+ # Review findings: accumulated across parallel review agents
89
+ findings: Annotated[list[Finding], add] = Field(default_factory=list)
90
+
91
+ review_stages: Annotated[list[dict], add] = Field(default_factory=list)
92
+ review_coverage: dict = Field(default_factory=dict)
93
+
94
+ # Aggregated (deduped, noise-filtered) findings: set-once by aggregator
95
+ final_findings: list[Finding] = Field(default_factory=list)
96
+
97
+ # Final verdict: set-once by the aggregation node
98
+ verdict: Optional[Verdict] = None
99
+
100
+ # Human-in-the-loop: set by the human_approval node
101
+ human_approved: bool = False
102
+ posting_result: Optional[dict] = None
tests/test_evaluation_quality.py CHANGED
@@ -44,6 +44,30 @@ def test_no_context_is_not_a_zero_quality_measurement():
44
  assert all(metric["status"] == "skipped" for metric in report["metrics"].values())
45
 
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  def test_cost_free_estimate_is_distinct_from_provider_report():
48
  callback = TokenCostCallback()
49
  callback.on_llm_end(SimpleNamespace(llm_output={"model_name": "minimax/test:free", "token_usage": {"prompt_tokens": 1000, "completion_tokens": 2000}}))
 
44
  assert all(metric["status"] == "skipped" for metric in report["metrics"].values())
45
 
46
 
47
+ def test_parallel_metrics_have_independent_evaluators(monkeypatch):
48
+ prepare(monkeypatch)
49
+ evaluators = []
50
+ def factory(endpoint):
51
+ evaluator = object()
52
+ evaluators.append(evaluator)
53
+ return evaluator
54
+ monkeypatch.setattr(ragas_eval, "_get_evaluator_llm", factory)
55
+ monkeypatch.setattr(ragas_eval, "_score_one_metric", lambda *args: .5)
56
+ report = ragas_eval.compute_ragas_report("query", ["context"], answer="answer")
57
+ assert len(evaluators) == 2
58
+ assert evaluators[0] is not evaluators[1]
59
+ assert len(report["scores"]) == 2
60
+
61
+
62
+ def test_metric_errors_are_actionable_without_provider_secrets():
63
+ connection_error = type("OpenAIConnectionError", (Exception,), {})
64
+ status, error = ragas_eval._safe_metric_error(connection_error("secret-api-key"))
65
+ assert status == "failed"
66
+ assert "connection failed" in error
67
+ assert "secret-api-key" not in error
68
+ assert ragas_eval._safe_metric_error(TimeoutError())[0] == "timed_out"
69
+
70
+
71
  def test_cost_free_estimate_is_distinct_from_provider_report():
72
  callback = TokenCostCallback()
73
  callback.on_llm_end(SimpleNamespace(llm_output={"model_name": "minimax/test:free", "token_usage": {"prompt_tokens": 1000, "completion_tokens": 2000}}))
tests/test_job_speed.py CHANGED
@@ -1,5 +1,6 @@
1
  """Exercise API scheduling without importing the heavyweight model runtime."""
2
  import ast
 
3
  from pathlib import Path
4
  from types import SimpleNamespace
5
  from unittest.mock import Mock
@@ -103,7 +104,7 @@ def test_cancellation_is_owner_scoped_and_terminal():
103
  def test_evaluation_quota_stops_followup_calls():
104
  tree = ast.parse(Path('eval_data/ragas_eval.py').read_text(encoding='utf-8'))
105
  node = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == '_ThrottledChatModel')
106
- ns = {'_RAGAS_INTERVAL': 0, '_ragas_throttle_lock': threading.Lock(), 'time': time}
107
  exec(compile(ast.Module(body=[node], type_ignores=[]), 'ragas_eval.py', 'exec'), ns)
108
  model = Mock()
109
  quota = RuntimeError('rate_limit_exceeded')
 
1
  """Exercise API scheduling without importing the heavyweight model runtime."""
2
  import ast
3
+ from contextvars import ContextVar
4
  from pathlib import Path
5
  from types import SimpleNamespace
6
  from unittest.mock import Mock
 
104
  def test_evaluation_quota_stops_followup_calls():
105
  tree = ast.parse(Path('eval_data/ragas_eval.py').read_text(encoding='utf-8'))
106
  node = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == '_ThrottledChatModel')
107
+ ns = {'_RAGAS_INTERVAL': 0, '_ragas_throttle_lock': threading.Lock(), 'time': time, '_metric_deadline': ContextVar('test_deadline', default=None)}
108
  exec(compile(ast.Module(body=[node], type_ignores=[]), 'ragas_eval.py', 'exec'), ns)
109
  model = Mock()
110
  quota = RuntimeError('rate_limit_exceeded')