Spaces:
Running
Running
Deploy ecaf69e2
Browse files- SPEED_IMPROVEMENTS.md +21 -0
- api.py +589 -589
- app.py +0 -0
- eval_data/ragas_eval.py +732 -732
- frontend/src/main.jsx +2 -2
- llm_factory.py +261 -261
- nodes/aggregator.py +286 -286
- nodes/correctness_reviewer.py +222 -222
- nodes/executor.py +330 -330
- nodes/human_approval.py +91 -91
- nodes/ingestion.py +228 -228
- nodes/review_runtime.py +81 -81
- nodes/security_reviewer.py +143 -143
- nodes/test_coverage_reviewer.py +150 -141
- state.py +95 -95
- tests/test_review_runtime.py +8 -0
SPEED_IMPROVEMENTS.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Review speed improvements
|
| 2 |
+
|
| 3 |
+
Implemented in this revision:
|
| 4 |
+
- Fast/Thorough modes: reviewer wall deadlines 45/90 seconds, native call timeouts 40/60 seconds; total pipeline also includes ingestion and aggregation.
|
| 5 |
+
- SDK retries disabled; one format repair within the reviewer deadline. No retries for auth/quota/transport failures.
|
| 6 |
+
- Failed reviewers make the result incomplete, with no numeric score and no posting.
|
| 7 |
+
- Background RAGAS uses a captured selected endpoint, stops after quota/auth failures, and is never automatically replayed after restart.
|
| 8 |
+
- Provider probe records real request latency and tests JSON output shape.
|
| 9 |
+
- Fast mode supplies numbered code windows around changes; Thorough retains existing full context bounds.
|
| 10 |
+
- Conservative routing: Fast documentation-only changes skip test coverage explicitly. Correctness/security remain; code, configuration, and unknown changes retain all specialists.
|
| 11 |
+
- Token budgets 1200/2000 per reviewer in Fast/Thorough. Model-specific reasoning parameters are deliberately not forced on incompatible providers.
|
| 12 |
+
- Polling streams completed stages, partial findings, reviewer statuses, timings, queue position, and background evaluation status.
|
| 13 |
+
- Cooperative cancellation discards late results; native network calls finish within their own timeout.
|
| 14 |
+
- Active duplicate prevention and 15-minute preview reuse require matching owner/configuration/prompt+node hashes and fresh GitHub head/base commits. Approval rechecks commits.
|
| 15 |
+
- Explicit incremental baseline comparisons reject divergent/truncated comparisons and are preview-only.
|
| 16 |
+
- GitHub file fetching runs concurrently with a maximum of four workers.
|
| 17 |
+
- User-selected saved providers remain the explicit alternative when a provider fails; no silent use of another user's/operator's key.
|
| 18 |
+
|
| 19 |
+
Validation: backend and frontend regression tests use fake providers; no local model runs. Live deployment verification is reported separately. No percentage speed improvement is claimed before measuring the same PR/model/configuration.
|
| 20 |
+
|
| 21 |
+
Known limits: cancellation is cooperative; browser-saved credentials remain local to the browser; cross-instance job dispatch requires a durable queue. Detailed provider-specific reasoning controls and automatic cross-provider failover are not implemented.
|
api.py
CHANGED
|
@@ -1,589 +1,589 @@
|
|
| 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"}}
|
| 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 |
-
def _authorize(token: str | None) -> None:
|
| 154 |
-
expected = os.getenv("OCR_API_KEY", "").strip()
|
| 155 |
-
# Authentication is opt-in for local development, but deployments can
|
| 156 |
-
# require it explicitly. Never silently treat a missing production key
|
| 157 |
-
# as authenticated.
|
| 158 |
-
require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
|
| 159 |
-
if require_auth and not expected:
|
| 160 |
-
raise HTTPException(status_code=503, detail="API authentication is not configured")
|
| 161 |
-
if expected and (not token or not secrets.compare_digest(token, expected)):
|
| 162 |
-
raise HTTPException(status_code=401, detail="Invalid API key")
|
| 163 |
-
|
| 164 |
-
def _authorize_request(token: str | None, request: Request) -> None:
|
| 165 |
-
if _session(request):
|
| 166 |
-
return
|
| 167 |
-
_authorize(token)
|
| 168 |
-
|
| 169 |
-
def _session(request: Request) -> dict[str, Any] | None:
|
| 170 |
-
sid = request.cookies.get("ocr_session")
|
| 171 |
-
return _sessions.get(sid) if sid else None
|
| 172 |
-
|
| 173 |
-
@app.get("/api/auth/github/start")
|
| 174 |
-
def github_login() -> RedirectResponse:
|
| 175 |
-
client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
|
| 176 |
-
if not client_id:
|
| 177 |
-
raise HTTPException(status_code=503, detail="GitHub OAuth is not configured")
|
| 178 |
-
state = secrets.token_urlsafe(32)
|
| 179 |
-
_oauth_states.add(state)
|
| 180 |
-
callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
|
| 181 |
-
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})
|
| 182 |
-
return RedirectResponse(url)
|
| 183 |
-
|
| 184 |
-
@app.get("/api/auth/github/callback")
|
| 185 |
-
def github_callback(code: str, state: str, response: Request) -> RedirectResponse:
|
| 186 |
-
if state not in _oauth_states:
|
| 187 |
-
raise HTTPException(status_code=400, detail="Invalid OAuth state")
|
| 188 |
-
_oauth_states.discard(state)
|
| 189 |
-
client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
|
| 190 |
-
client_secret = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "").strip()
|
| 191 |
-
callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
|
| 192 |
-
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)
|
| 193 |
-
token_resp.raise_for_status()
|
| 194 |
-
access_token = token_resp.json().get("access_token")
|
| 195 |
-
if not access_token:
|
| 196 |
-
raise HTTPException(status_code=502, detail="GitHub did not return an access token")
|
| 197 |
-
user_resp = requests.get("https://api.github.com/user", headers={"Authorization": f"Bearer {access_token}", "Accept": "application/vnd.github+json"}, timeout=20)
|
| 198 |
-
user_resp.raise_for_status()
|
| 199 |
-
user = user_resp.json()
|
| 200 |
-
sid = secrets.token_urlsafe(32)
|
| 201 |
-
_sessions[sid] = {"token": access_token, "github_id": user.get("id"), "login": user.get("login")}
|
| 202 |
-
frontend = os.getenv("OCR_FRONTEND_URL", allowed_origins[0] if allowed_origins else "http://localhost:5173")
|
| 203 |
-
out = RedirectResponse(frontend)
|
| 204 |
-
out.set_cookie("ocr_session", sid, httponly=True, secure=frontend.startswith("https://"), samesite="lax", max_age=86400)
|
| 205 |
-
return out
|
| 206 |
-
|
| 207 |
-
@app.get("/api/auth/me")
|
| 208 |
-
def github_me(request: Request) -> dict[str, Any]:
|
| 209 |
-
session = _session(request)
|
| 210 |
-
if not session:
|
| 211 |
-
raise HTTPException(status_code=401, detail="Not authenticated")
|
| 212 |
-
return {"github_id": session["github_id"], "login": session["login"]}
|
| 213 |
-
|
| 214 |
-
@app.post("/api/auth/logout")
|
| 215 |
-
def github_logout(request: Request) -> dict[str, str]:
|
| 216 |
-
sid = request.cookies.get("ocr_session")
|
| 217 |
-
if sid:
|
| 218 |
-
_sessions.pop(sid, None)
|
| 219 |
-
return {"status": "logged_out"}
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
def _public_job(job: dict[str, Any]) -> dict[str, Any]:
|
| 223 |
-
result = {key: value for key, value in job.items() if key not in {"config", "future", "request_fingerprint", "owner_id"}}
|
| 224 |
-
now = time.time()
|
| 225 |
-
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)
|
| 226 |
-
if job.get("status") == "queued":
|
| 227 |
-
result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
|
| 228 |
-
return result
|
| 229 |
-
|
| 230 |
-
def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
|
| 231 |
-
result = _public_job(job)
|
| 232 |
-
task_id = result.get("ragas_task_id")
|
| 233 |
-
if not task_id:
|
| 234 |
-
result["ragas"] = {
|
| 235 |
-
"status": "skipped",
|
| 236 |
-
"scores": result.get("ragas_scores") or {},
|
| 237 |
-
"reason": "No retrieval context was available for RAGAS evaluation",
|
| 238 |
-
}
|
| 239 |
-
else:
|
| 240 |
-
if job.get("ragas_status") in {"failed", "unavailable", "completed_no_scores"}:
|
| 241 |
-
result["ragas"] = {
|
| 242 |
-
"status": job["ragas_status"],
|
| 243 |
-
"scores": job.get("ragas_scores") or {},
|
| 244 |
-
"error": job.get("ragas_error"),
|
| 245 |
-
}
|
| 246 |
-
return result
|
| 247 |
-
with _ragas_lock:
|
| 248 |
-
task = _ragas_tasks.get(task_id)
|
| 249 |
-
if not task:
|
| 250 |
-
# Task registries are process-local. A restart invalidates an
|
| 251 |
-
# in-flight task instead of making the client poll forever.
|
| 252 |
-
if result.get("ragas_scores"):
|
| 253 |
-
result["ragas"] = {"status": "completed", "scores": result["ragas_scores"]}
|
| 254 |
-
else:
|
| 255 |
-
result["ragas"] = {"status": "unavailable", "error": "RAGAS task was lost during process restart"}
|
| 256 |
-
with _lock:
|
| 257 |
-
live = _jobs.get(job.get("id"))
|
| 258 |
-
if live is not None:
|
| 259 |
-
live["ragas_status"] = "unavailable"
|
| 260 |
-
live["ragas_error"] = result["ragas"]["error"]
|
| 261 |
-
_save_job(live)
|
| 262 |
-
elif not task.get("done"):
|
| 263 |
-
timeout = float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90"))
|
| 264 |
-
started = float(task.get("started", 0) or 0)
|
| 265 |
-
if started and datetime.now(timezone.utc).timestamp() - started > timeout:
|
| 266 |
-
result["ragas"] = {"status": "failed", "error": f"RAGAS exceeded {int(timeout)} second timeout"}
|
| 267 |
-
with _lock:
|
| 268 |
-
live = _jobs.get(job.get("id"))
|
| 269 |
-
if live is not None:
|
| 270 |
-
live["ragas_status"] = "failed"
|
| 271 |
-
live["ragas_error"] = result["ragas"]["error"]
|
| 272 |
-
_save_job(live)
|
| 273 |
-
else:
|
| 274 |
-
result["ragas"] = {"status": "pending"}
|
| 275 |
-
elif task.get("error"):
|
| 276 |
-
result["ragas"] = {"status": "failed", "error": task.get("error")}
|
| 277 |
-
with _lock:
|
| 278 |
-
live = _jobs.get(job.get("id"))
|
| 279 |
-
if live is not None:
|
| 280 |
-
live["ragas_status"] = "failed"
|
| 281 |
-
live["ragas_error"] = task.get("error")
|
| 282 |
-
_save_job(live)
|
| 283 |
-
else:
|
| 284 |
-
scores = task.get("scores") or {}
|
| 285 |
-
if scores:
|
| 286 |
-
result["ragas"] = {"status": "completed", "scores": scores}
|
| 287 |
-
if not job.get("ragas_scores"):
|
| 288 |
-
with _lock:
|
| 289 |
-
live = _jobs.get(job.get("id"))
|
| 290 |
-
if live is not None:
|
| 291 |
-
live["ragas_scores"] = scores
|
| 292 |
-
live["ragas_status"] = "completed"
|
| 293 |
-
_save_job(live)
|
| 294 |
-
else:
|
| 295 |
-
result["ragas"] = {"status": "completed_no_scores", "scores": {}, "error": "RAGAS completed without metric values"}
|
| 296 |
-
with _lock:
|
| 297 |
-
live = _jobs.get(job.get("id"))
|
| 298 |
-
if live is not None:
|
| 299 |
-
live["ragas_status"] = "completed_no_scores"
|
| 300 |
-
live["ragas_error"] = result["ragas"]["error"]
|
| 301 |
-
_save_job(live)
|
| 302 |
-
return result
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
def _run_job(job_id: str, request: ReviewRequest) -> None:
|
| 306 |
-
with _lock:
|
| 307 |
-
if _jobs.get(job_id, {}).get("status") == "cancelled":
|
| 308 |
-
return
|
| 309 |
-
if job_id in _jobs:
|
| 310 |
-
_jobs[job_id].update(status="processing", started_timestamp=time.time(), progress={"stage": "ingestion", "completed_stages": []})
|
| 311 |
-
_save_job(_jobs[job_id])
|
| 312 |
-
try:
|
| 313 |
-
ephemeral_endpoint = None
|
| 314 |
-
endpoint_name = _normalize_endpoint_name(request.endpoint)
|
| 315 |
-
if request.api_key:
|
| 316 |
-
if not request.provider or not request.model:
|
| 317 |
-
raise ValueError("provider and model are required when supplying a user API key")
|
| 318 |
-
ephemeral_endpoint = f"user-{job_id}"
|
| 319 |
-
register_endpoint(ephemeral_endpoint, request.provider, request.api_key, request.base_url, request.model)
|
| 320 |
-
endpoint_name = ephemeral_endpoint
|
| 321 |
-
def save_ragas(scores: dict, error: str | None) -> None:
|
| 322 |
-
with _lock:
|
| 323 |
-
live = _jobs.get(job_id)
|
| 324 |
-
if live is None:
|
| 325 |
-
return
|
| 326 |
-
live["ragas_scores"] = scores or None
|
| 327 |
-
live["ragas_status"] = "failed" if error else ("completed" if scores else "completed_no_scores")
|
| 328 |
-
live["ragas_error"] = error
|
| 329 |
-
_save_job(live)
|
| 330 |
-
|
| 331 |
-
def progress(stage: str, elapsed: float, update: dict | None = None) -> None:
|
| 332 |
-
with _lock:
|
| 333 |
-
live = _jobs[job_id]
|
| 334 |
-
if live.get("status") == "cancelled":
|
| 335 |
-
raise RuntimeError("Review cancelled")
|
| 336 |
-
completed = live.setdefault("progress", {}).setdefault("completed_stages", [])
|
| 337 |
-
if stage not in completed:
|
| 338 |
-
completed.append(stage)
|
| 339 |
-
live["progress"]["stage"] = stage
|
| 340 |
-
live.setdefault("stage_timings", {})[stage] = round(elapsed, 2)
|
| 341 |
-
if isinstance(update, dict):
|
| 342 |
-
stages = update.get("review_stages", [])
|
| 343 |
-
if isinstance(stages, list):
|
| 344 |
-
live.setdefault("review_stages", []).extend(stages)
|
| 345 |
-
for key in ("findings",):
|
| 346 |
-
for finding in update.get(key, []) or []:
|
| 347 |
-
if hasattr(finding, "model_dump"):
|
| 348 |
-
finding = finding.model_dump(mode="json")
|
| 349 |
-
if isinstance(finding, dict):
|
| 350 |
-
live.setdefault("findings", []).append(finding)
|
| 351 |
-
_save_job(live)
|
| 352 |
-
|
| 353 |
-
state, config, cost, ragas, ragas_inputs = _build_and_stream(
|
| 354 |
-
request.repo,
|
| 355 |
-
request.pr_number,
|
| 356 |
-
endpoint_name,
|
| 357 |
-
ragas_background=True,
|
| 358 |
-
ragas_result_callback=save_ragas,
|
| 359 |
-
progress_callback=progress,
|
| 360 |
-
review_mode=request.review_mode,
|
| 361 |
-
baseline_sha=request.baseline_sha,
|
| 362 |
-
)
|
| 363 |
-
actual_head = state.values.get("head_sha")
|
| 364 |
-
verdict: Verdict | None = state.values.get("verdict")
|
| 365 |
-
findings: list[Finding] = state.values.get("final_findings", [])
|
| 366 |
-
with _lock:
|
| 367 |
-
if _jobs[job_id].get("status") == "cancelled":
|
| 368 |
-
return
|
| 369 |
-
if actual_head and _jobs[job_id].get("head_sha") != actual_head:
|
| 370 |
-
# The PR moved between metadata lookup and ingestion. The result
|
| 371 |
-
# can still be viewed, but must not satisfy the old cache key.
|
| 372 |
-
_jobs[job_id]["request_fingerprint"] = None
|
| 373 |
-
_jobs[job_id]["head_sha"] = actual_head
|
| 374 |
-
stages = state.values.get("review_stages", [])
|
| 375 |
-
incomplete = bool(verdict and verdict.recommendation == "incomplete")
|
| 376 |
-
_jobs[job_id].update(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, ragas_task_id=ragas if isinstance(ragas, str) else None, ragas_scores=ragas if isinstance(ragas, dict) else None, ragas_inputs=ragas_inputs or None)
|
| 377 |
-
_save_job(_jobs[job_id])
|
| 378 |
-
except Exception as exc:
|
| 379 |
-
with _lock:
|
| 380 |
-
if _jobs[job_id].get("status") != "cancelled":
|
| 381 |
-
_jobs[job_id].update(status="failed", error=str(exc)[:500])
|
| 382 |
-
_save_job(_jobs[job_id])
|
| 383 |
-
finally:
|
| 384 |
-
if 'ephemeral_endpoint' in locals() and ephemeral_endpoint:
|
| 385 |
-
unregister_endpoint(ephemeral_endpoint)
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
def _hydrate_jobs() -> None:
|
| 389 |
-
"""Restore persisted jobs after a process restart and resume interrupted work."""
|
| 390 |
-
for persisted in _load_jobs():
|
| 391 |
-
job_id = persisted.get("id")
|
| 392 |
-
if not job_id:
|
| 393 |
-
continue
|
| 394 |
-
status = persisted.get("status")
|
| 395 |
-
_jobs[job_id] = persisted
|
| 396 |
-
if persisted.get("ragas_task_id") and not persisted.get("ragas_status"):
|
| 397 |
-
persisted.update(ragas_status="unavailable", ragas_error="Evaluation interrupted by restart; it was not automatically replayed.")
|
| 398 |
-
_save_job(persisted)
|
| 399 |
-
if status in {"queued", "processing"} and persisted.get("custom_provider"):
|
| 400 |
-
persisted.update(status="failed", error="Provider credentials were not persisted; resubmit this review after restart.")
|
| 401 |
-
_save_job(persisted)
|
| 402 |
-
continue
|
| 403 |
-
if status in {"queued", "processing", "processing_decision"}:
|
| 404 |
-
# Decision processing cannot be safely replayed without an explicit
|
| 405 |
-
# user action; review execution can be resumed idempotently.
|
| 406 |
-
if status == "processing_decision":
|
| 407 |
-
_jobs[job_id]["status"] = "awaiting_approval"
|
| 408 |
-
_save_job(_jobs[job_id])
|
| 409 |
-
continue
|
| 410 |
-
try:
|
| 411 |
-
request = ReviewRequest(repo=persisted["repo"], pr_number=int(persisted["pr_number"]), endpoint=persisted.get("endpoint"))
|
| 412 |
-
except Exception:
|
| 413 |
-
_jobs[job_id].update(status="failed", error="Persisted job request is invalid")
|
| 414 |
-
_save_job(_jobs[job_id])
|
| 415 |
-
continue
|
| 416 |
-
_jobs[job_id]["status"] = "queued"
|
| 417 |
-
_save_job(_jobs[job_id])
|
| 418 |
-
_jobs[job_id]["future"] = _executor.submit(_run_job, job_id, request)
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
_hydrate_jobs()
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
@app.get("/api/health")
|
| 425 |
-
def health() -> dict[str, Any]:
|
| 426 |
-
provider_configured = any(
|
| 427 |
-
os.getenv(name, "").strip()
|
| 428 |
-
for name in ("GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
|
| 429 |
-
)
|
| 430 |
-
require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
|
| 431 |
-
persistence = "local_default_path"
|
| 432 |
-
if os.getenv("SUPABASE_DB_URL"):
|
| 433 |
-
probe = _postgres_connect()
|
| 434 |
-
if probe is not None:
|
| 435 |
-
probe.close()
|
| 436 |
-
persistence = "supabase_postgres"
|
| 437 |
-
else:
|
| 438 |
-
persistence = "supabase_configured_unreachable"
|
| 439 |
-
elif os.getenv("OPENCODEREVIEW_DB_PATH"):
|
| 440 |
-
persistence = "configured_path"
|
| 441 |
-
return {
|
| 442 |
-
"status": "ok",
|
| 443 |
-
"inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
|
| 444 |
-
"authentication": "required" if require_auth else "optional",
|
| 445 |
-
"rate_limit_per_minute": int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0),
|
| 446 |
-
"persistence": persistence,
|
| 447 |
-
"local_embeddings": os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower()
|
| 448 |
-
in {"1", "true", "yes", "on"},
|
| 449 |
-
}
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
@app.post("/api/reviews", status_code=202)
|
| 453 |
-
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]:
|
| 454 |
-
_authorize_request(x_api_key, http_request)
|
| 455 |
-
_rate_limit(http_request)
|
| 456 |
-
owner = str((_session(http_request) or {}).get("github_id") or "api-key")
|
| 457 |
-
material = request.model_dump()
|
| 458 |
-
head_sha = base_sha = None
|
| 459 |
-
try:
|
| 460 |
-
token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
|
| 461 |
-
headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
|
| 462 |
-
if token:
|
| 463 |
-
headers["Authorization"] = f"Bearer {token}"
|
| 464 |
-
response = requests.get(f"https://api.github.com/repos/{request.repo}/pulls/{request.pr_number}", headers=headers, timeout=6)
|
| 465 |
-
response.raise_for_status()
|
| 466 |
-
pull = response.json()
|
| 467 |
-
head_sha, base_sha = pull["head"]["sha"], pull["base"]["sha"]
|
| 468 |
-
except (requests.RequestException, KeyError, ValueError):
|
| 469 |
-
pass # Active deduplication still works if GitHub metadata is unavailable.
|
| 470 |
-
prompt_hash = hashlib.sha256()
|
| 471 |
-
for source in sorted(Path(__file__).parent.joinpath("prompts").glob("*.txt")):
|
| 472 |
-
prompt_hash.update(source.read_bytes())
|
| 473 |
-
for source in sorted(Path(__file__).parent.joinpath("nodes").glob("*.py")):
|
| 474 |
-
prompt_hash.update(source.read_bytes())
|
| 475 |
-
material.update(head_sha=head_sha, base_sha=base_sha, pipeline_version=prompt_hash.hexdigest())
|
| 476 |
-
fingerprint = hashlib.sha256(json.dumps({"owner": owner, "request": material}, sort_keys=True).encode()).hexdigest()
|
| 477 |
-
# Reuse completed previews only for an identical immutable diff and configuration.
|
| 478 |
-
with _lock:
|
| 479 |
-
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)
|
| 480 |
-
if existing is None:
|
| 481 |
-
job_id = str(uuid.uuid4())
|
| 482 |
-
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()}
|
| 483 |
-
_jobs[job_id] = job
|
| 484 |
-
_save_job(job)
|
| 485 |
-
else:
|
| 486 |
-
job = existing
|
| 487 |
-
if existing is not None:
|
| 488 |
-
return {**_with_ragas(job), "reused": True}
|
| 489 |
-
job["future"] = _executor.submit(_run_job, job_id, request)
|
| 490 |
-
return _with_ragas(job)
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
@app.post("/api/reviews/{job_id}/cancel")
|
| 494 |
-
def cancel_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 495 |
-
_authorize_request(x_api_key, request)
|
| 496 |
-
owner = str((_session(request) or {}).get("github_id") or "api-key")
|
| 497 |
-
with _lock:
|
| 498 |
-
job = _jobs.get(job_id)
|
| 499 |
-
if not job or job.get("owner_id", "api-key") != owner:
|
| 500 |
-
raise HTTPException(status_code=404, detail="Review not found")
|
| 501 |
-
if job.get("status") not in {"queued", "processing"}:
|
| 502 |
-
raise HTTPException(status_code=409, detail="Only queued or processing reviews can be cancelled")
|
| 503 |
-
future = job.get("future")
|
| 504 |
-
if future:
|
| 505 |
-
future.cancel()
|
| 506 |
-
job.update(status="cancelled", cancellation_note="Running calls finish within their timeout; no results will be posted.")
|
| 507 |
-
_save_job(job)
|
| 508 |
-
return _public_job(job)
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
@app.get("/api/reviews/{job_id}")
|
| 512 |
-
def get_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 513 |
-
# API-key authorization remains supported for polling; OAuth callers use the cookie path.
|
| 514 |
-
_authorize_request(x_api_key, request)
|
| 515 |
-
with _lock:
|
| 516 |
-
job = _jobs.get(job_id)
|
| 517 |
-
if not job:
|
| 518 |
-
job = _load_job(job_id)
|
| 519 |
-
owner = str((_session(request) or {}).get("github_id") or "api-key")
|
| 520 |
-
if not job or job.get("owner_id", "api-key") != owner:
|
| 521 |
-
raise HTTPException(status_code=404, detail="Review not found")
|
| 522 |
-
return _with_ragas(job)
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
@app.post("/api/reviews/{job_id}/decision")
|
| 526 |
-
def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 527 |
-
_authorize_request(x_api_key, http_request)
|
| 528 |
-
_rate_limit(http_request)
|
| 529 |
-
with _lock:
|
| 530 |
-
preview = _jobs.get(job_id) or _load_job(job_id)
|
| 531 |
-
owner = str((_session(http_request) or {}).get("github_id") or "api-key")
|
| 532 |
-
if not preview or preview.get("owner_id", "api-key") != owner:
|
| 533 |
-
raise HTTPException(status_code=404, detail="Review not found")
|
| 534 |
-
if request.action == "approve" and preview.get("baseline_sha"):
|
| 535 |
-
raise HTTPException(status_code=409, detail="Incremental reviews are preview-only. Run a full review before posting.")
|
| 536 |
-
if preview and request.action == "approve" and preview.get("head_sha"):
|
| 537 |
-
headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
|
| 538 |
-
token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
|
| 539 |
-
if token:
|
| 540 |
-
headers["Authorization"] = f"Bearer {token}"
|
| 541 |
-
try:
|
| 542 |
-
response = requests.get(f"https://api.github.com/repos/{preview['repo']}/pulls/{preview['pr_number']}", headers=headers, timeout=6)
|
| 543 |
-
response.raise_for_status()
|
| 544 |
-
current = response.json()
|
| 545 |
-
if current["head"]["sha"] != preview["head_sha"] or current["base"]["sha"] != preview.get("base_sha"):
|
| 546 |
-
raise HTTPException(status_code=409, detail="PR changed since this review; start a new review before posting.")
|
| 547 |
-
except (requests.RequestException, KeyError, ValueError) as exc:
|
| 548 |
-
raise HTTPException(status_code=503, detail="Cannot verify the current PR commit; retry before posting.") from exc
|
| 549 |
-
with _lock:
|
| 550 |
-
job = _jobs.get(job_id)
|
| 551 |
-
if not job:
|
| 552 |
-
job = _load_job(job_id)
|
| 553 |
-
if not job:
|
| 554 |
-
raise HTTPException(status_code=404, detail="Review not found")
|
| 555 |
-
if job.get("status") != "awaiting_approval":
|
| 556 |
-
raise HTTPException(status_code=409, detail="Review is not awaiting approval")
|
| 557 |
-
config = job["config"]
|
| 558 |
-
job["status"] = "processing_decision"
|
| 559 |
-
_save_job(job)
|
| 560 |
-
if request.action == "reject":
|
| 561 |
-
with _lock:
|
| 562 |
-
job.update(status="rejected", decision="reject")
|
| 563 |
-
_save_job(job)
|
| 564 |
-
return _public_job(job)
|
| 565 |
-
graph = build_graph(DB_PATH)
|
| 566 |
-
try:
|
| 567 |
-
callbacks = [TokenCostCallback()]
|
| 568 |
-
handler = get_langfuse_handler()
|
| 569 |
-
if handler:
|
| 570 |
-
callbacks.append(handler)
|
| 571 |
-
config = dict(config)
|
| 572 |
-
config["callbacks"] = callbacks
|
| 573 |
-
result = graph.invoke(Command(resume={"action": "approve"}), config)
|
| 574 |
-
posting_result = result.get("posting_result") if isinstance(result, dict) else None
|
| 575 |
-
final_status = (posting_result or {}).get("status", "posted")
|
| 576 |
-
with _lock:
|
| 577 |
-
job.update(status=final_status, decision="approve", posting_result=posting_result)
|
| 578 |
-
_save_job(job)
|
| 579 |
-
return _public_job(job)
|
| 580 |
-
except Exception as exc:
|
| 581 |
-
with _lock:
|
| 582 |
-
job.update(status="failed", error=str(exc)[:500])
|
| 583 |
-
_save_job(job)
|
| 584 |
-
raise HTTPException(status_code=500, detail="Decision processing failed") from exc
|
| 585 |
-
finally:
|
| 586 |
-
conn = getattr(graph, "_opencodereview_conn", None)
|
| 587 |
-
if conn:
|
| 588 |
-
conn.close()
|
| 589 |
-
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"}}
|
| 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 |
+
def _authorize(token: str | None) -> None:
|
| 154 |
+
expected = os.getenv("OCR_API_KEY", "").strip()
|
| 155 |
+
# Authentication is opt-in for local development, but deployments can
|
| 156 |
+
# require it explicitly. Never silently treat a missing production key
|
| 157 |
+
# as authenticated.
|
| 158 |
+
require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
|
| 159 |
+
if require_auth and not expected:
|
| 160 |
+
raise HTTPException(status_code=503, detail="API authentication is not configured")
|
| 161 |
+
if expected and (not token or not secrets.compare_digest(token, expected)):
|
| 162 |
+
raise HTTPException(status_code=401, detail="Invalid API key")
|
| 163 |
+
|
| 164 |
+
def _authorize_request(token: str | None, request: Request) -> None:
|
| 165 |
+
if _session(request):
|
| 166 |
+
return
|
| 167 |
+
_authorize(token)
|
| 168 |
+
|
| 169 |
+
def _session(request: Request) -> dict[str, Any] | None:
|
| 170 |
+
sid = request.cookies.get("ocr_session")
|
| 171 |
+
return _sessions.get(sid) if sid else None
|
| 172 |
+
|
| 173 |
+
@app.get("/api/auth/github/start")
|
| 174 |
+
def github_login() -> RedirectResponse:
|
| 175 |
+
client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
|
| 176 |
+
if not client_id:
|
| 177 |
+
raise HTTPException(status_code=503, detail="GitHub OAuth is not configured")
|
| 178 |
+
state = secrets.token_urlsafe(32)
|
| 179 |
+
_oauth_states.add(state)
|
| 180 |
+
callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
|
| 181 |
+
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})
|
| 182 |
+
return RedirectResponse(url)
|
| 183 |
+
|
| 184 |
+
@app.get("/api/auth/github/callback")
|
| 185 |
+
def github_callback(code: str, state: str, response: Request) -> RedirectResponse:
|
| 186 |
+
if state not in _oauth_states:
|
| 187 |
+
raise HTTPException(status_code=400, detail="Invalid OAuth state")
|
| 188 |
+
_oauth_states.discard(state)
|
| 189 |
+
client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
|
| 190 |
+
client_secret = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "").strip()
|
| 191 |
+
callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
|
| 192 |
+
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)
|
| 193 |
+
token_resp.raise_for_status()
|
| 194 |
+
access_token = token_resp.json().get("access_token")
|
| 195 |
+
if not access_token:
|
| 196 |
+
raise HTTPException(status_code=502, detail="GitHub did not return an access token")
|
| 197 |
+
user_resp = requests.get("https://api.github.com/user", headers={"Authorization": f"Bearer {access_token}", "Accept": "application/vnd.github+json"}, timeout=20)
|
| 198 |
+
user_resp.raise_for_status()
|
| 199 |
+
user = user_resp.json()
|
| 200 |
+
sid = secrets.token_urlsafe(32)
|
| 201 |
+
_sessions[sid] = {"token": access_token, "github_id": user.get("id"), "login": user.get("login")}
|
| 202 |
+
frontend = os.getenv("OCR_FRONTEND_URL", allowed_origins[0] if allowed_origins else "http://localhost:5173")
|
| 203 |
+
out = RedirectResponse(frontend)
|
| 204 |
+
out.set_cookie("ocr_session", sid, httponly=True, secure=frontend.startswith("https://"), samesite="lax", max_age=86400)
|
| 205 |
+
return out
|
| 206 |
+
|
| 207 |
+
@app.get("/api/auth/me")
|
| 208 |
+
def github_me(request: Request) -> dict[str, Any]:
|
| 209 |
+
session = _session(request)
|
| 210 |
+
if not session:
|
| 211 |
+
raise HTTPException(status_code=401, detail="Not authenticated")
|
| 212 |
+
return {"github_id": session["github_id"], "login": session["login"]}
|
| 213 |
+
|
| 214 |
+
@app.post("/api/auth/logout")
|
| 215 |
+
def github_logout(request: Request) -> dict[str, str]:
|
| 216 |
+
sid = request.cookies.get("ocr_session")
|
| 217 |
+
if sid:
|
| 218 |
+
_sessions.pop(sid, None)
|
| 219 |
+
return {"status": "logged_out"}
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _public_job(job: dict[str, Any]) -> dict[str, Any]:
|
| 223 |
+
result = {key: value for key, value in job.items() if key not in {"config", "future", "request_fingerprint", "owner_id"}}
|
| 224 |
+
now = time.time()
|
| 225 |
+
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)
|
| 226 |
+
if job.get("status") == "queued":
|
| 227 |
+
result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
|
| 228 |
+
return result
|
| 229 |
+
|
| 230 |
+
def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
|
| 231 |
+
result = _public_job(job)
|
| 232 |
+
task_id = result.get("ragas_task_id")
|
| 233 |
+
if not task_id:
|
| 234 |
+
result["ragas"] = {
|
| 235 |
+
"status": "skipped",
|
| 236 |
+
"scores": result.get("ragas_scores") or {},
|
| 237 |
+
"reason": "No retrieval context was available for RAGAS evaluation",
|
| 238 |
+
}
|
| 239 |
+
else:
|
| 240 |
+
if job.get("ragas_status") in {"failed", "unavailable", "completed_no_scores"}:
|
| 241 |
+
result["ragas"] = {
|
| 242 |
+
"status": job["ragas_status"],
|
| 243 |
+
"scores": job.get("ragas_scores") or {},
|
| 244 |
+
"error": job.get("ragas_error"),
|
| 245 |
+
}
|
| 246 |
+
return result
|
| 247 |
+
with _ragas_lock:
|
| 248 |
+
task = _ragas_tasks.get(task_id)
|
| 249 |
+
if not task:
|
| 250 |
+
# Task registries are process-local. A restart invalidates an
|
| 251 |
+
# in-flight task instead of making the client poll forever.
|
| 252 |
+
if result.get("ragas_scores"):
|
| 253 |
+
result["ragas"] = {"status": "completed", "scores": result["ragas_scores"]}
|
| 254 |
+
else:
|
| 255 |
+
result["ragas"] = {"status": "unavailable", "error": "RAGAS task was lost during process restart"}
|
| 256 |
+
with _lock:
|
| 257 |
+
live = _jobs.get(job.get("id"))
|
| 258 |
+
if live is not None:
|
| 259 |
+
live["ragas_status"] = "unavailable"
|
| 260 |
+
live["ragas_error"] = result["ragas"]["error"]
|
| 261 |
+
_save_job(live)
|
| 262 |
+
elif not task.get("done"):
|
| 263 |
+
timeout = float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90"))
|
| 264 |
+
started = float(task.get("started", 0) or 0)
|
| 265 |
+
if started and datetime.now(timezone.utc).timestamp() - started > timeout:
|
| 266 |
+
result["ragas"] = {"status": "failed", "error": f"RAGAS exceeded {int(timeout)} second timeout"}
|
| 267 |
+
with _lock:
|
| 268 |
+
live = _jobs.get(job.get("id"))
|
| 269 |
+
if live is not None:
|
| 270 |
+
live["ragas_status"] = "failed"
|
| 271 |
+
live["ragas_error"] = result["ragas"]["error"]
|
| 272 |
+
_save_job(live)
|
| 273 |
+
else:
|
| 274 |
+
result["ragas"] = {"status": "pending"}
|
| 275 |
+
elif task.get("error"):
|
| 276 |
+
result["ragas"] = {"status": "failed", "error": task.get("error")}
|
| 277 |
+
with _lock:
|
| 278 |
+
live = _jobs.get(job.get("id"))
|
| 279 |
+
if live is not None:
|
| 280 |
+
live["ragas_status"] = "failed"
|
| 281 |
+
live["ragas_error"] = task.get("error")
|
| 282 |
+
_save_job(live)
|
| 283 |
+
else:
|
| 284 |
+
scores = task.get("scores") or {}
|
| 285 |
+
if scores:
|
| 286 |
+
result["ragas"] = {"status": "completed", "scores": scores}
|
| 287 |
+
if not job.get("ragas_scores"):
|
| 288 |
+
with _lock:
|
| 289 |
+
live = _jobs.get(job.get("id"))
|
| 290 |
+
if live is not None:
|
| 291 |
+
live["ragas_scores"] = scores
|
| 292 |
+
live["ragas_status"] = "completed"
|
| 293 |
+
_save_job(live)
|
| 294 |
+
else:
|
| 295 |
+
result["ragas"] = {"status": "completed_no_scores", "scores": {}, "error": "RAGAS completed without metric values"}
|
| 296 |
+
with _lock:
|
| 297 |
+
live = _jobs.get(job.get("id"))
|
| 298 |
+
if live is not None:
|
| 299 |
+
live["ragas_status"] = "completed_no_scores"
|
| 300 |
+
live["ragas_error"] = result["ragas"]["error"]
|
| 301 |
+
_save_job(live)
|
| 302 |
+
return result
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _run_job(job_id: str, request: ReviewRequest) -> None:
|
| 306 |
+
with _lock:
|
| 307 |
+
if _jobs.get(job_id, {}).get("status") == "cancelled":
|
| 308 |
+
return
|
| 309 |
+
if job_id in _jobs:
|
| 310 |
+
_jobs[job_id].update(status="processing", started_timestamp=time.time(), progress={"stage": "ingestion", "completed_stages": []})
|
| 311 |
+
_save_job(_jobs[job_id])
|
| 312 |
+
try:
|
| 313 |
+
ephemeral_endpoint = None
|
| 314 |
+
endpoint_name = _normalize_endpoint_name(request.endpoint)
|
| 315 |
+
if request.api_key:
|
| 316 |
+
if not request.provider or not request.model:
|
| 317 |
+
raise ValueError("provider and model are required when supplying a user API key")
|
| 318 |
+
ephemeral_endpoint = f"user-{job_id}"
|
| 319 |
+
register_endpoint(ephemeral_endpoint, request.provider, request.api_key, request.base_url, request.model)
|
| 320 |
+
endpoint_name = ephemeral_endpoint
|
| 321 |
+
def save_ragas(scores: dict, error: str | None) -> None:
|
| 322 |
+
with _lock:
|
| 323 |
+
live = _jobs.get(job_id)
|
| 324 |
+
if live is None:
|
| 325 |
+
return
|
| 326 |
+
live["ragas_scores"] = scores or None
|
| 327 |
+
live["ragas_status"] = "failed" if error else ("completed" if scores else "completed_no_scores")
|
| 328 |
+
live["ragas_error"] = error
|
| 329 |
+
_save_job(live)
|
| 330 |
+
|
| 331 |
+
def progress(stage: str, elapsed: float, update: dict | None = None) -> None:
|
| 332 |
+
with _lock:
|
| 333 |
+
live = _jobs[job_id]
|
| 334 |
+
if live.get("status") == "cancelled":
|
| 335 |
+
raise RuntimeError("Review cancelled")
|
| 336 |
+
completed = live.setdefault("progress", {}).setdefault("completed_stages", [])
|
| 337 |
+
if stage not in completed:
|
| 338 |
+
completed.append(stage)
|
| 339 |
+
live["progress"]["stage"] = stage
|
| 340 |
+
live.setdefault("stage_timings", {})[stage] = round(elapsed, 2)
|
| 341 |
+
if isinstance(update, dict):
|
| 342 |
+
stages = update.get("review_stages", [])
|
| 343 |
+
if isinstance(stages, list):
|
| 344 |
+
live.setdefault("review_stages", []).extend(stages)
|
| 345 |
+
for key in ("findings",):
|
| 346 |
+
for finding in update.get(key, []) or []:
|
| 347 |
+
if hasattr(finding, "model_dump"):
|
| 348 |
+
finding = finding.model_dump(mode="json")
|
| 349 |
+
if isinstance(finding, dict):
|
| 350 |
+
live.setdefault("findings", []).append(finding)
|
| 351 |
+
_save_job(live)
|
| 352 |
+
|
| 353 |
+
state, config, cost, ragas, ragas_inputs = _build_and_stream(
|
| 354 |
+
request.repo,
|
| 355 |
+
request.pr_number,
|
| 356 |
+
endpoint_name,
|
| 357 |
+
ragas_background=True,
|
| 358 |
+
ragas_result_callback=save_ragas,
|
| 359 |
+
progress_callback=progress,
|
| 360 |
+
review_mode=request.review_mode,
|
| 361 |
+
baseline_sha=request.baseline_sha,
|
| 362 |
+
)
|
| 363 |
+
actual_head = state.values.get("head_sha")
|
| 364 |
+
verdict: Verdict | None = state.values.get("verdict")
|
| 365 |
+
findings: list[Finding] = state.values.get("final_findings", [])
|
| 366 |
+
with _lock:
|
| 367 |
+
if _jobs[job_id].get("status") == "cancelled":
|
| 368 |
+
return
|
| 369 |
+
if actual_head and _jobs[job_id].get("head_sha") != actual_head:
|
| 370 |
+
# The PR moved between metadata lookup and ingestion. The result
|
| 371 |
+
# can still be viewed, but must not satisfy the old cache key.
|
| 372 |
+
_jobs[job_id]["request_fingerprint"] = None
|
| 373 |
+
_jobs[job_id]["head_sha"] = actual_head
|
| 374 |
+
stages = state.values.get("review_stages", [])
|
| 375 |
+
incomplete = bool(verdict and verdict.recommendation == "incomplete")
|
| 376 |
+
_jobs[job_id].update(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, ragas_task_id=ragas if isinstance(ragas, str) else None, ragas_scores=ragas if isinstance(ragas, dict) else None, ragas_inputs=ragas_inputs or None)
|
| 377 |
+
_save_job(_jobs[job_id])
|
| 378 |
+
except Exception as exc:
|
| 379 |
+
with _lock:
|
| 380 |
+
if _jobs[job_id].get("status") != "cancelled":
|
| 381 |
+
_jobs[job_id].update(status="failed", error=str(exc)[:500])
|
| 382 |
+
_save_job(_jobs[job_id])
|
| 383 |
+
finally:
|
| 384 |
+
if 'ephemeral_endpoint' in locals() and ephemeral_endpoint:
|
| 385 |
+
unregister_endpoint(ephemeral_endpoint)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def _hydrate_jobs() -> None:
|
| 389 |
+
"""Restore persisted jobs after a process restart and resume interrupted work."""
|
| 390 |
+
for persisted in _load_jobs():
|
| 391 |
+
job_id = persisted.get("id")
|
| 392 |
+
if not job_id:
|
| 393 |
+
continue
|
| 394 |
+
status = persisted.get("status")
|
| 395 |
+
_jobs[job_id] = persisted
|
| 396 |
+
if persisted.get("ragas_task_id") and not persisted.get("ragas_status"):
|
| 397 |
+
persisted.update(ragas_status="unavailable", ragas_error="Evaluation interrupted by restart; it was not automatically replayed.")
|
| 398 |
+
_save_job(persisted)
|
| 399 |
+
if status in {"queued", "processing"} and persisted.get("custom_provider"):
|
| 400 |
+
persisted.update(status="failed", error="Provider credentials were not persisted; resubmit this review after restart.")
|
| 401 |
+
_save_job(persisted)
|
| 402 |
+
continue
|
| 403 |
+
if status in {"queued", "processing", "processing_decision"}:
|
| 404 |
+
# Decision processing cannot be safely replayed without an explicit
|
| 405 |
+
# user action; review execution can be resumed idempotently.
|
| 406 |
+
if status == "processing_decision":
|
| 407 |
+
_jobs[job_id]["status"] = "awaiting_approval"
|
| 408 |
+
_save_job(_jobs[job_id])
|
| 409 |
+
continue
|
| 410 |
+
try:
|
| 411 |
+
request = ReviewRequest(repo=persisted["repo"], pr_number=int(persisted["pr_number"]), endpoint=persisted.get("endpoint"))
|
| 412 |
+
except Exception:
|
| 413 |
+
_jobs[job_id].update(status="failed", error="Persisted job request is invalid")
|
| 414 |
+
_save_job(_jobs[job_id])
|
| 415 |
+
continue
|
| 416 |
+
_jobs[job_id]["status"] = "queued"
|
| 417 |
+
_save_job(_jobs[job_id])
|
| 418 |
+
_jobs[job_id]["future"] = _executor.submit(_run_job, job_id, request)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
_hydrate_jobs()
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
@app.get("/api/health")
|
| 425 |
+
def health() -> dict[str, Any]:
|
| 426 |
+
provider_configured = any(
|
| 427 |
+
os.getenv(name, "").strip()
|
| 428 |
+
for name in ("GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
|
| 429 |
+
)
|
| 430 |
+
require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
|
| 431 |
+
persistence = "local_default_path"
|
| 432 |
+
if os.getenv("SUPABASE_DB_URL"):
|
| 433 |
+
probe = _postgres_connect()
|
| 434 |
+
if probe is not None:
|
| 435 |
+
probe.close()
|
| 436 |
+
persistence = "supabase_postgres"
|
| 437 |
+
else:
|
| 438 |
+
persistence = "supabase_configured_unreachable"
|
| 439 |
+
elif os.getenv("OPENCODEREVIEW_DB_PATH"):
|
| 440 |
+
persistence = "configured_path"
|
| 441 |
+
return {
|
| 442 |
+
"status": "ok",
|
| 443 |
+
"inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
|
| 444 |
+
"authentication": "required" if require_auth else "optional",
|
| 445 |
+
"rate_limit_per_minute": int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0),
|
| 446 |
+
"persistence": persistence,
|
| 447 |
+
"local_embeddings": os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower()
|
| 448 |
+
in {"1", "true", "yes", "on"},
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
@app.post("/api/reviews", status_code=202)
|
| 453 |
+
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]:
|
| 454 |
+
_authorize_request(x_api_key, http_request)
|
| 455 |
+
_rate_limit(http_request)
|
| 456 |
+
owner = str((_session(http_request) or {}).get("github_id") or "api-key")
|
| 457 |
+
material = request.model_dump()
|
| 458 |
+
head_sha = base_sha = None
|
| 459 |
+
try:
|
| 460 |
+
token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
|
| 461 |
+
headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
|
| 462 |
+
if token:
|
| 463 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 464 |
+
response = requests.get(f"https://api.github.com/repos/{request.repo}/pulls/{request.pr_number}", headers=headers, timeout=6)
|
| 465 |
+
response.raise_for_status()
|
| 466 |
+
pull = response.json()
|
| 467 |
+
head_sha, base_sha = pull["head"]["sha"], pull["base"]["sha"]
|
| 468 |
+
except (requests.RequestException, KeyError, ValueError):
|
| 469 |
+
pass # Active deduplication still works if GitHub metadata is unavailable.
|
| 470 |
+
prompt_hash = hashlib.sha256()
|
| 471 |
+
for source in sorted(Path(__file__).parent.joinpath("prompts").glob("*.txt")):
|
| 472 |
+
prompt_hash.update(source.read_bytes())
|
| 473 |
+
for source in sorted(Path(__file__).parent.joinpath("nodes").glob("*.py")):
|
| 474 |
+
prompt_hash.update(source.read_bytes())
|
| 475 |
+
material.update(head_sha=head_sha, base_sha=base_sha, pipeline_version=prompt_hash.hexdigest())
|
| 476 |
+
fingerprint = hashlib.sha256(json.dumps({"owner": owner, "request": material}, sort_keys=True).encode()).hexdigest()
|
| 477 |
+
# Reuse completed previews only for an identical immutable diff and configuration.
|
| 478 |
+
with _lock:
|
| 479 |
+
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)
|
| 480 |
+
if existing is None:
|
| 481 |
+
job_id = str(uuid.uuid4())
|
| 482 |
+
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()}
|
| 483 |
+
_jobs[job_id] = job
|
| 484 |
+
_save_job(job)
|
| 485 |
+
else:
|
| 486 |
+
job = existing
|
| 487 |
+
if existing is not None:
|
| 488 |
+
return {**_with_ragas(job), "reused": True}
|
| 489 |
+
job["future"] = _executor.submit(_run_job, job_id, request)
|
| 490 |
+
return _with_ragas(job)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
@app.post("/api/reviews/{job_id}/cancel")
|
| 494 |
+
def cancel_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 495 |
+
_authorize_request(x_api_key, request)
|
| 496 |
+
owner = str((_session(request) or {}).get("github_id") or "api-key")
|
| 497 |
+
with _lock:
|
| 498 |
+
job = _jobs.get(job_id)
|
| 499 |
+
if not job or job.get("owner_id", "api-key") != owner:
|
| 500 |
+
raise HTTPException(status_code=404, detail="Review not found")
|
| 501 |
+
if job.get("status") not in {"queued", "processing"}:
|
| 502 |
+
raise HTTPException(status_code=409, detail="Only queued or processing reviews can be cancelled")
|
| 503 |
+
future = job.get("future")
|
| 504 |
+
if future:
|
| 505 |
+
future.cancel()
|
| 506 |
+
job.update(status="cancelled", cancellation_note="Running calls finish within their timeout; no results will be posted.")
|
| 507 |
+
_save_job(job)
|
| 508 |
+
return _public_job(job)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
@app.get("/api/reviews/{job_id}")
|
| 512 |
+
def get_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 513 |
+
# API-key authorization remains supported for polling; OAuth callers use the cookie path.
|
| 514 |
+
_authorize_request(x_api_key, request)
|
| 515 |
+
with _lock:
|
| 516 |
+
job = _jobs.get(job_id)
|
| 517 |
+
if not job:
|
| 518 |
+
job = _load_job(job_id)
|
| 519 |
+
owner = str((_session(request) or {}).get("github_id") or "api-key")
|
| 520 |
+
if not job or job.get("owner_id", "api-key") != owner:
|
| 521 |
+
raise HTTPException(status_code=404, detail="Review not found")
|
| 522 |
+
return _with_ragas(job)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
@app.post("/api/reviews/{job_id}/decision")
|
| 526 |
+
def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 527 |
+
_authorize_request(x_api_key, http_request)
|
| 528 |
+
_rate_limit(http_request)
|
| 529 |
+
with _lock:
|
| 530 |
+
preview = _jobs.get(job_id) or _load_job(job_id)
|
| 531 |
+
owner = str((_session(http_request) or {}).get("github_id") or "api-key")
|
| 532 |
+
if not preview or preview.get("owner_id", "api-key") != owner:
|
| 533 |
+
raise HTTPException(status_code=404, detail="Review not found")
|
| 534 |
+
if request.action == "approve" and preview.get("baseline_sha"):
|
| 535 |
+
raise HTTPException(status_code=409, detail="Incremental reviews are preview-only. Run a full review before posting.")
|
| 536 |
+
if preview and request.action == "approve" and preview.get("head_sha"):
|
| 537 |
+
headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
|
| 538 |
+
token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
|
| 539 |
+
if token:
|
| 540 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 541 |
+
try:
|
| 542 |
+
response = requests.get(f"https://api.github.com/repos/{preview['repo']}/pulls/{preview['pr_number']}", headers=headers, timeout=6)
|
| 543 |
+
response.raise_for_status()
|
| 544 |
+
current = response.json()
|
| 545 |
+
if current["head"]["sha"] != preview["head_sha"] or current["base"]["sha"] != preview.get("base_sha"):
|
| 546 |
+
raise HTTPException(status_code=409, detail="PR changed since this review; start a new review before posting.")
|
| 547 |
+
except (requests.RequestException, KeyError, ValueError) as exc:
|
| 548 |
+
raise HTTPException(status_code=503, detail="Cannot verify the current PR commit; retry before posting.") from exc
|
| 549 |
+
with _lock:
|
| 550 |
+
job = _jobs.get(job_id)
|
| 551 |
+
if not job:
|
| 552 |
+
job = _load_job(job_id)
|
| 553 |
+
if not job:
|
| 554 |
+
raise HTTPException(status_code=404, detail="Review not found")
|
| 555 |
+
if job.get("status") != "awaiting_approval":
|
| 556 |
+
raise HTTPException(status_code=409, detail="Review is not awaiting approval")
|
| 557 |
+
config = job["config"]
|
| 558 |
+
job["status"] = "processing_decision"
|
| 559 |
+
_save_job(job)
|
| 560 |
+
if request.action == "reject":
|
| 561 |
+
with _lock:
|
| 562 |
+
job.update(status="rejected", decision="reject")
|
| 563 |
+
_save_job(job)
|
| 564 |
+
return _public_job(job)
|
| 565 |
+
graph = build_graph(DB_PATH)
|
| 566 |
+
try:
|
| 567 |
+
callbacks = [TokenCostCallback()]
|
| 568 |
+
handler = get_langfuse_handler()
|
| 569 |
+
if handler:
|
| 570 |
+
callbacks.append(handler)
|
| 571 |
+
config = dict(config)
|
| 572 |
+
config["callbacks"] = callbacks
|
| 573 |
+
result = graph.invoke(Command(resume={"action": "approve"}), config)
|
| 574 |
+
posting_result = result.get("posting_result") if isinstance(result, dict) else None
|
| 575 |
+
final_status = (posting_result or {}).get("status", "posted")
|
| 576 |
+
with _lock:
|
| 577 |
+
job.update(status=final_status, decision="approve", posting_result=posting_result)
|
| 578 |
+
_save_job(job)
|
| 579 |
+
return _public_job(job)
|
| 580 |
+
except Exception as exc:
|
| 581 |
+
with _lock:
|
| 582 |
+
job.update(status="failed", error=str(exc)[:500])
|
| 583 |
+
_save_job(job)
|
| 584 |
+
raise HTTPException(status_code=500, detail="Decision processing failed") from exc
|
| 585 |
+
finally:
|
| 586 |
+
conn = getattr(graph, "_opencodereview_conn", None)
|
| 587 |
+
if conn:
|
| 588 |
+
conn.close()
|
| 589 |
+
flush_langfuse()
|
app.py
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
eval_data/ragas_eval.py
CHANGED
|
@@ -1,732 +1,732 @@
|
|
| 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 |
-
import logging
|
| 30 |
-
import os
|
| 31 |
-
import threading
|
| 32 |
-
import time
|
| 33 |
-
from typing import Any, Optional
|
| 34 |
-
|
| 35 |
-
logger = logging.getLogger(__name__)
|
| 36 |
-
|
| 37 |
-
# βββ Lazy RAGAS imports with graceful fallback ββββββββββββββββββββββββββββββ
|
| 38 |
-
|
| 39 |
-
_RAGAS_AVAILABLE: bool | None = None
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
def _check_ragas() -> bool:
|
| 43 |
-
"""Return True if RAGAS is available.
|
| 44 |
-
|
| 45 |
-
Note: ``litellm`` is NOT required because RAGAS scoring uses the
|
| 46 |
-
project's own LLM factory (Gemini or Groq via LangChain), not
|
| 47 |
-
litellm internally.
|
| 48 |
-
"""
|
| 49 |
-
global _RAGAS_AVAILABLE
|
| 50 |
-
if _RAGAS_AVAILABLE is not None:
|
| 51 |
-
return _RAGAS_AVAILABLE
|
| 52 |
-
try:
|
| 53 |
-
import ragas # noqa: F401
|
| 54 |
-
_RAGAS_AVAILABLE = True
|
| 55 |
-
except ImportError:
|
| 56 |
-
logger.warning(
|
| 57 |
-
"ragas not installed. Install with: pip install ragas"
|
| 58 |
-
)
|
| 59 |
-
_RAGAS_AVAILABLE = False
|
| 60 |
-
return _RAGAS_AVAILABLE
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
# Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
|
| 64 |
-
# burst of ~20-30 model calls per review (context-precision judgments,
|
| 65 |
-
# faithfulness verification, answer relevancy, MMR relevance checks).
|
| 66 |
-
# Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
|
| 67 |
-
# limits so scoring completes instead of tripping 429s β which previously
|
| 68 |
-
# caused long retry backoffs and 0.0000 scores. Override with the
|
| 69 |
-
# OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
|
| 70 |
-
_RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
|
| 71 |
-
_ragas_throttle_lock = threading.Lock()
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
class _ThrottledChatModel:
|
| 75 |
-
"""Wrap a LangChain chat model so every underlying API call RAGAS makes
|
| 76 |
-
is spaced by a fixed interval.
|
| 77 |
-
|
| 78 |
-
RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
|
| 79 |
-
the langchain model) and the custom MMR path call the model through
|
| 80 |
-
different entry points (sync/async, single/batched). Intercepting
|
| 81 |
-
``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
|
| 82 |
-
every request is throttled regardless of ragas version.
|
| 83 |
-
"""
|
| 84 |
-
|
| 85 |
-
def __init__(self, model, interval: float | None = None):
|
| 86 |
-
self._model = model
|
| 87 |
-
self._interval = _RAGAS_INTERVAL if interval is None else interval
|
| 88 |
-
self._quota_exhausted = False
|
| 89 |
-
|
| 90 |
-
def _call(self, method, *args, **kwargs):
|
| 91 |
-
try:
|
| 92 |
-
return method(*args, **kwargs)
|
| 93 |
-
except Exception as exc:
|
| 94 |
-
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")):
|
| 95 |
-
self._quota_exhausted = True
|
| 96 |
-
raise
|
| 97 |
-
|
| 98 |
-
async def _acall(self, method, *args, **kwargs):
|
| 99 |
-
try:
|
| 100 |
-
return await method(*args, **kwargs)
|
| 101 |
-
except Exception as exc:
|
| 102 |
-
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")):
|
| 103 |
-
self._quota_exhausted = True
|
| 104 |
-
raise
|
| 105 |
-
|
| 106 |
-
def _wait(self) -> None:
|
| 107 |
-
if self._quota_exhausted:
|
| 108 |
-
raise RuntimeError("Evaluation stopped: provider authentication or quota limit; no further calls will be made for this evaluation.")
|
| 109 |
-
if self._interval > 0:
|
| 110 |
-
with _ragas_throttle_lock:
|
| 111 |
-
time.sleep(self._interval)
|
| 112 |
-
|
| 113 |
-
# ββ Sync entry points βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 114 |
-
def invoke(self, *args, **kwargs):
|
| 115 |
-
self._wait()
|
| 116 |
-
return self._call(self._model.invoke, *args, **kwargs)
|
| 117 |
-
|
| 118 |
-
def generate(self, messages, *args, **kwargs):
|
| 119 |
-
# Serialize LangChain batch calls into individual throttled
|
| 120 |
-
# requests so every underlying API call is spaced by the interval.
|
| 121 |
-
if (
|
| 122 |
-
isinstance(messages, list)
|
| 123 |
-
and messages
|
| 124 |
-
and isinstance(messages[0], list)
|
| 125 |
-
):
|
| 126 |
-
from langchain_core.outputs import Generation, LLMResult
|
| 127 |
-
|
| 128 |
-
generations = []
|
| 129 |
-
for msgs in messages:
|
| 130 |
-
self._wait()
|
| 131 |
-
# invoke() does not accept callbacks/run_manager/config that
|
| 132 |
-
# ragas may forward to generate() β drop them here.
|
| 133 |
-
resp = self._call(self._model.invoke, msgs)
|
| 134 |
-
text = resp.content if hasattr(resp, "content") else str(resp)
|
| 135 |
-
generations.append([Generation(text=text, message=resp)])
|
| 136 |
-
return LLMResult(generations=generations, llm_output=None)
|
| 137 |
-
self._wait()
|
| 138 |
-
return self._call(self._model.generate, messages, *args, **kwargs)
|
| 139 |
-
|
| 140 |
-
# ββ Async entry points ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 141 |
-
async def ainvoke(self, *args, **kwargs):
|
| 142 |
-
self._wait()
|
| 143 |
-
return await self._acall(self._model.ainvoke, *args, **kwargs)
|
| 144 |
-
|
| 145 |
-
async def agenerate(self, messages, *args, **kwargs):
|
| 146 |
-
if (
|
| 147 |
-
isinstance(messages, list)
|
| 148 |
-
and messages
|
| 149 |
-
and isinstance(messages[0], list)
|
| 150 |
-
):
|
| 151 |
-
from langchain_core.outputs import Generation, LLMResult
|
| 152 |
-
|
| 153 |
-
generations = []
|
| 154 |
-
for msgs in messages:
|
| 155 |
-
self._wait()
|
| 156 |
-
# Same kwargs caveat as generate(): ainvoke has no callbacks.
|
| 157 |
-
resp = await self._acall(self._model.ainvoke, msgs)
|
| 158 |
-
text = resp.content if hasattr(resp, "content") else str(resp)
|
| 159 |
-
generations.append([Generation(text=text, message=resp)])
|
| 160 |
-
return LLMResult(generations=generations, llm_output=None)
|
| 161 |
-
self._wait()
|
| 162 |
-
return await self._acall(self._model.agenerate, messages, *args, **kwargs)
|
| 163 |
-
|
| 164 |
-
# ββ Everything else passes through ββββββββββββββββββββββββββββββββββ
|
| 165 |
-
def __getattr__(self, name: str):
|
| 166 |
-
return getattr(self._model, name)
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
def _get_evaluator_llm(endpoint: Optional[str] = None):
|
| 170 |
-
"""Return a RAGAS-compatible LLM, reusing the project's LLM factory.
|
| 171 |
-
|
| 172 |
-
Priority:
|
| 173 |
-
1. **Custom endpoint** β when *endpoint* names a configured
|
| 174 |
-
``OCR_ENDPOINT_*`` config, it is used (any provider the user added).
|
| 175 |
-
2. **Groq** (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
|
| 176 |
-
3. **Google Gemini** (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``
|
| 177 |
-
|
| 178 |
-
Groq is preferred over Gemini because scoring fires many LLM calls per
|
| 179 |
-
review and the Gemini free tier (15 req/min) is already shared with the
|
| 180 |
-
main review pipeline β using Groq's separate quota pool avoids the 429
|
| 181 |
-
rate-limit failures that used to zero out the metrics.
|
| 182 |
-
|
| 183 |
-
RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
|
| 184 |
-
"""
|
| 185 |
-
from ragas.llms import LangchainLLMWrapper
|
| 186 |
-
|
| 187 |
-
try:
|
| 188 |
-
if endpoint:
|
| 189 |
-
from llm_factory import create_llm
|
| 190 |
-
|
| 191 |
-
llm = create_llm(endpoint=endpoint, temperature=0, timeout=15, max_retries=0)
|
| 192 |
-
logger.info("RAGAS evaluator: using custom endpoint %s", endpoint)
|
| 193 |
-
return LangchainLLMWrapper(_ThrottledChatModel(llm))
|
| 194 |
-
|
| 195 |
-
from llm_factory import _get_groq_chat, _get_gemini_chat
|
| 196 |
-
|
| 197 |
-
# Keep evaluation bounded: RAGAS runs several provider calls and
|
| 198 |
-
# retrying each one can otherwise hold a review open for minutes.
|
| 199 |
-
configured_model = os.getenv("RAGAS_MODEL", "").strip()
|
| 200 |
-
if configured_model.startswith("groq/"):
|
| 201 |
-
configured_model = configured_model.split("/", 1)[1]
|
| 202 |
-
groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": 15}
|
| 203 |
-
if configured_model:
|
| 204 |
-
groq_kwargs["model"] = configured_model
|
| 205 |
-
llm = _get_groq_chat(**groq_kwargs)
|
| 206 |
-
if llm is None:
|
| 207 |
-
logger.info(
|
| 208 |
-
"RAGAS evaluator: GROQ_API_KEY not set β falling back to Gemini"
|
| 209 |
-
)
|
| 210 |
-
llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=15)
|
| 211 |
-
if llm is None:
|
| 212 |
-
raise ValueError(
|
| 213 |
-
"No LLM available for RAGAS scoring. "
|
| 214 |
-
"Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
|
| 215 |
-
)
|
| 216 |
-
logger.info(
|
| 217 |
-
"RAGAS evaluator: using %s (throttled %ss)",
|
| 218 |
-
type(llm).__name__,
|
| 219 |
-
_RAGAS_INTERVAL,
|
| 220 |
-
)
|
| 221 |
-
return LangchainLLMWrapper(_ThrottledChatModel(llm))
|
| 222 |
-
except ValueError as exc:
|
| 223 |
-
logger.warning("RAGAS evaluator: %s", exc)
|
| 224 |
-
raise RuntimeError(
|
| 225 |
-
"No LLM available for RAGAS scoring. "
|
| 226 |
-
"Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
|
| 227 |
-
) from exc
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
# βββ Score computation βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
def compute_ragas_retrieval_scores(
|
| 234 |
-
query: str,
|
| 235 |
-
retrieved_contexts: list[str],
|
| 236 |
-
ground_truth: Optional[str] = None,
|
| 237 |
-
answer: Optional[str] = None,
|
| 238 |
-
endpoint: Optional[str] = None,
|
| 239 |
-
) -> dict[str, float | None]:
|
| 240 |
-
"""Compute RAGAS retrieval & generation quality metrics.
|
| 241 |
-
|
| 242 |
-
Computes up to five metrics depending on available inputs:
|
| 243 |
-
|
| 244 |
-
+---------------------------+------------------------------------------+
|
| 245 |
-
| Metric | Required inputs |
|
| 246 |
-
+===========================+==========================================+
|
| 247 |
-
| ``context_precision`` | query, retrieved_contexts |
|
| 248 |
-
| ``context_recall`` | query, retrieved_contexts, ground_truth |
|
| 249 |
-
| ``faithfulness`` | query, retrieved_contexts, answer |
|
| 250 |
-
| ``answer_relevancy`` | query, answer |
|
| 251 |
-
| ``mmr`` (Mean Reciprocal | query, retrieved_contexts |
|
| 252 |
-
| Rank) | (custom LLM-judged) |
|
| 253 |
-
+---------------------------+------------------------------------------+
|
| 254 |
-
|
| 255 |
-
Parameters
|
| 256 |
-
----------
|
| 257 |
-
query : str
|
| 258 |
-
The search query β in OpenCodeReview this is the PR diff text.
|
| 259 |
-
retrieved_contexts : list[str]
|
| 260 |
-
The code/document chunks returned by the retrieval node.
|
| 261 |
-
ground_truth : str or None
|
| 262 |
-
Ground-truth reference text (e.g. human review comment). Required
|
| 263 |
-
for ``context_recall``.
|
| 264 |
-
answer : str or None
|
| 265 |
-
The generated answer (e.g. concatenated review findings / verdict).
|
| 266 |
-
Required for ``faithfulness`` and ``answer_relevancy``.
|
| 267 |
-
endpoint : str or None
|
| 268 |
-
Optional name of a configured custom LLM endpoint
|
| 269 |
-
(``OCR_ENDPOINT_*``) to score with. ``None`` uses the built-in
|
| 270 |
-
Groq β Gemini priority.
|
| 271 |
-
|
| 272 |
-
Returns
|
| 273 |
-
-------
|
| 274 |
-
dict
|
| 275 |
-
Mapping of metric name β score (0β1 range, higher is better),
|
| 276 |
-
or ``None`` when that metric's computation failed (e.g. LLM
|
| 277 |
-
rate limit / error). Possible keys: ``context_precision``,
|
| 278 |
-
``context_recall``, ``faithfulness``, ``answer_relevancy``,
|
| 279 |
-
``mmr``.
|
| 280 |
-
|
| 281 |
-
Raises
|
| 282 |
-
------
|
| 283 |
-
RuntimeError
|
| 284 |
-
If RAGAS or a suitable LLM backend is not available.
|
| 285 |
-
"""
|
| 286 |
-
if not _check_ragas():
|
| 287 |
-
raise RuntimeError(
|
| 288 |
-
"RAGAS is not installed. Run: pip install ragas litellm"
|
| 289 |
-
)
|
| 290 |
-
|
| 291 |
-
if not retrieved_contexts:
|
| 292 |
-
logger.warning("No retrieved contexts β RAGAS scores set to 0.0")
|
| 293 |
-
result: dict[str, float] = {"context_precision": 0.0, "mmr": 0.0}
|
| 294 |
-
if ground_truth:
|
| 295 |
-
result["context_recall"] = 0.0
|
| 296 |
-
if answer:
|
| 297 |
-
result["faithfulness"] = 0.0
|
| 298 |
-
result["answer_relevancy"] = 0.0
|
| 299 |
-
return result
|
| 300 |
-
|
| 301 |
-
from ragas.dataset_schema import SingleTurnSample
|
| 302 |
-
|
| 303 |
-
llm = _get_evaluator_llm(endpoint=endpoint)
|
| 304 |
-
scores: dict[str, float | None] = {}
|
| 305 |
-
|
| 306 |
-
# ββ Context Precision (reference-free) βββββββββββββββββββββββββββ
|
| 307 |
-
# Uses LLMContextPrecisionWithoutReference which needs user_input +
|
| 308 |
-
# response + retrieved_contexts (no ground-truth reference required).
|
| 309 |
-
if answer:
|
| 310 |
-
try:
|
| 311 |
-
from ragas.metrics import LLMContextPrecisionWithoutReference
|
| 312 |
-
|
| 313 |
-
scorer = LLMContextPrecisionWithoutReference(llm=llm)
|
| 314 |
-
sample = SingleTurnSample(
|
| 315 |
-
user_input=query,
|
| 316 |
-
response=answer,
|
| 317 |
-
retrieved_contexts=retrieved_contexts,
|
| 318 |
-
)
|
| 319 |
-
result = scorer.single_turn_score(sample)
|
| 320 |
-
scores["context_precision"] = round(float(result), 4)
|
| 321 |
-
logger.info("RAGAS context_precision: %.4f", scores["context_precision"])
|
| 322 |
-
except Exception as exc:
|
| 323 |
-
logger.warning("RAGAS context_precision failed: %s", exc)
|
| 324 |
-
scores["context_precision"] = None
|
| 325 |
-
|
| 326 |
-
# ββ Context Recall (requires ground_truth) βββββββββββββββββββββββ
|
| 327 |
-
if ground_truth:
|
| 328 |
-
try:
|
| 329 |
-
from ragas.metrics import ContextRecall
|
| 330 |
-
|
| 331 |
-
recall_scorer = ContextRecall(llm=llm)
|
| 332 |
-
recall_sample = SingleTurnSample(
|
| 333 |
-
user_input=query,
|
| 334 |
-
retrieved_contexts=retrieved_contexts,
|
| 335 |
-
reference=ground_truth,
|
| 336 |
-
)
|
| 337 |
-
recall_result = recall_scorer.single_turn_score(recall_sample)
|
| 338 |
-
scores["context_recall"] = round(float(recall_result), 4)
|
| 339 |
-
logger.info("RAGAS context_recall: %.4f", scores["context_recall"])
|
| 340 |
-
except Exception as exc:
|
| 341 |
-
logger.warning("RAGAS context_recall failed: %s", exc)
|
| 342 |
-
scores["context_recall"] = None
|
| 343 |
-
|
| 344 |
-
# ββ Faithfulness βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 345 |
-
if answer:
|
| 346 |
-
try:
|
| 347 |
-
from ragas.metrics import Faithfulness
|
| 348 |
-
|
| 349 |
-
faithfulness_scorer = Faithfulness(llm=llm)
|
| 350 |
-
faithful_sample = SingleTurnSample(
|
| 351 |
-
user_input=query,
|
| 352 |
-
response=answer,
|
| 353 |
-
retrieved_contexts=retrieved_contexts,
|
| 354 |
-
)
|
| 355 |
-
faithful_result = faithfulness_scorer.single_turn_score(faithful_sample)
|
| 356 |
-
scores["faithfulness"] = round(float(faithful_result), 4)
|
| 357 |
-
logger.info("RAGAS faithfulness: %.4f", scores["faithfulness"])
|
| 358 |
-
except Exception as exc:
|
| 359 |
-
logger.warning("RAGAS faithfulness failed: %s", exc)
|
| 360 |
-
scores["faithfulness"] = None
|
| 361 |
-
|
| 362 |
-
# ββ Answer Relevancy (ResponseRelevancy) βββββββββββββββββββββββββ
|
| 363 |
-
if answer:
|
| 364 |
-
try:
|
| 365 |
-
from ragas.metrics import ResponseRelevancy
|
| 366 |
-
|
| 367 |
-
# ResponseRelevancy also needs an embedding model for cosine
|
| 368 |
-
# similarity. We create a lightweight one from the project's
|
| 369 |
-
# ChromaDB embedding function (ONNX MiniLM, already cached).
|
| 370 |
-
embeddings = _create_ragas_embeddings()
|
| 371 |
-
if embeddings is None:
|
| 372 |
-
raise RuntimeError(
|
| 373 |
-
"No embedding model available for ResponseRelevancy β "
|
| 374 |
-
"install chromadb"
|
| 375 |
-
)
|
| 376 |
-
|
| 377 |
-
relevancy_scorer = ResponseRelevancy(
|
| 378 |
-
llm=llm,
|
| 379 |
-
embeddings=embeddings,
|
| 380 |
-
strictness=1, # Groq only supports n=1
|
| 381 |
-
)
|
| 382 |
-
relevancy_sample = SingleTurnSample(
|
| 383 |
-
user_input=query,
|
| 384 |
-
response=answer,
|
| 385 |
-
)
|
| 386 |
-
relevancy_result = relevancy_scorer.single_turn_score(relevancy_sample)
|
| 387 |
-
scores["answer_relevancy"] = round(float(relevancy_result), 4)
|
| 388 |
-
logger.info("RAGAS answer_relevancy: %.4f", scores["answer_relevancy"])
|
| 389 |
-
except Exception as exc:
|
| 390 |
-
logger.warning("RAGAS answer_relevancy failed: %s", exc)
|
| 391 |
-
scores["answer_relevancy"] = None
|
| 392 |
-
|
| 393 |
-
# ββ MMR (Mean Reciprocal Rank) β custom implementation βββββββββββ
|
| 394 |
-
try:
|
| 395 |
-
mmr = _compute_mmr(query, retrieved_contexts, llm)
|
| 396 |
-
scores["mmr"] = round(mmr, 4)
|
| 397 |
-
logger.info("RAGAS mmr: %.4f", scores["mmr"])
|
| 398 |
-
except Exception as exc:
|
| 399 |
-
logger.warning("RAGAS mmr failed: %s", exc)
|
| 400 |
-
scores["mmr"] = None
|
| 401 |
-
|
| 402 |
-
# ββ Context Precision (reference-based, fallback when no answer) β
|
| 403 |
-
if "context_precision" not in scores and ground_truth:
|
| 404 |
-
try:
|
| 405 |
-
from ragas.metrics import ContextPrecision
|
| 406 |
-
|
| 407 |
-
scorer = ContextPrecision(llm=llm)
|
| 408 |
-
sample = SingleTurnSample(
|
| 409 |
-
user_input=query,
|
| 410 |
-
retrieved_contexts=retrieved_contexts,
|
| 411 |
-
reference=ground_truth,
|
| 412 |
-
)
|
| 413 |
-
result = scorer.single_turn_score(sample)
|
| 414 |
-
scores["context_precision"] = round(float(result), 4)
|
| 415 |
-
logger.info("RAGAS context_precision: %.4f", scores["context_precision"])
|
| 416 |
-
except Exception as exc:
|
| 417 |
-
logger.warning("RAGAS context_precision failed: %s", exc)
|
| 418 |
-
scores["context_precision"] = None
|
| 419 |
-
|
| 420 |
-
# Deterministic fallback: retrieval-only reviews may not have an answer or
|
| 421 |
-
# reference, and provider-backed judges can fail or rate-limit. Preserve a
|
| 422 |
-
# truthful numeric signal from lexical query/context coverage instead of
|
| 423 |
-
# returning an empty score map.
|
| 424 |
-
if not any(value is not None for value in scores.values()):
|
| 425 |
-
query_terms = {term.lower() for term in query.split() if len(term) >= 4}
|
| 426 |
-
overlaps = []
|
| 427 |
-
for context in retrieved_contexts:
|
| 428 |
-
context_terms = {term.lower() for term in context.split() if len(term) >= 4}
|
| 429 |
-
overlaps.append(len(query_terms & context_terms) / max(1, len(query_terms)))
|
| 430 |
-
coverage = round(sum(overlaps) / max(1, len(overlaps)), 4)
|
| 431 |
-
first_relevant = next((index for index, value in enumerate(overlaps, 1) if value > 0), None)
|
| 432 |
-
scores["context_precision"] = coverage
|
| 433 |
-
scores["mmr"] = round(1 / first_relevant, 4) if first_relevant else 0.0
|
| 434 |
-
logger.info("RAGAS deterministic fallback: context_precision=%.4f mmr=%.4f", scores["context_precision"], scores["mmr"])
|
| 435 |
-
return scores
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
def _create_ragas_embeddings():
|
| 439 |
-
"""Return a lightweight embedding object compatible with RAGAS metrics.
|
| 440 |
-
|
| 441 |
-
Wraps the ChromaDB ONNX MiniLM embedding function so that metrics like
|
| 442 |
-
``ResponseRelevancy`` can compute cosine similarity between embeddings.
|
| 443 |
-
The underlying ONNX model is cached globally and loads in <1 s.
|
| 444 |
-
"""
|
| 445 |
-
if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
|
| 446 |
-
logger.info("Local RAGAS embeddings disabled; skipping answer relevancy")
|
| 447 |
-
return None
|
| 448 |
-
try:
|
| 449 |
-
from chromadb.utils import embedding_functions
|
| 450 |
-
|
| 451 |
-
if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
|
| 452 |
-
ef = embedding_functions.ONNXMiniLM_L6_V2()
|
| 453 |
-
else:
|
| 454 |
-
ef = embedding_functions.SentenceTransformerEmbeddingFunction(
|
| 455 |
-
model_name="all-MiniLM-L6-v2"
|
| 456 |
-
)
|
| 457 |
-
|
| 458 |
-
class _RagasEmbeddings:
|
| 459 |
-
def __init__(self, ef):
|
| 460 |
-
self._ef = ef
|
| 461 |
-
|
| 462 |
-
def embed_query(self, text: str) -> list[float]:
|
| 463 |
-
result = self._ef([text])[0]
|
| 464 |
-
return list(result) if not isinstance(result, list) else result
|
| 465 |
-
|
| 466 |
-
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
| 467 |
-
results = self._ef(texts)
|
| 468 |
-
return [list(r) if not isinstance(r, list) else r for r in results]
|
| 469 |
-
|
| 470 |
-
return _RagasEmbeddings(ef)
|
| 471 |
-
except Exception as exc:
|
| 472 |
-
logger.warning("Cannot create RAGAS embeddings: %s", exc)
|
| 473 |
-
return None
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
def _compute_mmr(
|
| 477 |
-
query: str,
|
| 478 |
-
retrieved_contexts: list[str],
|
| 479 |
-
llm: Any,
|
| 480 |
-
) -> float:
|
| 481 |
-
"""Compute Mean Reciprocal Rank β how early the first relevant chunk appears.
|
| 482 |
-
|
| 483 |
-
Uses the LLM to judge each chunk's relevance to the query in order.
|
| 484 |
-
The first chunk judged relevant determines the reciprocal rank:
|
| 485 |
-
``1 / rank_of_first_relevant``. Returns 0.0 if none are relevant.
|
| 486 |
-
|
| 487 |
-
Parameters
|
| 488 |
-
----------
|
| 489 |
-
query : str
|
| 490 |
-
The search query (PR diff).
|
| 491 |
-
retrieved_contexts : list[str]
|
| 492 |
-
Ranked list of retrieved code chunks.
|
| 493 |
-
llm : LangchainLLMWrapper
|
| 494 |
-
RAGAS-wrapped LLM for relevance judgments.
|
| 495 |
-
|
| 496 |
-
Returns
|
| 497 |
-
-------
|
| 498 |
-
float
|
| 499 |
-
MMR score in [0, 1]; 0.0 when chunks were judged but none were
|
| 500 |
-
relevant.
|
| 501 |
-
|
| 502 |
-
Raises
|
| 503 |
-
------
|
| 504 |
-
RuntimeError
|
| 505 |
-
If every relevance judgment failed (e.g. LLM rate-limited) β
|
| 506 |
-
callers treat this as a failed metric rather than a fake 0.0.
|
| 507 |
-
"""
|
| 508 |
-
if not retrieved_contexts:
|
| 509 |
-
return 0.0
|
| 510 |
-
|
| 511 |
-
# Score up to the first 5 chunks for relevance using the LLM.
|
| 512 |
-
# Top-5 MMR is standard β rank 5 yields 1/5 = 0.20, and
|
| 513 |
-
# anything beyond rank 5 barely changes the score anyway.
|
| 514 |
-
MAX_MMR_RANK = 2
|
| 515 |
-
top_chunks = retrieved_contexts[:MAX_MMR_RANK]
|
| 516 |
-
|
| 517 |
-
judged = 0
|
| 518 |
-
for rank, chunk in enumerate(top_chunks, start=1):
|
| 519 |
-
try:
|
| 520 |
-
prompt = (
|
| 521 |
-
f"Is the following code/document chunk relevant to the question?\n\n"
|
| 522 |
-
f"Question: {query[:2_000]}\n\n"
|
| 523 |
-
f"Chunk: {chunk[:2_000]}\n\n"
|
| 524 |
-
f"Answer with exactly one word: YES or NO"
|
| 525 |
-
)
|
| 526 |
-
# Use the wrapped LangChain model for fast synchronous invoke.
|
| 527 |
-
# LangchainLLMWrapper stores the model as .langchain_llm in ragas
|
| 528 |
-
# 0.4.x and as .llm in 0.3.x β accept both.
|
| 529 |
-
langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
|
| 530 |
-
# Space the relevance judgments too β this unwrapped path bypasses
|
| 531 |
-
# the model wrapper on some ragas versions, so sleep explicitly
|
| 532 |
-
# (unless the wrapper is already in the path, to avoid double-sleep).
|
| 533 |
-
if not isinstance(langchain_model, _ThrottledChatModel):
|
| 534 |
-
time.sleep(_RAGAS_INTERVAL)
|
| 535 |
-
raw = langchain_model.invoke(prompt)
|
| 536 |
-
response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
|
| 537 |
-
if response_text.startswith("Y"):
|
| 538 |
-
return 1.0 / rank
|
| 539 |
-
judged += 1 # judge responded β chunk deemed not relevant
|
| 540 |
-
except Exception:
|
| 541 |
-
continue
|
| 542 |
-
|
| 543 |
-
if judged == 0:
|
| 544 |
-
# Every relevance judgment failed (e.g. LLM rate-limited) β surface
|
| 545 |
-
# this as a failed metric instead of a misleading 0.0.
|
| 546 |
-
raise RuntimeError("all MMR relevance judgments failed")
|
| 547 |
-
|
| 548 |
-
return 0.0
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
def log_ragas_scores_to_langfuse(
|
| 552 |
-
scores: dict[str, float | None],
|
| 553 |
-
repo: str = "",
|
| 554 |
-
pr_number: int = 0,
|
| 555 |
-
handler: Any = None,
|
| 556 |
-
) -> None:
|
| 557 |
-
"""Log RAGAS metrics as Langfuse scores (linked to the review trace).
|
| 558 |
-
|
| 559 |
-
Parameters
|
| 560 |
-
----------
|
| 561 |
-
scores : dict
|
| 562 |
-
Output of :func:`compute_ragas_retrieval_scores`.
|
| 563 |
-
repo : str
|
| 564 |
-
GitHub repository name (e.g. ``\"psf/requests\"``).
|
| 565 |
-
pr_number : int
|
| 566 |
-
Pull request number.
|
| 567 |
-
handler : Langfuse CallbackHandler or None
|
| 568 |
-
Handler from the current review run, used to link scores to the trace.
|
| 569 |
-
"""
|
| 570 |
-
try:
|
| 571 |
-
from observability import log_langfuse_score
|
| 572 |
-
except ImportError:
|
| 573 |
-
logger.debug("observability module not available β skipping Langfuse")
|
| 574 |
-
return
|
| 575 |
-
|
| 576 |
-
for metric_name, value in scores.items():
|
| 577 |
-
if value is None:
|
| 578 |
-
continue
|
| 579 |
-
log_langfuse_score(
|
| 580 |
-
name=f"ragas_{metric_name}",
|
| 581 |
-
value=value,
|
| 582 |
-
comment=f"{repo}#{pr_number} β {metric_name}",
|
| 583 |
-
handler=handler,
|
| 584 |
-
)
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
# βββ Standalone CLI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
def main() -> None:
|
| 591 |
-
"""CLI entry point: compute RAGAS scores from a JSONL dataset.
|
| 592 |
-
|
| 593 |
-
Usage::
|
| 594 |
-
|
| 595 |
-
python eval_data/ragas_eval.py --data eval_data/prs.jsonl
|
| 596 |
-
"""
|
| 597 |
-
import argparse
|
| 598 |
-
import json
|
| 599 |
-
|
| 600 |
-
parser = argparse.ArgumentParser(
|
| 601 |
-
description="Compute RAGAS retrieval quality scores on evaluation data",
|
| 602 |
-
)
|
| 603 |
-
parser.add_argument(
|
| 604 |
-
"--data", default=None,
|
| 605 |
-
help="Path to JSONL dataset (same format as evaluate.py)",
|
| 606 |
-
)
|
| 607 |
-
parser.add_argument(
|
| 608 |
-
"--output", default=None,
|
| 609 |
-
help="Path to write per-PR RAGAS scores (JSON)",
|
| 610 |
-
)
|
| 611 |
-
parser.add_argument(
|
| 612 |
-
"--max-prs", type=int, default=None,
|
| 613 |
-
help="Max PRs to process",
|
| 614 |
-
)
|
| 615 |
-
parser.add_argument(
|
| 616 |
-
"--log-to-observability", action="store_true",
|
| 617 |
-
help="Log RAGAS scores to Langfuse",
|
| 618 |
-
)
|
| 619 |
-
args = parser.parse_args()
|
| 620 |
-
|
| 621 |
-
logging.basicConfig(
|
| 622 |
-
level=logging.INFO,
|
| 623 |
-
format="%(asctime)s [%(levelname)s] %(name)s β %(message)s",
|
| 624 |
-
)
|
| 625 |
-
|
| 626 |
-
if not args.data:
|
| 627 |
-
# If no data file specified, try default location
|
| 628 |
-
default_path = os.path.join(
|
| 629 |
-
os.path.dirname(__file__), "prs.jsonl"
|
| 630 |
-
)
|
| 631 |
-
if os.path.exists(default_path):
|
| 632 |
-
args.data = default_path
|
| 633 |
-
else:
|
| 634 |
-
logger.error(
|
| 635 |
-
"No --data provided and default not found at %s. "
|
| 636 |
-
"Run eval_data/fetcher.py first.",
|
| 637 |
-
default_path,
|
| 638 |
-
)
|
| 639 |
-
return
|
| 640 |
-
|
| 641 |
-
with open(args.data, "r", encoding="utf-8") as f:
|
| 642 |
-
entries = [json.loads(line) for line in f if line.strip()]
|
| 643 |
-
|
| 644 |
-
if args.max_prs:
|
| 645 |
-
entries = entries[: args.max_prs]
|
| 646 |
-
|
| 647 |
-
all_scores: list[dict] = []
|
| 648 |
-
for entry in entries:
|
| 649 |
-
repo = entry.get("repo", "?")
|
| 650 |
-
pr = entry.get("pr_number", 0)
|
| 651 |
-
diff = entry.get("diff", "")
|
| 652 |
-
ground_truth_list = entry.get("ground_truth", [])
|
| 653 |
-
|
| 654 |
-
# Use the diff as the query, and first few human comments
|
| 655 |
-
# as a proxy for "what the retrieval should have found"
|
| 656 |
-
query = diff[:8_000] if diff else entry.get("title", "")
|
| 657 |
-
gt_text = (
|
| 658 |
-
" ".join(
|
| 659 |
-
g.get("comment", "")
|
| 660 |
-
for g in ground_truth_list[:5]
|
| 661 |
-
)
|
| 662 |
-
if ground_truth_list
|
| 663 |
-
else None
|
| 664 |
-
)
|
| 665 |
-
|
| 666 |
-
# Retrieved contexts come from the graph run, but for the CLI
|
| 667 |
-
# we don't re-run the graph β we just skip if no retrieval data
|
| 668 |
-
# is available in the entry.
|
| 669 |
-
stored_contexts = entry.get("retrieved_contexts", [])
|
| 670 |
-
if not stored_contexts:
|
| 671 |
-
logger.info(
|
| 672 |
-
"[%s#%d] No stored retrieval contexts β skipping RAGAS",
|
| 673 |
-
repo, pr,
|
| 674 |
-
)
|
| 675 |
-
continue
|
| 676 |
-
|
| 677 |
-
logger.info("[%s#%d] Computing RAGAS scores β¦", repo, pr)
|
| 678 |
-
try:
|
| 679 |
-
scores = compute_ragas_retrieval_scores(
|
| 680 |
-
query=query,
|
| 681 |
-
retrieved_contexts=stored_contexts,
|
| 682 |
-
ground_truth=gt_text,
|
| 683 |
-
)
|
| 684 |
-
except RuntimeError as exc:
|
| 685 |
-
logger.warning("[%s#%d] %s", repo, pr, exc)
|
| 686 |
-
break
|
| 687 |
-
|
| 688 |
-
scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
|
| 689 |
-
all_scores.append(scores)
|
| 690 |
-
|
| 691 |
-
if args.log_to_observability:
|
| 692 |
-
log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)
|
| 693 |
-
|
| 694 |
-
print(
|
| 695 |
-
f" {repo}#{pr}: "
|
| 696 |
-
+ " | ".join(
|
| 697 |
-
f"{k}={v:.3f}" for k, v in scores.items()
|
| 698 |
-
if k not in ("repo", "pr_number", "id") and v is not None
|
| 699 |
-
)
|
| 700 |
-
)
|
| 701 |
-
|
| 702 |
-
# Print aggregate
|
| 703 |
-
if all_scores:
|
| 704 |
-
print()
|
| 705 |
-
print("=" * 60)
|
| 706 |
-
print(" Aggregate RAGAS scores")
|
| 707 |
-
print("=" * 60)
|
| 708 |
-
metrics = [
|
| 709 |
-
k for k in all_scores[0].keys()
|
| 710 |
-
if k not in ("repo", "pr_number", "id")
|
| 711 |
-
]
|
| 712 |
-
for metric in metrics:
|
| 713 |
-
values = [
|
| 714 |
-
s.get(metric) for s in all_scores
|
| 715 |
-
if s.get(metric) is not None
|
| 716 |
-
]
|
| 717 |
-
if not values:
|
| 718 |
-
print(f" {metric:30s}: n/a (no successful scores)")
|
| 719 |
-
continue
|
| 720 |
-
avg = sum(values) / len(values)
|
| 721 |
-
print(f" {metric:30s}: {avg:.4f} (over {len(values)} PRs)")
|
| 722 |
-
print()
|
| 723 |
-
|
| 724 |
-
# Save output
|
| 725 |
-
if args.output and all_scores:
|
| 726 |
-
with open(args.output, "w", encoding="utf-8") as f:
|
| 727 |
-
json.dump(all_scores, f, indent=2)
|
| 728 |
-
logger.info("Saved RAGAS scores to %s", args.output)
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
if __name__ == "__main__":
|
| 732 |
-
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 |
+
import logging
|
| 30 |
+
import os
|
| 31 |
+
import threading
|
| 32 |
+
import time
|
| 33 |
+
from typing import Any, Optional
|
| 34 |
+
|
| 35 |
+
logger = logging.getLogger(__name__)
|
| 36 |
+
|
| 37 |
+
# βββ Lazy RAGAS imports with graceful fallback ββββββββββββββββββββββββββββββ
|
| 38 |
+
|
| 39 |
+
_RAGAS_AVAILABLE: bool | None = None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _check_ragas() -> bool:
|
| 43 |
+
"""Return True if RAGAS is available.
|
| 44 |
+
|
| 45 |
+
Note: ``litellm`` is NOT required because RAGAS scoring uses the
|
| 46 |
+
project's own LLM factory (Gemini or Groq via LangChain), not
|
| 47 |
+
litellm internally.
|
| 48 |
+
"""
|
| 49 |
+
global _RAGAS_AVAILABLE
|
| 50 |
+
if _RAGAS_AVAILABLE is not None:
|
| 51 |
+
return _RAGAS_AVAILABLE
|
| 52 |
+
try:
|
| 53 |
+
import ragas # noqa: F401
|
| 54 |
+
_RAGAS_AVAILABLE = True
|
| 55 |
+
except ImportError:
|
| 56 |
+
logger.warning(
|
| 57 |
+
"ragas not installed. Install with: pip install ragas"
|
| 58 |
+
)
|
| 59 |
+
_RAGAS_AVAILABLE = False
|
| 60 |
+
return _RAGAS_AVAILABLE
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
|
| 64 |
+
# burst of ~20-30 model calls per review (context-precision judgments,
|
| 65 |
+
# faithfulness verification, answer relevancy, MMR relevance checks).
|
| 66 |
+
# Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
|
| 67 |
+
# limits so scoring completes instead of tripping 429s β which previously
|
| 68 |
+
# caused long retry backoffs and 0.0000 scores. Override with the
|
| 69 |
+
# OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
|
| 70 |
+
_RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
|
| 71 |
+
_ragas_throttle_lock = threading.Lock()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class _ThrottledChatModel:
|
| 75 |
+
"""Wrap a LangChain chat model so every underlying API call RAGAS makes
|
| 76 |
+
is spaced by a fixed interval.
|
| 77 |
+
|
| 78 |
+
RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
|
| 79 |
+
the langchain model) and the custom MMR path call the model through
|
| 80 |
+
different entry points (sync/async, single/batched). Intercepting
|
| 81 |
+
``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
|
| 82 |
+
every request is throttled regardless of ragas version.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
def __init__(self, model, interval: float | None = None):
|
| 86 |
+
self._model = model
|
| 87 |
+
self._interval = _RAGAS_INTERVAL if interval is None else interval
|
| 88 |
+
self._quota_exhausted = False
|
| 89 |
+
|
| 90 |
+
def _call(self, method, *args, **kwargs):
|
| 91 |
+
try:
|
| 92 |
+
return method(*args, **kwargs)
|
| 93 |
+
except Exception as exc:
|
| 94 |
+
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")):
|
| 95 |
+
self._quota_exhausted = True
|
| 96 |
+
raise
|
| 97 |
+
|
| 98 |
+
async def _acall(self, method, *args, **kwargs):
|
| 99 |
+
try:
|
| 100 |
+
return await method(*args, **kwargs)
|
| 101 |
+
except Exception as exc:
|
| 102 |
+
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")):
|
| 103 |
+
self._quota_exhausted = True
|
| 104 |
+
raise
|
| 105 |
+
|
| 106 |
+
def _wait(self) -> None:
|
| 107 |
+
if self._quota_exhausted:
|
| 108 |
+
raise RuntimeError("Evaluation stopped: provider authentication or quota limit; no further calls will be made for this evaluation.")
|
| 109 |
+
if self._interval > 0:
|
| 110 |
+
with _ragas_throttle_lock:
|
| 111 |
+
time.sleep(self._interval)
|
| 112 |
+
|
| 113 |
+
# ββ Sync entry points βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 114 |
+
def invoke(self, *args, **kwargs):
|
| 115 |
+
self._wait()
|
| 116 |
+
return self._call(self._model.invoke, *args, **kwargs)
|
| 117 |
+
|
| 118 |
+
def generate(self, messages, *args, **kwargs):
|
| 119 |
+
# Serialize LangChain batch calls into individual throttled
|
| 120 |
+
# requests so every underlying API call is spaced by the interval.
|
| 121 |
+
if (
|
| 122 |
+
isinstance(messages, list)
|
| 123 |
+
and messages
|
| 124 |
+
and isinstance(messages[0], list)
|
| 125 |
+
):
|
| 126 |
+
from langchain_core.outputs import Generation, LLMResult
|
| 127 |
+
|
| 128 |
+
generations = []
|
| 129 |
+
for msgs in messages:
|
| 130 |
+
self._wait()
|
| 131 |
+
# invoke() does not accept callbacks/run_manager/config that
|
| 132 |
+
# ragas may forward to generate() β drop them here.
|
| 133 |
+
resp = self._call(self._model.invoke, msgs)
|
| 134 |
+
text = resp.content if hasattr(resp, "content") else str(resp)
|
| 135 |
+
generations.append([Generation(text=text, message=resp)])
|
| 136 |
+
return LLMResult(generations=generations, llm_output=None)
|
| 137 |
+
self._wait()
|
| 138 |
+
return self._call(self._model.generate, messages, *args, **kwargs)
|
| 139 |
+
|
| 140 |
+
# ββ Async entry points ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 141 |
+
async def ainvoke(self, *args, **kwargs):
|
| 142 |
+
self._wait()
|
| 143 |
+
return await self._acall(self._model.ainvoke, *args, **kwargs)
|
| 144 |
+
|
| 145 |
+
async def agenerate(self, messages, *args, **kwargs):
|
| 146 |
+
if (
|
| 147 |
+
isinstance(messages, list)
|
| 148 |
+
and messages
|
| 149 |
+
and isinstance(messages[0], list)
|
| 150 |
+
):
|
| 151 |
+
from langchain_core.outputs import Generation, LLMResult
|
| 152 |
+
|
| 153 |
+
generations = []
|
| 154 |
+
for msgs in messages:
|
| 155 |
+
self._wait()
|
| 156 |
+
# Same kwargs caveat as generate(): ainvoke has no callbacks.
|
| 157 |
+
resp = await self._acall(self._model.ainvoke, msgs)
|
| 158 |
+
text = resp.content if hasattr(resp, "content") else str(resp)
|
| 159 |
+
generations.append([Generation(text=text, message=resp)])
|
| 160 |
+
return LLMResult(generations=generations, llm_output=None)
|
| 161 |
+
self._wait()
|
| 162 |
+
return await self._acall(self._model.agenerate, messages, *args, **kwargs)
|
| 163 |
+
|
| 164 |
+
# ββ Everything else passes through ββββββββββββββββββββββββββββββββββ
|
| 165 |
+
def __getattr__(self, name: str):
|
| 166 |
+
return getattr(self._model, name)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _get_evaluator_llm(endpoint: Optional[str] = None):
|
| 170 |
+
"""Return a RAGAS-compatible LLM, reusing the project's LLM factory.
|
| 171 |
+
|
| 172 |
+
Priority:
|
| 173 |
+
1. **Custom endpoint** β when *endpoint* names a configured
|
| 174 |
+
``OCR_ENDPOINT_*`` config, it is used (any provider the user added).
|
| 175 |
+
2. **Groq** (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
|
| 176 |
+
3. **Google Gemini** (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``
|
| 177 |
+
|
| 178 |
+
Groq is preferred over Gemini because scoring fires many LLM calls per
|
| 179 |
+
review and the Gemini free tier (15 req/min) is already shared with the
|
| 180 |
+
main review pipeline β using Groq's separate quota pool avoids the 429
|
| 181 |
+
rate-limit failures that used to zero out the metrics.
|
| 182 |
+
|
| 183 |
+
RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
|
| 184 |
+
"""
|
| 185 |
+
from ragas.llms import LangchainLLMWrapper
|
| 186 |
+
|
| 187 |
+
try:
|
| 188 |
+
if endpoint:
|
| 189 |
+
from llm_factory import create_llm
|
| 190 |
+
|
| 191 |
+
llm = create_llm(endpoint=endpoint, temperature=0, timeout=15, max_retries=0)
|
| 192 |
+
logger.info("RAGAS evaluator: using custom endpoint %s", endpoint)
|
| 193 |
+
return LangchainLLMWrapper(_ThrottledChatModel(llm))
|
| 194 |
+
|
| 195 |
+
from llm_factory import _get_groq_chat, _get_gemini_chat
|
| 196 |
+
|
| 197 |
+
# Keep evaluation bounded: RAGAS runs several provider calls and
|
| 198 |
+
# retrying each one can otherwise hold a review open for minutes.
|
| 199 |
+
configured_model = os.getenv("RAGAS_MODEL", "").strip()
|
| 200 |
+
if configured_model.startswith("groq/"):
|
| 201 |
+
configured_model = configured_model.split("/", 1)[1]
|
| 202 |
+
groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": 15}
|
| 203 |
+
if configured_model:
|
| 204 |
+
groq_kwargs["model"] = configured_model
|
| 205 |
+
llm = _get_groq_chat(**groq_kwargs)
|
| 206 |
+
if llm is None:
|
| 207 |
+
logger.info(
|
| 208 |
+
"RAGAS evaluator: GROQ_API_KEY not set β falling back to Gemini"
|
| 209 |
+
)
|
| 210 |
+
llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=15)
|
| 211 |
+
if llm is None:
|
| 212 |
+
raise ValueError(
|
| 213 |
+
"No LLM available for RAGAS scoring. "
|
| 214 |
+
"Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
|
| 215 |
+
)
|
| 216 |
+
logger.info(
|
| 217 |
+
"RAGAS evaluator: using %s (throttled %ss)",
|
| 218 |
+
type(llm).__name__,
|
| 219 |
+
_RAGAS_INTERVAL,
|
| 220 |
+
)
|
| 221 |
+
return LangchainLLMWrapper(_ThrottledChatModel(llm))
|
| 222 |
+
except ValueError as exc:
|
| 223 |
+
logger.warning("RAGAS evaluator: %s", exc)
|
| 224 |
+
raise RuntimeError(
|
| 225 |
+
"No LLM available for RAGAS scoring. "
|
| 226 |
+
"Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
|
| 227 |
+
) from exc
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# βββ Score computation βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def compute_ragas_retrieval_scores(
|
| 234 |
+
query: str,
|
| 235 |
+
retrieved_contexts: list[str],
|
| 236 |
+
ground_truth: Optional[str] = None,
|
| 237 |
+
answer: Optional[str] = None,
|
| 238 |
+
endpoint: Optional[str] = None,
|
| 239 |
+
) -> dict[str, float | None]:
|
| 240 |
+
"""Compute RAGAS retrieval & generation quality metrics.
|
| 241 |
+
|
| 242 |
+
Computes up to five metrics depending on available inputs:
|
| 243 |
+
|
| 244 |
+
+---------------------------+------------------------------------------+
|
| 245 |
+
| Metric | Required inputs |
|
| 246 |
+
+===========================+==========================================+
|
| 247 |
+
| ``context_precision`` | query, retrieved_contexts |
|
| 248 |
+
| ``context_recall`` | query, retrieved_contexts, ground_truth |
|
| 249 |
+
| ``faithfulness`` | query, retrieved_contexts, answer |
|
| 250 |
+
| ``answer_relevancy`` | query, answer |
|
| 251 |
+
| ``mmr`` (Mean Reciprocal | query, retrieved_contexts |
|
| 252 |
+
| Rank) | (custom LLM-judged) |
|
| 253 |
+
+---------------------------+------------------------------------------+
|
| 254 |
+
|
| 255 |
+
Parameters
|
| 256 |
+
----------
|
| 257 |
+
query : str
|
| 258 |
+
The search query β in OpenCodeReview this is the PR diff text.
|
| 259 |
+
retrieved_contexts : list[str]
|
| 260 |
+
The code/document chunks returned by the retrieval node.
|
| 261 |
+
ground_truth : str or None
|
| 262 |
+
Ground-truth reference text (e.g. human review comment). Required
|
| 263 |
+
for ``context_recall``.
|
| 264 |
+
answer : str or None
|
| 265 |
+
The generated answer (e.g. concatenated review findings / verdict).
|
| 266 |
+
Required for ``faithfulness`` and ``answer_relevancy``.
|
| 267 |
+
endpoint : str or None
|
| 268 |
+
Optional name of a configured custom LLM endpoint
|
| 269 |
+
(``OCR_ENDPOINT_*``) to score with. ``None`` uses the built-in
|
| 270 |
+
Groq β Gemini priority.
|
| 271 |
+
|
| 272 |
+
Returns
|
| 273 |
+
-------
|
| 274 |
+
dict
|
| 275 |
+
Mapping of metric name β score (0β1 range, higher is better),
|
| 276 |
+
or ``None`` when that metric's computation failed (e.g. LLM
|
| 277 |
+
rate limit / error). Possible keys: ``context_precision``,
|
| 278 |
+
``context_recall``, ``faithfulness``, ``answer_relevancy``,
|
| 279 |
+
``mmr``.
|
| 280 |
+
|
| 281 |
+
Raises
|
| 282 |
+
------
|
| 283 |
+
RuntimeError
|
| 284 |
+
If RAGAS or a suitable LLM backend is not available.
|
| 285 |
+
"""
|
| 286 |
+
if not _check_ragas():
|
| 287 |
+
raise RuntimeError(
|
| 288 |
+
"RAGAS is not installed. Run: pip install ragas litellm"
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
if not retrieved_contexts:
|
| 292 |
+
logger.warning("No retrieved contexts β RAGAS scores set to 0.0")
|
| 293 |
+
result: dict[str, float] = {"context_precision": 0.0, "mmr": 0.0}
|
| 294 |
+
if ground_truth:
|
| 295 |
+
result["context_recall"] = 0.0
|
| 296 |
+
if answer:
|
| 297 |
+
result["faithfulness"] = 0.0
|
| 298 |
+
result["answer_relevancy"] = 0.0
|
| 299 |
+
return result
|
| 300 |
+
|
| 301 |
+
from ragas.dataset_schema import SingleTurnSample
|
| 302 |
+
|
| 303 |
+
llm = _get_evaluator_llm(endpoint=endpoint)
|
| 304 |
+
scores: dict[str, float | None] = {}
|
| 305 |
+
|
| 306 |
+
# ββ Context Precision (reference-free) βββββββββββββββββββββββββββ
|
| 307 |
+
# Uses LLMContextPrecisionWithoutReference which needs user_input +
|
| 308 |
+
# response + retrieved_contexts (no ground-truth reference required).
|
| 309 |
+
if answer:
|
| 310 |
+
try:
|
| 311 |
+
from ragas.metrics import LLMContextPrecisionWithoutReference
|
| 312 |
+
|
| 313 |
+
scorer = LLMContextPrecisionWithoutReference(llm=llm)
|
| 314 |
+
sample = SingleTurnSample(
|
| 315 |
+
user_input=query,
|
| 316 |
+
response=answer,
|
| 317 |
+
retrieved_contexts=retrieved_contexts,
|
| 318 |
+
)
|
| 319 |
+
result = scorer.single_turn_score(sample)
|
| 320 |
+
scores["context_precision"] = round(float(result), 4)
|
| 321 |
+
logger.info("RAGAS context_precision: %.4f", scores["context_precision"])
|
| 322 |
+
except Exception as exc:
|
| 323 |
+
logger.warning("RAGAS context_precision failed: %s", exc)
|
| 324 |
+
scores["context_precision"] = None
|
| 325 |
+
|
| 326 |
+
# ββ Context Recall (requires ground_truth) βββββββββββββββββββββββ
|
| 327 |
+
if ground_truth:
|
| 328 |
+
try:
|
| 329 |
+
from ragas.metrics import ContextRecall
|
| 330 |
+
|
| 331 |
+
recall_scorer = ContextRecall(llm=llm)
|
| 332 |
+
recall_sample = SingleTurnSample(
|
| 333 |
+
user_input=query,
|
| 334 |
+
retrieved_contexts=retrieved_contexts,
|
| 335 |
+
reference=ground_truth,
|
| 336 |
+
)
|
| 337 |
+
recall_result = recall_scorer.single_turn_score(recall_sample)
|
| 338 |
+
scores["context_recall"] = round(float(recall_result), 4)
|
| 339 |
+
logger.info("RAGAS context_recall: %.4f", scores["context_recall"])
|
| 340 |
+
except Exception as exc:
|
| 341 |
+
logger.warning("RAGAS context_recall failed: %s", exc)
|
| 342 |
+
scores["context_recall"] = None
|
| 343 |
+
|
| 344 |
+
# ββ Faithfulness βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 345 |
+
if answer:
|
| 346 |
+
try:
|
| 347 |
+
from ragas.metrics import Faithfulness
|
| 348 |
+
|
| 349 |
+
faithfulness_scorer = Faithfulness(llm=llm)
|
| 350 |
+
faithful_sample = SingleTurnSample(
|
| 351 |
+
user_input=query,
|
| 352 |
+
response=answer,
|
| 353 |
+
retrieved_contexts=retrieved_contexts,
|
| 354 |
+
)
|
| 355 |
+
faithful_result = faithfulness_scorer.single_turn_score(faithful_sample)
|
| 356 |
+
scores["faithfulness"] = round(float(faithful_result), 4)
|
| 357 |
+
logger.info("RAGAS faithfulness: %.4f", scores["faithfulness"])
|
| 358 |
+
except Exception as exc:
|
| 359 |
+
logger.warning("RAGAS faithfulness failed: %s", exc)
|
| 360 |
+
scores["faithfulness"] = None
|
| 361 |
+
|
| 362 |
+
# ββ Answer Relevancy (ResponseRelevancy) βββββββββββββββββββββββββ
|
| 363 |
+
if answer:
|
| 364 |
+
try:
|
| 365 |
+
from ragas.metrics import ResponseRelevancy
|
| 366 |
+
|
| 367 |
+
# ResponseRelevancy also needs an embedding model for cosine
|
| 368 |
+
# similarity. We create a lightweight one from the project's
|
| 369 |
+
# ChromaDB embedding function (ONNX MiniLM, already cached).
|
| 370 |
+
embeddings = _create_ragas_embeddings()
|
| 371 |
+
if embeddings is None:
|
| 372 |
+
raise RuntimeError(
|
| 373 |
+
"No embedding model available for ResponseRelevancy β "
|
| 374 |
+
"install chromadb"
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
relevancy_scorer = ResponseRelevancy(
|
| 378 |
+
llm=llm,
|
| 379 |
+
embeddings=embeddings,
|
| 380 |
+
strictness=1, # Groq only supports n=1
|
| 381 |
+
)
|
| 382 |
+
relevancy_sample = SingleTurnSample(
|
| 383 |
+
user_input=query,
|
| 384 |
+
response=answer,
|
| 385 |
+
)
|
| 386 |
+
relevancy_result = relevancy_scorer.single_turn_score(relevancy_sample)
|
| 387 |
+
scores["answer_relevancy"] = round(float(relevancy_result), 4)
|
| 388 |
+
logger.info("RAGAS answer_relevancy: %.4f", scores["answer_relevancy"])
|
| 389 |
+
except Exception as exc:
|
| 390 |
+
logger.warning("RAGAS answer_relevancy failed: %s", exc)
|
| 391 |
+
scores["answer_relevancy"] = None
|
| 392 |
+
|
| 393 |
+
# ββ MMR (Mean Reciprocal Rank) β custom implementation βββββββββββ
|
| 394 |
+
try:
|
| 395 |
+
mmr = _compute_mmr(query, retrieved_contexts, llm)
|
| 396 |
+
scores["mmr"] = round(mmr, 4)
|
| 397 |
+
logger.info("RAGAS mmr: %.4f", scores["mmr"])
|
| 398 |
+
except Exception as exc:
|
| 399 |
+
logger.warning("RAGAS mmr failed: %s", exc)
|
| 400 |
+
scores["mmr"] = None
|
| 401 |
+
|
| 402 |
+
# ββ Context Precision (reference-based, fallback when no answer) β
|
| 403 |
+
if "context_precision" not in scores and ground_truth:
|
| 404 |
+
try:
|
| 405 |
+
from ragas.metrics import ContextPrecision
|
| 406 |
+
|
| 407 |
+
scorer = ContextPrecision(llm=llm)
|
| 408 |
+
sample = SingleTurnSample(
|
| 409 |
+
user_input=query,
|
| 410 |
+
retrieved_contexts=retrieved_contexts,
|
| 411 |
+
reference=ground_truth,
|
| 412 |
+
)
|
| 413 |
+
result = scorer.single_turn_score(sample)
|
| 414 |
+
scores["context_precision"] = round(float(result), 4)
|
| 415 |
+
logger.info("RAGAS context_precision: %.4f", scores["context_precision"])
|
| 416 |
+
except Exception as exc:
|
| 417 |
+
logger.warning("RAGAS context_precision failed: %s", exc)
|
| 418 |
+
scores["context_precision"] = None
|
| 419 |
+
|
| 420 |
+
# Deterministic fallback: retrieval-only reviews may not have an answer or
|
| 421 |
+
# reference, and provider-backed judges can fail or rate-limit. Preserve a
|
| 422 |
+
# truthful numeric signal from lexical query/context coverage instead of
|
| 423 |
+
# returning an empty score map.
|
| 424 |
+
if not any(value is not None for value in scores.values()):
|
| 425 |
+
query_terms = {term.lower() for term in query.split() if len(term) >= 4}
|
| 426 |
+
overlaps = []
|
| 427 |
+
for context in retrieved_contexts:
|
| 428 |
+
context_terms = {term.lower() for term in context.split() if len(term) >= 4}
|
| 429 |
+
overlaps.append(len(query_terms & context_terms) / max(1, len(query_terms)))
|
| 430 |
+
coverage = round(sum(overlaps) / max(1, len(overlaps)), 4)
|
| 431 |
+
first_relevant = next((index for index, value in enumerate(overlaps, 1) if value > 0), None)
|
| 432 |
+
scores["context_precision"] = coverage
|
| 433 |
+
scores["mmr"] = round(1 / first_relevant, 4) if first_relevant else 0.0
|
| 434 |
+
logger.info("RAGAS deterministic fallback: context_precision=%.4f mmr=%.4f", scores["context_precision"], scores["mmr"])
|
| 435 |
+
return scores
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def _create_ragas_embeddings():
|
| 439 |
+
"""Return a lightweight embedding object compatible with RAGAS metrics.
|
| 440 |
+
|
| 441 |
+
Wraps the ChromaDB ONNX MiniLM embedding function so that metrics like
|
| 442 |
+
``ResponseRelevancy`` can compute cosine similarity between embeddings.
|
| 443 |
+
The underlying ONNX model is cached globally and loads in <1 s.
|
| 444 |
+
"""
|
| 445 |
+
if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
|
| 446 |
+
logger.info("Local RAGAS embeddings disabled; skipping answer relevancy")
|
| 447 |
+
return None
|
| 448 |
+
try:
|
| 449 |
+
from chromadb.utils import embedding_functions
|
| 450 |
+
|
| 451 |
+
if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
|
| 452 |
+
ef = embedding_functions.ONNXMiniLM_L6_V2()
|
| 453 |
+
else:
|
| 454 |
+
ef = embedding_functions.SentenceTransformerEmbeddingFunction(
|
| 455 |
+
model_name="all-MiniLM-L6-v2"
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
class _RagasEmbeddings:
|
| 459 |
+
def __init__(self, ef):
|
| 460 |
+
self._ef = ef
|
| 461 |
+
|
| 462 |
+
def embed_query(self, text: str) -> list[float]:
|
| 463 |
+
result = self._ef([text])[0]
|
| 464 |
+
return list(result) if not isinstance(result, list) else result
|
| 465 |
+
|
| 466 |
+
def embed_documents(self, texts: list[str]) -> list[list[float]]:
|
| 467 |
+
results = self._ef(texts)
|
| 468 |
+
return [list(r) if not isinstance(r, list) else r for r in results]
|
| 469 |
+
|
| 470 |
+
return _RagasEmbeddings(ef)
|
| 471 |
+
except Exception as exc:
|
| 472 |
+
logger.warning("Cannot create RAGAS embeddings: %s", exc)
|
| 473 |
+
return None
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def _compute_mmr(
|
| 477 |
+
query: str,
|
| 478 |
+
retrieved_contexts: list[str],
|
| 479 |
+
llm: Any,
|
| 480 |
+
) -> float:
|
| 481 |
+
"""Compute Mean Reciprocal Rank β how early the first relevant chunk appears.
|
| 482 |
+
|
| 483 |
+
Uses the LLM to judge each chunk's relevance to the query in order.
|
| 484 |
+
The first chunk judged relevant determines the reciprocal rank:
|
| 485 |
+
``1 / rank_of_first_relevant``. Returns 0.0 if none are relevant.
|
| 486 |
+
|
| 487 |
+
Parameters
|
| 488 |
+
----------
|
| 489 |
+
query : str
|
| 490 |
+
The search query (PR diff).
|
| 491 |
+
retrieved_contexts : list[str]
|
| 492 |
+
Ranked list of retrieved code chunks.
|
| 493 |
+
llm : LangchainLLMWrapper
|
| 494 |
+
RAGAS-wrapped LLM for relevance judgments.
|
| 495 |
+
|
| 496 |
+
Returns
|
| 497 |
+
-------
|
| 498 |
+
float
|
| 499 |
+
MMR score in [0, 1]; 0.0 when chunks were judged but none were
|
| 500 |
+
relevant.
|
| 501 |
+
|
| 502 |
+
Raises
|
| 503 |
+
------
|
| 504 |
+
RuntimeError
|
| 505 |
+
If every relevance judgment failed (e.g. LLM rate-limited) β
|
| 506 |
+
callers treat this as a failed metric rather than a fake 0.0.
|
| 507 |
+
"""
|
| 508 |
+
if not retrieved_contexts:
|
| 509 |
+
return 0.0
|
| 510 |
+
|
| 511 |
+
# Score up to the first 5 chunks for relevance using the LLM.
|
| 512 |
+
# Top-5 MMR is standard β rank 5 yields 1/5 = 0.20, and
|
| 513 |
+
# anything beyond rank 5 barely changes the score anyway.
|
| 514 |
+
MAX_MMR_RANK = 2
|
| 515 |
+
top_chunks = retrieved_contexts[:MAX_MMR_RANK]
|
| 516 |
+
|
| 517 |
+
judged = 0
|
| 518 |
+
for rank, chunk in enumerate(top_chunks, start=1):
|
| 519 |
+
try:
|
| 520 |
+
prompt = (
|
| 521 |
+
f"Is the following code/document chunk relevant to the question?\n\n"
|
| 522 |
+
f"Question: {query[:2_000]}\n\n"
|
| 523 |
+
f"Chunk: {chunk[:2_000]}\n\n"
|
| 524 |
+
f"Answer with exactly one word: YES or NO"
|
| 525 |
+
)
|
| 526 |
+
# Use the wrapped LangChain model for fast synchronous invoke.
|
| 527 |
+
# LangchainLLMWrapper stores the model as .langchain_llm in ragas
|
| 528 |
+
# 0.4.x and as .llm in 0.3.x β accept both.
|
| 529 |
+
langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
|
| 530 |
+
# Space the relevance judgments too β this unwrapped path bypasses
|
| 531 |
+
# the model wrapper on some ragas versions, so sleep explicitly
|
| 532 |
+
# (unless the wrapper is already in the path, to avoid double-sleep).
|
| 533 |
+
if not isinstance(langchain_model, _ThrottledChatModel):
|
| 534 |
+
time.sleep(_RAGAS_INTERVAL)
|
| 535 |
+
raw = langchain_model.invoke(prompt)
|
| 536 |
+
response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
|
| 537 |
+
if response_text.startswith("Y"):
|
| 538 |
+
return 1.0 / rank
|
| 539 |
+
judged += 1 # judge responded β chunk deemed not relevant
|
| 540 |
+
except Exception:
|
| 541 |
+
continue
|
| 542 |
+
|
| 543 |
+
if judged == 0:
|
| 544 |
+
# Every relevance judgment failed (e.g. LLM rate-limited) β surface
|
| 545 |
+
# this as a failed metric instead of a misleading 0.0.
|
| 546 |
+
raise RuntimeError("all MMR relevance judgments failed")
|
| 547 |
+
|
| 548 |
+
return 0.0
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def log_ragas_scores_to_langfuse(
|
| 552 |
+
scores: dict[str, float | None],
|
| 553 |
+
repo: str = "",
|
| 554 |
+
pr_number: int = 0,
|
| 555 |
+
handler: Any = None,
|
| 556 |
+
) -> None:
|
| 557 |
+
"""Log RAGAS metrics as Langfuse scores (linked to the review trace).
|
| 558 |
+
|
| 559 |
+
Parameters
|
| 560 |
+
----------
|
| 561 |
+
scores : dict
|
| 562 |
+
Output of :func:`compute_ragas_retrieval_scores`.
|
| 563 |
+
repo : str
|
| 564 |
+
GitHub repository name (e.g. ``\"psf/requests\"``).
|
| 565 |
+
pr_number : int
|
| 566 |
+
Pull request number.
|
| 567 |
+
handler : Langfuse CallbackHandler or None
|
| 568 |
+
Handler from the current review run, used to link scores to the trace.
|
| 569 |
+
"""
|
| 570 |
+
try:
|
| 571 |
+
from observability import log_langfuse_score
|
| 572 |
+
except ImportError:
|
| 573 |
+
logger.debug("observability module not available β skipping Langfuse")
|
| 574 |
+
return
|
| 575 |
+
|
| 576 |
+
for metric_name, value in scores.items():
|
| 577 |
+
if value is None:
|
| 578 |
+
continue
|
| 579 |
+
log_langfuse_score(
|
| 580 |
+
name=f"ragas_{metric_name}",
|
| 581 |
+
value=value,
|
| 582 |
+
comment=f"{repo}#{pr_number} β {metric_name}",
|
| 583 |
+
handler=handler,
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
# βββ Standalone CLI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def main() -> None:
|
| 591 |
+
"""CLI entry point: compute RAGAS scores from a JSONL dataset.
|
| 592 |
+
|
| 593 |
+
Usage::
|
| 594 |
+
|
| 595 |
+
python eval_data/ragas_eval.py --data eval_data/prs.jsonl
|
| 596 |
+
"""
|
| 597 |
+
import argparse
|
| 598 |
+
import json
|
| 599 |
+
|
| 600 |
+
parser = argparse.ArgumentParser(
|
| 601 |
+
description="Compute RAGAS retrieval quality scores on evaluation data",
|
| 602 |
+
)
|
| 603 |
+
parser.add_argument(
|
| 604 |
+
"--data", default=None,
|
| 605 |
+
help="Path to JSONL dataset (same format as evaluate.py)",
|
| 606 |
+
)
|
| 607 |
+
parser.add_argument(
|
| 608 |
+
"--output", default=None,
|
| 609 |
+
help="Path to write per-PR RAGAS scores (JSON)",
|
| 610 |
+
)
|
| 611 |
+
parser.add_argument(
|
| 612 |
+
"--max-prs", type=int, default=None,
|
| 613 |
+
help="Max PRs to process",
|
| 614 |
+
)
|
| 615 |
+
parser.add_argument(
|
| 616 |
+
"--log-to-observability", action="store_true",
|
| 617 |
+
help="Log RAGAS scores to Langfuse",
|
| 618 |
+
)
|
| 619 |
+
args = parser.parse_args()
|
| 620 |
+
|
| 621 |
+
logging.basicConfig(
|
| 622 |
+
level=logging.INFO,
|
| 623 |
+
format="%(asctime)s [%(levelname)s] %(name)s β %(message)s",
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
if not args.data:
|
| 627 |
+
# If no data file specified, try default location
|
| 628 |
+
default_path = os.path.join(
|
| 629 |
+
os.path.dirname(__file__), "prs.jsonl"
|
| 630 |
+
)
|
| 631 |
+
if os.path.exists(default_path):
|
| 632 |
+
args.data = default_path
|
| 633 |
+
else:
|
| 634 |
+
logger.error(
|
| 635 |
+
"No --data provided and default not found at %s. "
|
| 636 |
+
"Run eval_data/fetcher.py first.",
|
| 637 |
+
default_path,
|
| 638 |
+
)
|
| 639 |
+
return
|
| 640 |
+
|
| 641 |
+
with open(args.data, "r", encoding="utf-8") as f:
|
| 642 |
+
entries = [json.loads(line) for line in f if line.strip()]
|
| 643 |
+
|
| 644 |
+
if args.max_prs:
|
| 645 |
+
entries = entries[: args.max_prs]
|
| 646 |
+
|
| 647 |
+
all_scores: list[dict] = []
|
| 648 |
+
for entry in entries:
|
| 649 |
+
repo = entry.get("repo", "?")
|
| 650 |
+
pr = entry.get("pr_number", 0)
|
| 651 |
+
diff = entry.get("diff", "")
|
| 652 |
+
ground_truth_list = entry.get("ground_truth", [])
|
| 653 |
+
|
| 654 |
+
# Use the diff as the query, and first few human comments
|
| 655 |
+
# as a proxy for "what the retrieval should have found"
|
| 656 |
+
query = diff[:8_000] if diff else entry.get("title", "")
|
| 657 |
+
gt_text = (
|
| 658 |
+
" ".join(
|
| 659 |
+
g.get("comment", "")
|
| 660 |
+
for g in ground_truth_list[:5]
|
| 661 |
+
)
|
| 662 |
+
if ground_truth_list
|
| 663 |
+
else None
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
# Retrieved contexts come from the graph run, but for the CLI
|
| 667 |
+
# we don't re-run the graph β we just skip if no retrieval data
|
| 668 |
+
# is available in the entry.
|
| 669 |
+
stored_contexts = entry.get("retrieved_contexts", [])
|
| 670 |
+
if not stored_contexts:
|
| 671 |
+
logger.info(
|
| 672 |
+
"[%s#%d] No stored retrieval contexts β skipping RAGAS",
|
| 673 |
+
repo, pr,
|
| 674 |
+
)
|
| 675 |
+
continue
|
| 676 |
+
|
| 677 |
+
logger.info("[%s#%d] Computing RAGAS scores β¦", repo, pr)
|
| 678 |
+
try:
|
| 679 |
+
scores = compute_ragas_retrieval_scores(
|
| 680 |
+
query=query,
|
| 681 |
+
retrieved_contexts=stored_contexts,
|
| 682 |
+
ground_truth=gt_text,
|
| 683 |
+
)
|
| 684 |
+
except RuntimeError as exc:
|
| 685 |
+
logger.warning("[%s#%d] %s", repo, pr, exc)
|
| 686 |
+
break
|
| 687 |
+
|
| 688 |
+
scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
|
| 689 |
+
all_scores.append(scores)
|
| 690 |
+
|
| 691 |
+
if args.log_to_observability:
|
| 692 |
+
log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)
|
| 693 |
+
|
| 694 |
+
print(
|
| 695 |
+
f" {repo}#{pr}: "
|
| 696 |
+
+ " | ".join(
|
| 697 |
+
f"{k}={v:.3f}" for k, v in scores.items()
|
| 698 |
+
if k not in ("repo", "pr_number", "id") and v is not None
|
| 699 |
+
)
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
# Print aggregate
|
| 703 |
+
if all_scores:
|
| 704 |
+
print()
|
| 705 |
+
print("=" * 60)
|
| 706 |
+
print(" Aggregate RAGAS scores")
|
| 707 |
+
print("=" * 60)
|
| 708 |
+
metrics = [
|
| 709 |
+
k for k in all_scores[0].keys()
|
| 710 |
+
if k not in ("repo", "pr_number", "id")
|
| 711 |
+
]
|
| 712 |
+
for metric in metrics:
|
| 713 |
+
values = [
|
| 714 |
+
s.get(metric) for s in all_scores
|
| 715 |
+
if s.get(metric) is not None
|
| 716 |
+
]
|
| 717 |
+
if not values:
|
| 718 |
+
print(f" {metric:30s}: n/a (no successful scores)")
|
| 719 |
+
continue
|
| 720 |
+
avg = sum(values) / len(values)
|
| 721 |
+
print(f" {metric:30s}: {avg:.4f} (over {len(values)} PRs)")
|
| 722 |
+
print()
|
| 723 |
+
|
| 724 |
+
# Save output
|
| 725 |
+
if args.output and all_scores:
|
| 726 |
+
with open(args.output, "w", encoding="utf-8") as f:
|
| 727 |
+
json.dump(all_scores, f, indent=2)
|
| 728 |
+
logger.info("Saved RAGAS scores to %s", args.output)
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
if __name__ == "__main__":
|
| 732 |
+
main()
|
frontend/src/main.jsx
CHANGED
|
@@ -39,8 +39,8 @@ function ReviewProgress({ job }) {
|
|
| 39 |
return <section className="review-progress" aria-label="Review progress" aria-live="polite">
|
| 40 |
{job.status === "incomplete" && <p className="message error">Review incomplete. Failed reviewers do not mean the code is free of issues.</p>}
|
| 41 |
<div className="metrics">{job.elapsed_seconds != null && <span>Elapsed: {Math.round(job.elapsed_seconds)}s</span>}{job.review_mode && <span>{pretty(job.review_mode)} review</span>}{job.progress?.completed_stages?.length > 0 && <span>{job.progress.completed_stages.length} stages finished</span>}</div>
|
| 42 |
-
{stages.length > 0 && <ul className="reviewer-stages">{stages.map((stage, index) => <li key={`${stage.reviewer}-${index}`}><strong>{pretty(stage.reviewer)}</strong><span>{pretty(stage.status)}{stage.duration_seconds != null ? ` Β· ${stage.duration_seconds.toFixed(1)}s` : ""}</span>{stage.model && <small>{stage.model}</small>}{stage.error && <small className="reviewer-error">{stage.error}</small>}</li>)}</ul>}
|
| 43 |
-
{Object.keys(timings).length > 0 && <details><summary>Stage
|
| 44 |
</section>;
|
| 45 |
}
|
| 46 |
|
|
|
|
| 39 |
return <section className="review-progress" aria-label="Review progress" aria-live="polite">
|
| 40 |
{job.status === "incomplete" && <p className="message error">Review incomplete. Failed reviewers do not mean the code is free of issues.</p>}
|
| 41 |
<div className="metrics">{job.elapsed_seconds != null && <span>Elapsed: {Math.round(job.elapsed_seconds)}s</span>}{job.review_mode && <span>{pretty(job.review_mode)} review</span>}{job.progress?.completed_stages?.length > 0 && <span>{job.progress.completed_stages.length} stages finished</span>}</div>
|
| 42 |
+
{stages.length > 0 && <ul className="reviewer-stages">{stages.map((stage, index) => <li key={`${stage.reviewer}-${index}`}><strong>{pretty(stage.reviewer)}</strong><span>{pretty(stage.status)}{stage.duration_seconds != null ? ` Β· ${stage.duration_seconds.toFixed(1)}s` : ""}</span>{stage.model && <small>{stage.model}</small>}{stage.reason && <small>{stage.reason}</small>}{stage.error && <small className="reviewer-error">{stage.error}</small>}</li>)}</ul>}
|
| 43 |
+
{Object.keys(timings).length > 0 && <details><summary>Stage completion times (since review start)</summary><ul>{Object.entries(timings).map(([name, seconds]) => <li key={name}>{pretty(name)}: {Number(seconds).toFixed(1)}s</li>)}</ul></details>}
|
| 44 |
</section>;
|
| 45 |
}
|
| 46 |
|
llm_factory.py
CHANGED
|
@@ -1,261 +1,261 @@
|
|
| 1 |
-
"""LLM factory β creates LangChain chat models with primary + fallback support.
|
| 2 |
-
|
| 3 |
-
Priority
|
| 4 |
-
--------
|
| 5 |
-
1. **Google Gemini** (primary) β uses ``GEMINI_API_KEY`` env var.
|
| 6 |
-
Model: ``gemini-3.1-flash-lite`` β generous free tier.
|
| 7 |
-
2. **Groq** (fallback) β uses ``GROQ_API_KEY`` env var.
|
| 8 |
-
Model: ``llama-3.3-70b-versatile`` β fast inference, lower free limit.
|
| 9 |
-
|
| 10 |
-
If neither key is set, functions raise ``ValueError`` so callers can skip
|
| 11 |
-
gracefully (as they already do for Groq-only today).
|
| 12 |
-
"""
|
| 13 |
-
|
| 14 |
-
from __future__ import annotations
|
| 15 |
-
|
| 16 |
-
import logging
|
| 17 |
-
import os
|
| 18 |
-
from typing import Any, Optional
|
| 19 |
-
|
| 20 |
-
logger = logging.getLogger(__name__)
|
| 21 |
-
|
| 22 |
-
# Gemini 3.1 Flash model name as of 2026-07
|
| 23 |
-
# Verified via Google AI documentation: gemini-3.1-flash-lite is the correct name.
|
| 24 |
-
# The base 'gemini-3.1-flash' does not exist in the API.
|
| 25 |
-
GEMINI_MODEL = "gemini-3.1-flash-lite"
|
| 26 |
-
GROQ_MODEL = os.getenv("GROQ_MODEL", "openai/gpt-oss-20b")
|
| 27 |
-
DEFAULT_TEMPERATURE = 0.0
|
| 28 |
-
DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
|
| 29 |
-
DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
def _get_gemini_chat(**kwargs: Any) -> Optional[Any]:
|
| 33 |
-
"""Create a ``ChatGoogleGenerativeAI`` instance if ``GEMINI_API_KEY`` is set.
|
| 34 |
-
|
| 35 |
-
Returns ``None`` silently when the key is missing or the package is not
|
| 36 |
-
installed β callers are expected to fall back.
|
| 37 |
-
"""
|
| 38 |
-
kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
|
| 39 |
-
kwargs.setdefault("max_retries", 0)
|
| 40 |
-
kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
|
| 41 |
-
api_key = os.environ.get("GEMINI_API_KEY", "").strip()
|
| 42 |
-
if not api_key:
|
| 43 |
-
return None
|
| 44 |
-
|
| 45 |
-
try:
|
| 46 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 47 |
-
|
| 48 |
-
return ChatGoogleGenerativeAI(
|
| 49 |
-
model=kwargs.pop("model", GEMINI_MODEL),
|
| 50 |
-
temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
|
| 51 |
-
google_api_key=api_key,
|
| 52 |
-
**kwargs,
|
| 53 |
-
)
|
| 54 |
-
except ImportError:
|
| 55 |
-
logger.warning("langchain-google-genai not installed β skipping Gemini")
|
| 56 |
-
return None
|
| 57 |
-
except Exception as exc:
|
| 58 |
-
logger.warning("Failed to initialise Gemini: %s", exc)
|
| 59 |
-
return None
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def _get_groq_chat(**kwargs: Any) -> Optional[Any]:
|
| 63 |
-
"""Create a ``ChatGroq`` instance if ``GROQ_API_KEY`` is set."""
|
| 64 |
-
kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
|
| 65 |
-
kwargs.setdefault("max_retries", 0)
|
| 66 |
-
kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
|
| 67 |
-
api_key = os.environ.get("GROQ_API_KEY", "").strip()
|
| 68 |
-
if not api_key:
|
| 69 |
-
return None
|
| 70 |
-
|
| 71 |
-
try:
|
| 72 |
-
from langchain_groq import ChatGroq
|
| 73 |
-
|
| 74 |
-
return ChatGroq(
|
| 75 |
-
model=kwargs.pop("model", GROQ_MODEL),
|
| 76 |
-
temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
|
| 77 |
-
api_key=api_key,
|
| 78 |
-
**kwargs,
|
| 79 |
-
)
|
| 80 |
-
except ImportError:
|
| 81 |
-
logger.warning("langchain-groq not installed")
|
| 82 |
-
return None
|
| 83 |
-
except Exception as exc:
|
| 84 |
-
logger.warning("Failed to initialise Groq: %s", exc)
|
| 85 |
-
return None
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
def create_endpoint_llm(endpoint, **kwargs: Any) -> Any:
|
| 89 |
-
"""Create a chat model from a user-configured custom endpoint.
|
| 90 |
-
|
| 91 |
-
Supports OpenAI-compatible APIs (DeepSeek, OpenRouter, vLLM, Ollama,
|
| 92 |
-
Groq, Together, ...), Anthropic Claude, and Google Gemini.
|
| 93 |
-
|
| 94 |
-
Parameters
|
| 95 |
-
----------
|
| 96 |
-
endpoint : EndpointConfig
|
| 97 |
-
The user's endpoint config (name, provider, api_key, base_url, model).
|
| 98 |
-
**kwargs
|
| 99 |
-
Passed through to the underlying LangChain constructor (e.g.
|
| 100 |
-
``temperature``). ``model`` / ``api_key`` / ``base_url`` come from
|
| 101 |
-
the endpoint and cannot be overridden here.
|
| 102 |
-
|
| 103 |
-
Returns
|
| 104 |
-
-------
|
| 105 |
-
Any
|
| 106 |
-
A LangChain chat model instance (``ChatOpenAI``, ``ChatAnthropic``
|
| 107 |
-
or ``ChatGoogleGenerativeAI``).
|
| 108 |
-
|
| 109 |
-
Raises
|
| 110 |
-
------
|
| 111 |
-
ValueError
|
| 112 |
-
If the endpoint's provider package is not installed or the config
|
| 113 |
-
is incomplete.
|
| 114 |
-
"""
|
| 115 |
-
if not endpoint.api_key or not endpoint.model:
|
| 116 |
-
raise ValueError(
|
| 117 |
-
f"Endpoint '{endpoint.name}' is missing an API key or model name."
|
| 118 |
-
)
|
| 119 |
-
|
| 120 |
-
kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
|
| 121 |
-
kwargs.setdefault("max_retries", 0)
|
| 122 |
-
kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
|
| 123 |
-
provider = endpoint.provider
|
| 124 |
-
model = endpoint.model
|
| 125 |
-
temperature = kwargs.pop("temperature", DEFAULT_TEMPERATURE)
|
| 126 |
-
|
| 127 |
-
if provider == "anthropic":
|
| 128 |
-
try:
|
| 129 |
-
from langchain_anthropic import ChatAnthropic
|
| 130 |
-
except ImportError:
|
| 131 |
-
raise ValueError(
|
| 132 |
-
"langchain-anthropic is not installed β cannot use endpoint "
|
| 133 |
-
f"'{endpoint.name}'. Run: pip install langchain-anthropic"
|
| 134 |
-
) from None
|
| 135 |
-
params: dict[str, Any] = {
|
| 136 |
-
"model": model,
|
| 137 |
-
"api_key": endpoint.api_key,
|
| 138 |
-
"temperature": temperature,
|
| 139 |
-
}
|
| 140 |
-
if endpoint.base_url:
|
| 141 |
-
params["base_url"] = endpoint.base_url
|
| 142 |
-
params.update(kwargs)
|
| 143 |
-
return ChatAnthropic(**params)
|
| 144 |
-
|
| 145 |
-
if provider == "google":
|
| 146 |
-
try:
|
| 147 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 148 |
-
except ImportError:
|
| 149 |
-
raise ValueError(
|
| 150 |
-
"langchain-google-genai is not installed β cannot use endpoint "
|
| 151 |
-
f"'{endpoint.name}'. Run: pip install langchain-google-genai"
|
| 152 |
-
) from None
|
| 153 |
-
params = {
|
| 154 |
-
"model": model,
|
| 155 |
-
"google_api_key": endpoint.api_key,
|
| 156 |
-
"temperature": temperature,
|
| 157 |
-
}
|
| 158 |
-
params.update(kwargs)
|
| 159 |
-
return ChatGoogleGenerativeAI(**params)
|
| 160 |
-
|
| 161 |
-
# Default: OpenAI-compatible
|
| 162 |
-
try:
|
| 163 |
-
from langchain_openai import ChatOpenAI
|
| 164 |
-
except ImportError:
|
| 165 |
-
raise ValueError(
|
| 166 |
-
"langchain-openai is not installed β cannot use endpoint "
|
| 167 |
-
f"'{endpoint.name}'. Run: pip install langchain-openai"
|
| 168 |
-
) from None
|
| 169 |
-
params = {
|
| 170 |
-
"model": model,
|
| 171 |
-
"api_key": endpoint.api_key,
|
| 172 |
-
"temperature": temperature,
|
| 173 |
-
}
|
| 174 |
-
if endpoint.base_url:
|
| 175 |
-
params["base_url"] = endpoint.base_url
|
| 176 |
-
params.update(kwargs)
|
| 177 |
-
return ChatOpenAI(**params)
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
def create_llm(endpoint=None, **kwargs: Any) -> Any:
|
| 181 |
-
"""Create a chat LLM β custom endpoint first, else Gemini β Groq.
|
| 182 |
-
|
| 183 |
-
Parameters
|
| 184 |
-
----------
|
| 185 |
-
endpoint : EndpointConfig or str or None
|
| 186 |
-
A custom endpoint to run on (``EndpointConfig`` object or its name).
|
| 187 |
-
``None`` (default) falls back to the built-in providers.
|
| 188 |
-
**kwargs
|
| 189 |
-
Passed through to the underlying LangChain constructor.
|
| 190 |
-
Common overrides: ``model``, ``temperature``.
|
| 191 |
-
|
| 192 |
-
Returns
|
| 193 |
-
-------
|
| 194 |
-
Any
|
| 195 |
-
A LangChain chat model instance (``ChatOpenAI``/``ChatAnthropic``/
|
| 196 |
-
``ChatGoogleGenerativeAI`` from a custom endpoint, or the built-in
|
| 197 |
-
``ChatGoogleGenerativeAI`` / ``ChatGroq``).
|
| 198 |
-
|
| 199 |
-
Raises
|
| 200 |
-
------
|
| 201 |
-
ValueError
|
| 202 |
-
If a custom endpoint is named but not found, or no provider key is set.
|
| 203 |
-
"""
|
| 204 |
-
if endpoint:
|
| 205 |
-
from endpoints import EndpointConfig, get_endpoint
|
| 206 |
-
|
| 207 |
-
ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
|
| 208 |
-
if ep is not None:
|
| 209 |
-
if getattr(ep, "builtin", False):
|
| 210 |
-
# Built-in providers use their native constructors so the
|
| 211 |
-
# behaviour is identical to the default (no-endpoint) path.
|
| 212 |
-
if ep.name == "Gemini":
|
| 213 |
-
llm = _get_gemini_chat(**kwargs)
|
| 214 |
-
if llm is not None:
|
| 215 |
-
logger.info(
|
| 216 |
-
"Using built-in Gemini endpoint (model=%s)",
|
| 217 |
-
kwargs.get("model", GEMINI_MODEL),
|
| 218 |
-
)
|
| 219 |
-
return llm
|
| 220 |
-
raise ValueError(
|
| 221 |
-
"Gemini selected but GEMINI_API_KEY is not set."
|
| 222 |
-
)
|
| 223 |
-
if ep.name == "Grok":
|
| 224 |
-
llm = _get_groq_chat(**kwargs)
|
| 225 |
-
if llm is not None:
|
| 226 |
-
logger.info(
|
| 227 |
-
"Using built-in Grok endpoint (model=%s)",
|
| 228 |
-
kwargs.get("model", GROQ_MODEL),
|
| 229 |
-
)
|
| 230 |
-
return llm
|
| 231 |
-
raise ValueError(
|
| 232 |
-
"Grok selected but GROQ_API_KEY is not set."
|
| 233 |
-
)
|
| 234 |
-
try:
|
| 235 |
-
llm = create_endpoint_llm(ep, **kwargs)
|
| 236 |
-
logger.info("Using custom endpoint %s (%s/%s)", ep.name, ep.provider, ep.model)
|
| 237 |
-
return llm
|
| 238 |
-
except ValueError:
|
| 239 |
-
raise
|
| 240 |
-
else:
|
| 241 |
-
raise ValueError(
|
| 242 |
-
f"Custom endpoint '{endpoint}' not found. "
|
| 243 |
-
"Configure it via OCR_ENDPOINT_* environment variables "
|
| 244 |
-
"or add it in the UI."
|
| 245 |
-
)
|
| 246 |
-
|
| 247 |
-
# Prefer Groq when configured: it has a separate quota pool and avoids
|
| 248 |
-
# stalling the review pipeline on Gemini free-tier exhaustion.
|
| 249 |
-
llm = _get_groq_chat(**kwargs)
|
| 250 |
-
if llm is not None:
|
| 251 |
-
logger.debug("Using Groq (model=%s)", kwargs.get("model", GROQ_MODEL))
|
| 252 |
-
return llm
|
| 253 |
-
|
| 254 |
-
llm = _get_gemini_chat(**kwargs)
|
| 255 |
-
if llm is not None:
|
| 256 |
-
logger.debug("Falling back to Gemini (model=%s)", kwargs.get("model", GEMINI_MODEL))
|
| 257 |
-
return llm
|
| 258 |
-
|
| 259 |
-
raise ValueError(
|
| 260 |
-
"No LLM available. Set GEMINI_API_KEY (primary) or GROQ_API_KEY (fallback)."
|
| 261 |
-
)
|
|
|
|
| 1 |
+
"""LLM factory β creates LangChain chat models with primary + fallback support.
|
| 2 |
+
|
| 3 |
+
Priority
|
| 4 |
+
--------
|
| 5 |
+
1. **Google Gemini** (primary) β uses ``GEMINI_API_KEY`` env var.
|
| 6 |
+
Model: ``gemini-3.1-flash-lite`` β generous free tier.
|
| 7 |
+
2. **Groq** (fallback) β uses ``GROQ_API_KEY`` env var.
|
| 8 |
+
Model: ``llama-3.3-70b-versatile`` β fast inference, lower free limit.
|
| 9 |
+
|
| 10 |
+
If neither key is set, functions raise ``ValueError`` so callers can skip
|
| 11 |
+
gracefully (as they already do for Groq-only today).
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import logging
|
| 17 |
+
import os
|
| 18 |
+
from typing import Any, Optional
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
# Gemini 3.1 Flash model name as of 2026-07
|
| 23 |
+
# Verified via Google AI documentation: gemini-3.1-flash-lite is the correct name.
|
| 24 |
+
# The base 'gemini-3.1-flash' does not exist in the API.
|
| 25 |
+
GEMINI_MODEL = "gemini-3.1-flash-lite"
|
| 26 |
+
GROQ_MODEL = os.getenv("GROQ_MODEL", "openai/gpt-oss-20b")
|
| 27 |
+
DEFAULT_TEMPERATURE = 0.0
|
| 28 |
+
DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
|
| 29 |
+
DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _get_gemini_chat(**kwargs: Any) -> Optional[Any]:
|
| 33 |
+
"""Create a ``ChatGoogleGenerativeAI`` instance if ``GEMINI_API_KEY`` is set.
|
| 34 |
+
|
| 35 |
+
Returns ``None`` silently when the key is missing or the package is not
|
| 36 |
+
installed β callers are expected to fall back.
|
| 37 |
+
"""
|
| 38 |
+
kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
|
| 39 |
+
kwargs.setdefault("max_retries", 0)
|
| 40 |
+
kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
|
| 41 |
+
api_key = os.environ.get("GEMINI_API_KEY", "").strip()
|
| 42 |
+
if not api_key:
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 47 |
+
|
| 48 |
+
return ChatGoogleGenerativeAI(
|
| 49 |
+
model=kwargs.pop("model", GEMINI_MODEL),
|
| 50 |
+
temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
|
| 51 |
+
google_api_key=api_key,
|
| 52 |
+
**kwargs,
|
| 53 |
+
)
|
| 54 |
+
except ImportError:
|
| 55 |
+
logger.warning("langchain-google-genai not installed β skipping Gemini")
|
| 56 |
+
return None
|
| 57 |
+
except Exception as exc:
|
| 58 |
+
logger.warning("Failed to initialise Gemini: %s", exc)
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _get_groq_chat(**kwargs: Any) -> Optional[Any]:
|
| 63 |
+
"""Create a ``ChatGroq`` instance if ``GROQ_API_KEY`` is set."""
|
| 64 |
+
kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
|
| 65 |
+
kwargs.setdefault("max_retries", 0)
|
| 66 |
+
kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
|
| 67 |
+
api_key = os.environ.get("GROQ_API_KEY", "").strip()
|
| 68 |
+
if not api_key:
|
| 69 |
+
return None
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
from langchain_groq import ChatGroq
|
| 73 |
+
|
| 74 |
+
return ChatGroq(
|
| 75 |
+
model=kwargs.pop("model", GROQ_MODEL),
|
| 76 |
+
temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
|
| 77 |
+
api_key=api_key,
|
| 78 |
+
**kwargs,
|
| 79 |
+
)
|
| 80 |
+
except ImportError:
|
| 81 |
+
logger.warning("langchain-groq not installed")
|
| 82 |
+
return None
|
| 83 |
+
except Exception as exc:
|
| 84 |
+
logger.warning("Failed to initialise Groq: %s", exc)
|
| 85 |
+
return None
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def create_endpoint_llm(endpoint, **kwargs: Any) -> Any:
|
| 89 |
+
"""Create a chat model from a user-configured custom endpoint.
|
| 90 |
+
|
| 91 |
+
Supports OpenAI-compatible APIs (DeepSeek, OpenRouter, vLLM, Ollama,
|
| 92 |
+
Groq, Together, ...), Anthropic Claude, and Google Gemini.
|
| 93 |
+
|
| 94 |
+
Parameters
|
| 95 |
+
----------
|
| 96 |
+
endpoint : EndpointConfig
|
| 97 |
+
The user's endpoint config (name, provider, api_key, base_url, model).
|
| 98 |
+
**kwargs
|
| 99 |
+
Passed through to the underlying LangChain constructor (e.g.
|
| 100 |
+
``temperature``). ``model`` / ``api_key`` / ``base_url`` come from
|
| 101 |
+
the endpoint and cannot be overridden here.
|
| 102 |
+
|
| 103 |
+
Returns
|
| 104 |
+
-------
|
| 105 |
+
Any
|
| 106 |
+
A LangChain chat model instance (``ChatOpenAI``, ``ChatAnthropic``
|
| 107 |
+
or ``ChatGoogleGenerativeAI``).
|
| 108 |
+
|
| 109 |
+
Raises
|
| 110 |
+
------
|
| 111 |
+
ValueError
|
| 112 |
+
If the endpoint's provider package is not installed or the config
|
| 113 |
+
is incomplete.
|
| 114 |
+
"""
|
| 115 |
+
if not endpoint.api_key or not endpoint.model:
|
| 116 |
+
raise ValueError(
|
| 117 |
+
f"Endpoint '{endpoint.name}' is missing an API key or model name."
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
|
| 121 |
+
kwargs.setdefault("max_retries", 0)
|
| 122 |
+
kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
|
| 123 |
+
provider = endpoint.provider
|
| 124 |
+
model = endpoint.model
|
| 125 |
+
temperature = kwargs.pop("temperature", DEFAULT_TEMPERATURE)
|
| 126 |
+
|
| 127 |
+
if provider == "anthropic":
|
| 128 |
+
try:
|
| 129 |
+
from langchain_anthropic import ChatAnthropic
|
| 130 |
+
except ImportError:
|
| 131 |
+
raise ValueError(
|
| 132 |
+
"langchain-anthropic is not installed β cannot use endpoint "
|
| 133 |
+
f"'{endpoint.name}'. Run: pip install langchain-anthropic"
|
| 134 |
+
) from None
|
| 135 |
+
params: dict[str, Any] = {
|
| 136 |
+
"model": model,
|
| 137 |
+
"api_key": endpoint.api_key,
|
| 138 |
+
"temperature": temperature,
|
| 139 |
+
}
|
| 140 |
+
if endpoint.base_url:
|
| 141 |
+
params["base_url"] = endpoint.base_url
|
| 142 |
+
params.update(kwargs)
|
| 143 |
+
return ChatAnthropic(**params)
|
| 144 |
+
|
| 145 |
+
if provider == "google":
|
| 146 |
+
try:
|
| 147 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 148 |
+
except ImportError:
|
| 149 |
+
raise ValueError(
|
| 150 |
+
"langchain-google-genai is not installed β cannot use endpoint "
|
| 151 |
+
f"'{endpoint.name}'. Run: pip install langchain-google-genai"
|
| 152 |
+
) from None
|
| 153 |
+
params = {
|
| 154 |
+
"model": model,
|
| 155 |
+
"google_api_key": endpoint.api_key,
|
| 156 |
+
"temperature": temperature,
|
| 157 |
+
}
|
| 158 |
+
params.update(kwargs)
|
| 159 |
+
return ChatGoogleGenerativeAI(**params)
|
| 160 |
+
|
| 161 |
+
# Default: OpenAI-compatible
|
| 162 |
+
try:
|
| 163 |
+
from langchain_openai import ChatOpenAI
|
| 164 |
+
except ImportError:
|
| 165 |
+
raise ValueError(
|
| 166 |
+
"langchain-openai is not installed β cannot use endpoint "
|
| 167 |
+
f"'{endpoint.name}'. Run: pip install langchain-openai"
|
| 168 |
+
) from None
|
| 169 |
+
params = {
|
| 170 |
+
"model": model,
|
| 171 |
+
"api_key": endpoint.api_key,
|
| 172 |
+
"temperature": temperature,
|
| 173 |
+
}
|
| 174 |
+
if endpoint.base_url:
|
| 175 |
+
params["base_url"] = endpoint.base_url
|
| 176 |
+
params.update(kwargs)
|
| 177 |
+
return ChatOpenAI(**params)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def create_llm(endpoint=None, **kwargs: Any) -> Any:
|
| 181 |
+
"""Create a chat LLM β custom endpoint first, else Gemini β Groq.
|
| 182 |
+
|
| 183 |
+
Parameters
|
| 184 |
+
----------
|
| 185 |
+
endpoint : EndpointConfig or str or None
|
| 186 |
+
A custom endpoint to run on (``EndpointConfig`` object or its name).
|
| 187 |
+
``None`` (default) falls back to the built-in providers.
|
| 188 |
+
**kwargs
|
| 189 |
+
Passed through to the underlying LangChain constructor.
|
| 190 |
+
Common overrides: ``model``, ``temperature``.
|
| 191 |
+
|
| 192 |
+
Returns
|
| 193 |
+
-------
|
| 194 |
+
Any
|
| 195 |
+
A LangChain chat model instance (``ChatOpenAI``/``ChatAnthropic``/
|
| 196 |
+
``ChatGoogleGenerativeAI`` from a custom endpoint, or the built-in
|
| 197 |
+
``ChatGoogleGenerativeAI`` / ``ChatGroq``).
|
| 198 |
+
|
| 199 |
+
Raises
|
| 200 |
+
------
|
| 201 |
+
ValueError
|
| 202 |
+
If a custom endpoint is named but not found, or no provider key is set.
|
| 203 |
+
"""
|
| 204 |
+
if endpoint:
|
| 205 |
+
from endpoints import EndpointConfig, get_endpoint
|
| 206 |
+
|
| 207 |
+
ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
|
| 208 |
+
if ep is not None:
|
| 209 |
+
if getattr(ep, "builtin", False):
|
| 210 |
+
# Built-in providers use their native constructors so the
|
| 211 |
+
# behaviour is identical to the default (no-endpoint) path.
|
| 212 |
+
if ep.name == "Gemini":
|
| 213 |
+
llm = _get_gemini_chat(**kwargs)
|
| 214 |
+
if llm is not None:
|
| 215 |
+
logger.info(
|
| 216 |
+
"Using built-in Gemini endpoint (model=%s)",
|
| 217 |
+
kwargs.get("model", GEMINI_MODEL),
|
| 218 |
+
)
|
| 219 |
+
return llm
|
| 220 |
+
raise ValueError(
|
| 221 |
+
"Gemini selected but GEMINI_API_KEY is not set."
|
| 222 |
+
)
|
| 223 |
+
if ep.name == "Grok":
|
| 224 |
+
llm = _get_groq_chat(**kwargs)
|
| 225 |
+
if llm is not None:
|
| 226 |
+
logger.info(
|
| 227 |
+
"Using built-in Grok endpoint (model=%s)",
|
| 228 |
+
kwargs.get("model", GROQ_MODEL),
|
| 229 |
+
)
|
| 230 |
+
return llm
|
| 231 |
+
raise ValueError(
|
| 232 |
+
"Grok selected but GROQ_API_KEY is not set."
|
| 233 |
+
)
|
| 234 |
+
try:
|
| 235 |
+
llm = create_endpoint_llm(ep, **kwargs)
|
| 236 |
+
logger.info("Using custom endpoint %s (%s/%s)", ep.name, ep.provider, ep.model)
|
| 237 |
+
return llm
|
| 238 |
+
except ValueError:
|
| 239 |
+
raise
|
| 240 |
+
else:
|
| 241 |
+
raise ValueError(
|
| 242 |
+
f"Custom endpoint '{endpoint}' not found. "
|
| 243 |
+
"Configure it via OCR_ENDPOINT_* environment variables "
|
| 244 |
+
"or add it in the UI."
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# Prefer Groq when configured: it has a separate quota pool and avoids
|
| 248 |
+
# stalling the review pipeline on Gemini free-tier exhaustion.
|
| 249 |
+
llm = _get_groq_chat(**kwargs)
|
| 250 |
+
if llm is not None:
|
| 251 |
+
logger.debug("Using Groq (model=%s)", kwargs.get("model", GROQ_MODEL))
|
| 252 |
+
return llm
|
| 253 |
+
|
| 254 |
+
llm = _get_gemini_chat(**kwargs)
|
| 255 |
+
if llm is not None:
|
| 256 |
+
logger.debug("Falling back to Gemini (model=%s)", kwargs.get("model", GEMINI_MODEL))
|
| 257 |
+
return llm
|
| 258 |
+
|
| 259 |
+
raise ValueError(
|
| 260 |
+
"No LLM available. Set GEMINI_API_KEY (primary) or GROQ_API_KEY (fallback)."
|
| 261 |
+
)
|
nodes/aggregator.py
CHANGED
|
@@ -1,286 +1,286 @@
|
|
| 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 pydantic import BaseModel, Field
|
| 9 |
-
|
| 10 |
-
from state import Finding, OpenCodeReviewState, Severity, Verdict
|
| 11 |
-
|
| 12 |
-
logger = logging.getLogger(__name__)
|
| 13 |
-
|
| 14 |
-
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 15 |
-
DEFAULT_TEMPERATURE = 0.0
|
| 16 |
-
|
| 17 |
-
# Prompt version β tied to the file on disk
|
| 18 |
-
PROMPT_VERSION = "v1"
|
| 19 |
-
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"aggregator_{PROMPT_VERSION}.txt"
|
| 20 |
-
|
| 21 |
-
# Findings below this confidence are dropped before the LLM step
|
| 22 |
-
MIN_CONFIDENCE = 0.25
|
| 23 |
-
# Files/line pairs within this many lines are considered duplicates
|
| 24 |
-
LINE_TOLERANCE = 5
|
| 25 |
-
|
| 26 |
-
# Default to rule-based aggregation (skips expensive LLM critic call).
|
| 27 |
-
# Set AGGREGATOR_USE_LLM_CRITIC=true in env to re-enable the LLM pass.
|
| 28 |
-
USE_LLM_CRITIC = os.environ.get("AGGREGATOR_USE_LLM_CRITIC", "").lower() in ("1", "true", "yes")
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
# βββ Load prompt from file ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def _load_prompt() -> str:
|
| 35 |
-
"""Load the system prompt from the versioned prompt file."""
|
| 36 |
-
try:
|
| 37 |
-
return PROMPT_FILE.read_text(encoding="utf-8")
|
| 38 |
-
except FileNotFoundError:
|
| 39 |
-
logger.warning("Prompt file %s not found β using fallback", PROMPT_FILE)
|
| 40 |
-
return (
|
| 41 |
-
"You are a senior engineer acting as a critic of a code review. "
|
| 42 |
-
"Filter out noise, deduplicate findings, and produce a verdict. "
|
| 43 |
-
"Return the filtered list of findings plus your verdict."
|
| 44 |
-
)
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
SYSTEM_PROMPT = _load_prompt()
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
# βββ LLM output schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
class AggregatedReview(BaseModel):
|
| 54 |
-
"""Final, noise-filtered findings and overall verdict."""
|
| 55 |
-
findings: list[Finding] = Field(
|
| 56 |
-
default_factory=list,
|
| 57 |
-
description="Deduplicated, noise-filtered findings worth a senior engineer's time.",
|
| 58 |
-
)
|
| 59 |
-
verdict: Verdict = Field(
|
| 60 |
-
description="Overall PR verdict after considering all findings.",
|
| 61 |
-
)
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
# βββ Pre-LLM heuristic deduplication ββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def _deduplicate(findings: list[Finding]) -> list[Finding]:
|
| 68 |
-
"""Heuristic dedup: group by ``(file_path, line_start)`` with a line
|
| 69 |
-
tolerance, keeping the highest-confidence finding per group."""
|
| 70 |
-
if not findings:
|
| 71 |
-
return []
|
| 72 |
-
|
| 73 |
-
# Sort by (file, line_start) so we can iterate and merge neighbours
|
| 74 |
-
sorted_fs = sorted(findings, key=lambda f: (f.file_path, f.line_start))
|
| 75 |
-
|
| 76 |
-
merged: list[Finding] = []
|
| 77 |
-
current: Finding = sorted_fs[0]
|
| 78 |
-
|
| 79 |
-
for f in sorted_fs[1:]:
|
| 80 |
-
same_file = f.file_path == current.file_path
|
| 81 |
-
close_lines = abs(f.line_start - current.line_start) <= LINE_TOLERANCE
|
| 82 |
-
if same_file and close_lines:
|
| 83 |
-
# Keep the higher-confidence finding, merge comments
|
| 84 |
-
if f.confidence > current.confidence:
|
| 85 |
-
current = f
|
| 86 |
-
if current.confidence < 0.9:
|
| 87 |
-
current.confidence = round(
|
| 88 |
-
(current.confidence + f.confidence) / 2, 2
|
| 89 |
-
)
|
| 90 |
-
# Prefer the specific comment over a generic one
|
| 91 |
-
if len(f.comment) > len(current.comment):
|
| 92 |
-
current.comment = f.comment
|
| 93 |
-
if f.suggested_fix and not current.suggested_fix:
|
| 94 |
-
current.suggested_fix = f.suggested_fix
|
| 95 |
-
# Escalate severity if either finding is more severe
|
| 96 |
-
current.severity = _more_severe(current.severity, f.severity)
|
| 97 |
-
else:
|
| 98 |
-
merged.append(current)
|
| 99 |
-
current = f
|
| 100 |
-
merged.append(current)
|
| 101 |
-
|
| 102 |
-
# Drop low-confidence noise
|
| 103 |
-
merged = [f for f in merged if f.confidence >= MIN_CONFIDENCE]
|
| 104 |
-
|
| 105 |
-
return merged
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
_SEVERITY_ORDER = {
|
| 109 |
-
Severity.CRITICAL: 0,
|
| 110 |
-
Severity.HIGH: 1,
|
| 111 |
-
Severity.MEDIUM: 2,
|
| 112 |
-
Severity.LOW: 3,
|
| 113 |
-
Severity.INFO: 4,
|
| 114 |
-
}
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
def _more_severe(a: Severity, b: Severity) -> Severity:
|
| 118 |
-
return a if _SEVERITY_ORDER.get(a, 5) < _SEVERITY_ORDER.get(b, 5) else b
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
# βββ Rule-based fallback verdict ββββββββββββββββββββββββββββββββββββββββββββ
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
def _rule_verdict(findings: list[Finding]) -> Verdict:
|
| 125 |
-
"""Build a verdict from deduplicated findings without an LLM call."""
|
| 126 |
-
counts = {s: 0 for s in Severity}
|
| 127 |
-
for f in findings:
|
| 128 |
-
counts[f.severity] = counts.get(f.severity, 0) + 1
|
| 129 |
-
|
| 130 |
-
critical = counts[Severity.CRITICAL]
|
| 131 |
-
high = counts[Severity.HIGH]
|
| 132 |
-
|
| 133 |
-
if critical > 0:
|
| 134 |
-
recommendation = "block"
|
| 135 |
-
approved = False
|
| 136 |
-
elif high > 0:
|
| 137 |
-
recommendation = "request_changes"
|
| 138 |
-
approved = False
|
| 139 |
-
elif len(findings) > 0:
|
| 140 |
-
recommendation = "comment"
|
| 141 |
-
approved = True
|
| 142 |
-
else:
|
| 143 |
-
recommendation = "approve"
|
| 144 |
-
approved = True
|
| 145 |
-
|
| 146 |
-
# Score: 10 - penalty based on severity
|
| 147 |
-
score = max(0.0, min(10.0, 10.0 - critical * 4.0 - high * 2.0 - counts.get(Severity.MEDIUM, 0) * 0.5))
|
| 148 |
-
|
| 149 |
-
severity_counts = {s.value: counts.get(s, 0) for s in Severity}
|
| 150 |
-
|
| 151 |
-
return Verdict(
|
| 152 |
-
summary=_rule_summary(recommendation, severity_counts),
|
| 153 |
-
approved=approved,
|
| 154 |
-
overall_score=round(score, 1),
|
| 155 |
-
critical_count=critical,
|
| 156 |
-
high_count=high,
|
| 157 |
-
recommendation=recommendation,
|
| 158 |
-
)
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
def _rule_summary(recommendation: str, counts: dict) -> str:
|
| 162 |
-
parts = [f"{v} {k}" for k, v in counts.items() if v > 0]
|
| 163 |
-
if not parts:
|
| 164 |
-
return "No issues found β PR looks clean."
|
| 165 |
-
body = ", ".join(parts)
|
| 166 |
-
if recommendation == "block":
|
| 167 |
-
return f"Blocking: {body} β critical issues must be resolved."
|
| 168 |
-
elif recommendation == "request_changes":
|
| 169 |
-
return f"Changes requested: {body} β high-severity issues should be addressed."
|
| 170 |
-
elif recommendation == "comment":
|
| 171 |
-
return f"Minor concerns: {body} β consider addressing for best practices."
|
| 172 |
-
return f"Approved: {body} β no significant issues."
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
# βββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
def _build_prompt(findings: list[Finding]) -> str:
|
| 179 |
-
lines = [
|
| 180 |
-
"Below are the raw findings from automated code reviewers "
|
| 181 |
-
"(correctness, security, test-coverage).",
|
| 182 |
-
"",
|
| 183 |
-
"Filter out noise and return only the findings a senior engineer "
|
| 184 |
-
"would actually leave on this PR.",
|
| 185 |
-
"",
|
| 186 |
-
"## Raw findings",
|
| 187 |
-
]
|
| 188 |
-
for i, f in enumerate(findings, 1):
|
| 189 |
-
lines.append(f"\n--- Finding {i} ---")
|
| 190 |
-
lines.append(f" File: {f.file_path}")
|
| 191 |
-
lines.append(f" Lines: {f.line_start}β{f.line_end}")
|
| 192 |
-
lines.append(f" Severity: {f.severity.value}")
|
| 193 |
-
lines.append(f" Category: {f.category}")
|
| 194 |
-
lines.append(f" Comment: {f.comment}")
|
| 195 |
-
lines.append(f" Confidence: {f.confidence}")
|
| 196 |
-
if f.suggested_fix:
|
| 197 |
-
lines.append(f" Fix: {f.suggested_fix[:200]}")
|
| 198 |
-
|
| 199 |
-
lines.append("\nNow apply the deduplication, noise-filtering, and verdict rules.")
|
| 200 |
-
return "\n".join(lines)
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
def aggregator_node(state: OpenCodeReviewState) -> dict:
|
| 207 |
-
"""Deduplicate, filter, and aggregate all findings into a final verdict.
|
| 208 |
-
|
| 209 |
-
Returns state updates for ``findings`` (overwritten with the filtered
|
| 210 |
-
list) and ``verdict`` (set-once by this node).
|
| 211 |
-
|
| 212 |
-
Two-phase approach:
|
| 213 |
-
1. Pre-LLM heuristic deduplication (groups by file/line proximity).
|
| 214 |
-
2. Rule-based verdict by default (fast, ~10ms), or optional LLM critic
|
| 215 |
-
when ``USE_LLM_CRITIC`` is enabled.
|
| 216 |
-
"""
|
| 217 |
-
failed = [stage for stage in state.review_stages if stage.get("status") == "failed"]
|
| 218 |
-
if failed:
|
| 219 |
-
names = ", ".join(stage["reviewer"] for stage in failed)
|
| 220 |
-
return {"final_findings": _deduplicate(state.findings), "verdict": Verdict(
|
| 221 |
-
summary=f"Review incomplete: {names} failed. Findings are partial; no approval or quality score is available.",
|
| 222 |
-
approved=False, overall_score=None, recommendation="incomplete",
|
| 223 |
-
)}
|
| 224 |
-
raw_findings = state.findings
|
| 225 |
-
if not raw_findings:
|
| 226 |
-
logger.info("No findings to aggregate β producing empty verdict")
|
| 227 |
-
empty_verdict = Verdict(
|
| 228 |
-
summary="No issues found β PR looks clean.",
|
| 229 |
-
approved=True,
|
| 230 |
-
overall_score=10.0,
|
| 231 |
-
critical_count=0,
|
| 232 |
-
high_count=0,
|
| 233 |
-
recommendation="approve",
|
| 234 |
-
)
|
| 235 |
-
return {"final_findings": [], "verdict": empty_verdict}
|
| 236 |
-
|
| 237 |
-
# -- Phase 1: Heuristic dedup --------------------------------------------
|
| 238 |
-
deduped = _deduplicate(raw_findings)
|
| 239 |
-
logger.info(
|
| 240 |
-
"Dedup heuristic: %d raw β %d merged",
|
| 241 |
-
len(raw_findings), len(deduped),
|
| 242 |
-
)
|
| 243 |
-
|
| 244 |
-
# -- Phase 2: Rule-based (default, fast) or LLM critic (opt-in) ----------
|
| 245 |
-
if USE_LLM_CRITIC:
|
| 246 |
-
try:
|
| 247 |
-
llm = create_llm(endpoint=state.endpoint or None)
|
| 248 |
-
except ValueError as exc:
|
| 249 |
-
logger.warning("LLM critic unavailable β using rule-based: %s", exc)
|
| 250 |
-
llm = None
|
| 251 |
-
|
| 252 |
-
if llm is not None:
|
| 253 |
-
logger.info(
|
| 254 |
-
"Invoking aggregator LLM critic (prompt_version=%s) β¦",
|
| 255 |
-
PROMPT_VERSION,
|
| 256 |
-
)
|
| 257 |
-
try:
|
| 258 |
-
structured_llm = llm.with_structured_output(AggregatedReview)
|
| 259 |
-
messages = [
|
| 260 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 261 |
-
{"role": "user", "content": _build_prompt(deduped)},
|
| 262 |
-
]
|
| 263 |
-
result: AggregatedReview = structured_llm.invoke(messages) # type: ignore[assignment]
|
| 264 |
-
except Exception as exc:
|
| 265 |
-
logger.warning("LLM critic failed β falling back to rule-based: %s", exc)
|
| 266 |
-
result = None
|
| 267 |
-
|
| 268 |
-
if result is not None:
|
| 269 |
-
final_findings = result.findings
|
| 270 |
-
verdict = result.verdict
|
| 271 |
-
logger.info(
|
| 272 |
-
"LLM aggregator: %d deduped β %d final, recommendation=%s",
|
| 273 |
-
len(deduped), len(final_findings),
|
| 274 |
-
verdict.recommendation,
|
| 275 |
-
)
|
| 276 |
-
return {"final_findings": final_findings, "verdict": verdict}
|
| 277 |
-
|
| 278 |
-
# Rule-based path (default) β zero LLM overhead
|
| 279 |
-
logger.info("Using rule-based aggregation (fast path)")
|
| 280 |
-
final_findings = deduped
|
| 281 |
-
verdict = _rule_verdict(deduped)
|
| 282 |
-
|
| 283 |
-
return {
|
| 284 |
-
"final_findings": final_findings, # plain list, overwrites
|
| 285 |
-
"verdict": verdict, # set-once, no reducer needed
|
| 286 |
-
}
|
|
|
|
| 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 pydantic import BaseModel, Field
|
| 9 |
+
|
| 10 |
+
from state import Finding, OpenCodeReviewState, Severity, Verdict
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 15 |
+
DEFAULT_TEMPERATURE = 0.0
|
| 16 |
+
|
| 17 |
+
# Prompt version β tied to the file on disk
|
| 18 |
+
PROMPT_VERSION = "v1"
|
| 19 |
+
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"aggregator_{PROMPT_VERSION}.txt"
|
| 20 |
+
|
| 21 |
+
# Findings below this confidence are dropped before the LLM step
|
| 22 |
+
MIN_CONFIDENCE = 0.25
|
| 23 |
+
# Files/line pairs within this many lines are considered duplicates
|
| 24 |
+
LINE_TOLERANCE = 5
|
| 25 |
+
|
| 26 |
+
# Default to rule-based aggregation (skips expensive LLM critic call).
|
| 27 |
+
# Set AGGREGATOR_USE_LLM_CRITIC=true in env to re-enable the LLM pass.
|
| 28 |
+
USE_LLM_CRITIC = os.environ.get("AGGREGATOR_USE_LLM_CRITIC", "").lower() in ("1", "true", "yes")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# βββ Load prompt from file ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _load_prompt() -> str:
|
| 35 |
+
"""Load the system prompt from the versioned prompt file."""
|
| 36 |
+
try:
|
| 37 |
+
return PROMPT_FILE.read_text(encoding="utf-8")
|
| 38 |
+
except FileNotFoundError:
|
| 39 |
+
logger.warning("Prompt file %s not found β using fallback", PROMPT_FILE)
|
| 40 |
+
return (
|
| 41 |
+
"You are a senior engineer acting as a critic of a code review. "
|
| 42 |
+
"Filter out noise, deduplicate findings, and produce a verdict. "
|
| 43 |
+
"Return the filtered list of findings plus your verdict."
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
SYSTEM_PROMPT = _load_prompt()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# βββ LLM output schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class AggregatedReview(BaseModel):
|
| 54 |
+
"""Final, noise-filtered findings and overall verdict."""
|
| 55 |
+
findings: list[Finding] = Field(
|
| 56 |
+
default_factory=list,
|
| 57 |
+
description="Deduplicated, noise-filtered findings worth a senior engineer's time.",
|
| 58 |
+
)
|
| 59 |
+
verdict: Verdict = Field(
|
| 60 |
+
description="Overall PR verdict after considering all findings.",
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# βββ Pre-LLM heuristic deduplication ββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _deduplicate(findings: list[Finding]) -> list[Finding]:
|
| 68 |
+
"""Heuristic dedup: group by ``(file_path, line_start)`` with a line
|
| 69 |
+
tolerance, keeping the highest-confidence finding per group."""
|
| 70 |
+
if not findings:
|
| 71 |
+
return []
|
| 72 |
+
|
| 73 |
+
# Sort by (file, line_start) so we can iterate and merge neighbours
|
| 74 |
+
sorted_fs = sorted(findings, key=lambda f: (f.file_path, f.line_start))
|
| 75 |
+
|
| 76 |
+
merged: list[Finding] = []
|
| 77 |
+
current: Finding = sorted_fs[0]
|
| 78 |
+
|
| 79 |
+
for f in sorted_fs[1:]:
|
| 80 |
+
same_file = f.file_path == current.file_path
|
| 81 |
+
close_lines = abs(f.line_start - current.line_start) <= LINE_TOLERANCE
|
| 82 |
+
if same_file and close_lines:
|
| 83 |
+
# Keep the higher-confidence finding, merge comments
|
| 84 |
+
if f.confidence > current.confidence:
|
| 85 |
+
current = f
|
| 86 |
+
if current.confidence < 0.9:
|
| 87 |
+
current.confidence = round(
|
| 88 |
+
(current.confidence + f.confidence) / 2, 2
|
| 89 |
+
)
|
| 90 |
+
# Prefer the specific comment over a generic one
|
| 91 |
+
if len(f.comment) > len(current.comment):
|
| 92 |
+
current.comment = f.comment
|
| 93 |
+
if f.suggested_fix and not current.suggested_fix:
|
| 94 |
+
current.suggested_fix = f.suggested_fix
|
| 95 |
+
# Escalate severity if either finding is more severe
|
| 96 |
+
current.severity = _more_severe(current.severity, f.severity)
|
| 97 |
+
else:
|
| 98 |
+
merged.append(current)
|
| 99 |
+
current = f
|
| 100 |
+
merged.append(current)
|
| 101 |
+
|
| 102 |
+
# Drop low-confidence noise
|
| 103 |
+
merged = [f for f in merged if f.confidence >= MIN_CONFIDENCE]
|
| 104 |
+
|
| 105 |
+
return merged
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
_SEVERITY_ORDER = {
|
| 109 |
+
Severity.CRITICAL: 0,
|
| 110 |
+
Severity.HIGH: 1,
|
| 111 |
+
Severity.MEDIUM: 2,
|
| 112 |
+
Severity.LOW: 3,
|
| 113 |
+
Severity.INFO: 4,
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _more_severe(a: Severity, b: Severity) -> Severity:
|
| 118 |
+
return a if _SEVERITY_ORDER.get(a, 5) < _SEVERITY_ORDER.get(b, 5) else b
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# βββ Rule-based fallback verdict ββββββββββββββββββββββββββββββββββββββββββββ
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _rule_verdict(findings: list[Finding]) -> Verdict:
|
| 125 |
+
"""Build a verdict from deduplicated findings without an LLM call."""
|
| 126 |
+
counts = {s: 0 for s in Severity}
|
| 127 |
+
for f in findings:
|
| 128 |
+
counts[f.severity] = counts.get(f.severity, 0) + 1
|
| 129 |
+
|
| 130 |
+
critical = counts[Severity.CRITICAL]
|
| 131 |
+
high = counts[Severity.HIGH]
|
| 132 |
+
|
| 133 |
+
if critical > 0:
|
| 134 |
+
recommendation = "block"
|
| 135 |
+
approved = False
|
| 136 |
+
elif high > 0:
|
| 137 |
+
recommendation = "request_changes"
|
| 138 |
+
approved = False
|
| 139 |
+
elif len(findings) > 0:
|
| 140 |
+
recommendation = "comment"
|
| 141 |
+
approved = True
|
| 142 |
+
else:
|
| 143 |
+
recommendation = "approve"
|
| 144 |
+
approved = True
|
| 145 |
+
|
| 146 |
+
# Score: 10 - penalty based on severity
|
| 147 |
+
score = max(0.0, min(10.0, 10.0 - critical * 4.0 - high * 2.0 - counts.get(Severity.MEDIUM, 0) * 0.5))
|
| 148 |
+
|
| 149 |
+
severity_counts = {s.value: counts.get(s, 0) for s in Severity}
|
| 150 |
+
|
| 151 |
+
return Verdict(
|
| 152 |
+
summary=_rule_summary(recommendation, severity_counts),
|
| 153 |
+
approved=approved,
|
| 154 |
+
overall_score=round(score, 1),
|
| 155 |
+
critical_count=critical,
|
| 156 |
+
high_count=high,
|
| 157 |
+
recommendation=recommendation,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _rule_summary(recommendation: str, counts: dict) -> str:
|
| 162 |
+
parts = [f"{v} {k}" for k, v in counts.items() if v > 0]
|
| 163 |
+
if not parts:
|
| 164 |
+
return "No issues found β PR looks clean."
|
| 165 |
+
body = ", ".join(parts)
|
| 166 |
+
if recommendation == "block":
|
| 167 |
+
return f"Blocking: {body} β critical issues must be resolved."
|
| 168 |
+
elif recommendation == "request_changes":
|
| 169 |
+
return f"Changes requested: {body} β high-severity issues should be addressed."
|
| 170 |
+
elif recommendation == "comment":
|
| 171 |
+
return f"Minor concerns: {body} β consider addressing for best practices."
|
| 172 |
+
return f"Approved: {body} β no significant issues."
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# βββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _build_prompt(findings: list[Finding]) -> str:
|
| 179 |
+
lines = [
|
| 180 |
+
"Below are the raw findings from automated code reviewers "
|
| 181 |
+
"(correctness, security, test-coverage).",
|
| 182 |
+
"",
|
| 183 |
+
"Filter out noise and return only the findings a senior engineer "
|
| 184 |
+
"would actually leave on this PR.",
|
| 185 |
+
"",
|
| 186 |
+
"## Raw findings",
|
| 187 |
+
]
|
| 188 |
+
for i, f in enumerate(findings, 1):
|
| 189 |
+
lines.append(f"\n--- Finding {i} ---")
|
| 190 |
+
lines.append(f" File: {f.file_path}")
|
| 191 |
+
lines.append(f" Lines: {f.line_start}β{f.line_end}")
|
| 192 |
+
lines.append(f" Severity: {f.severity.value}")
|
| 193 |
+
lines.append(f" Category: {f.category}")
|
| 194 |
+
lines.append(f" Comment: {f.comment}")
|
| 195 |
+
lines.append(f" Confidence: {f.confidence}")
|
| 196 |
+
if f.suggested_fix:
|
| 197 |
+
lines.append(f" Fix: {f.suggested_fix[:200]}")
|
| 198 |
+
|
| 199 |
+
lines.append("\nNow apply the deduplication, noise-filtering, and verdict rules.")
|
| 200 |
+
return "\n".join(lines)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def aggregator_node(state: OpenCodeReviewState) -> dict:
|
| 207 |
+
"""Deduplicate, filter, and aggregate all findings into a final verdict.
|
| 208 |
+
|
| 209 |
+
Returns state updates for ``findings`` (overwritten with the filtered
|
| 210 |
+
list) and ``verdict`` (set-once by this node).
|
| 211 |
+
|
| 212 |
+
Two-phase approach:
|
| 213 |
+
1. Pre-LLM heuristic deduplication (groups by file/line proximity).
|
| 214 |
+
2. Rule-based verdict by default (fast, ~10ms), or optional LLM critic
|
| 215 |
+
when ``USE_LLM_CRITIC`` is enabled.
|
| 216 |
+
"""
|
| 217 |
+
failed = [stage for stage in state.review_stages if stage.get("status") == "failed"]
|
| 218 |
+
if failed:
|
| 219 |
+
names = ", ".join(stage["reviewer"] for stage in failed)
|
| 220 |
+
return {"final_findings": _deduplicate(state.findings), "verdict": Verdict(
|
| 221 |
+
summary=f"Review incomplete: {names} failed. Findings are partial; no approval or quality score is available.",
|
| 222 |
+
approved=False, overall_score=None, recommendation="incomplete",
|
| 223 |
+
)}
|
| 224 |
+
raw_findings = state.findings
|
| 225 |
+
if not raw_findings:
|
| 226 |
+
logger.info("No findings to aggregate β producing empty verdict")
|
| 227 |
+
empty_verdict = Verdict(
|
| 228 |
+
summary="No issues found β PR looks clean.",
|
| 229 |
+
approved=True,
|
| 230 |
+
overall_score=10.0,
|
| 231 |
+
critical_count=0,
|
| 232 |
+
high_count=0,
|
| 233 |
+
recommendation="approve",
|
| 234 |
+
)
|
| 235 |
+
return {"final_findings": [], "verdict": empty_verdict}
|
| 236 |
+
|
| 237 |
+
# -- Phase 1: Heuristic dedup --------------------------------------------
|
| 238 |
+
deduped = _deduplicate(raw_findings)
|
| 239 |
+
logger.info(
|
| 240 |
+
"Dedup heuristic: %d raw β %d merged",
|
| 241 |
+
len(raw_findings), len(deduped),
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
# -- Phase 2: Rule-based (default, fast) or LLM critic (opt-in) ----------
|
| 245 |
+
if USE_LLM_CRITIC:
|
| 246 |
+
try:
|
| 247 |
+
llm = create_llm(endpoint=state.endpoint or None)
|
| 248 |
+
except ValueError as exc:
|
| 249 |
+
logger.warning("LLM critic unavailable β using rule-based: %s", exc)
|
| 250 |
+
llm = None
|
| 251 |
+
|
| 252 |
+
if llm is not None:
|
| 253 |
+
logger.info(
|
| 254 |
+
"Invoking aggregator LLM critic (prompt_version=%s) β¦",
|
| 255 |
+
PROMPT_VERSION,
|
| 256 |
+
)
|
| 257 |
+
try:
|
| 258 |
+
structured_llm = llm.with_structured_output(AggregatedReview)
|
| 259 |
+
messages = [
|
| 260 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 261 |
+
{"role": "user", "content": _build_prompt(deduped)},
|
| 262 |
+
]
|
| 263 |
+
result: AggregatedReview = structured_llm.invoke(messages) # type: ignore[assignment]
|
| 264 |
+
except Exception as exc:
|
| 265 |
+
logger.warning("LLM critic failed β falling back to rule-based: %s", exc)
|
| 266 |
+
result = None
|
| 267 |
+
|
| 268 |
+
if result is not None:
|
| 269 |
+
final_findings = result.findings
|
| 270 |
+
verdict = result.verdict
|
| 271 |
+
logger.info(
|
| 272 |
+
"LLM aggregator: %d deduped β %d final, recommendation=%s",
|
| 273 |
+
len(deduped), len(final_findings),
|
| 274 |
+
verdict.recommendation,
|
| 275 |
+
)
|
| 276 |
+
return {"final_findings": final_findings, "verdict": verdict}
|
| 277 |
+
|
| 278 |
+
# Rule-based path (default) β zero LLM overhead
|
| 279 |
+
logger.info("Using rule-based aggregation (fast path)")
|
| 280 |
+
final_findings = deduped
|
| 281 |
+
verdict = _rule_verdict(deduped)
|
| 282 |
+
|
| 283 |
+
return {
|
| 284 |
+
"final_findings": final_findings, # plain list, overwrites
|
| 285 |
+
"verdict": verdict, # set-once, no reducer needed
|
| 286 |
+
}
|
nodes/correctness_reviewer.py
CHANGED
|
@@ -1,222 +1,222 @@
|
|
| 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.review_runtime import changed_context, invoke_review, stage_result
|
| 11 |
-
from pydantic import BaseModel, Field
|
| 12 |
-
|
| 13 |
-
from state import Finding, OpenCodeReviewState, Severity
|
| 14 |
-
|
| 15 |
-
logger = logging.getLogger(__name__)
|
| 16 |
-
|
| 17 |
-
# Model used on Groq β good at function calling / structured output
|
| 18 |
-
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 19 |
-
DEFAULT_TEMPERATURE = 0.0
|
| 20 |
-
|
| 21 |
-
# Prompt version β tied to the file on disk
|
| 22 |
-
PROMPT_VERSION = "v1"
|
| 23 |
-
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"correctness_{PROMPT_VERSION}.txt"
|
| 24 |
-
|
| 25 |
-
# Max characters of context to include in the prompt (soft limit)
|
| 26 |
-
MAX_CONTEXT_CHARS = 2_000
|
| 27 |
-
# Max changed-file content to include per file
|
| 28 |
-
MAX_FILE_CONTENT_CHARS = 600
|
| 29 |
-
# Keep model requests below free-provider token limits. Deterministic checks
|
| 30 |
-
# still inspect the complete diff from state.diff.
|
| 31 |
-
MAX_DIFF_CHARS = 9_000
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
# βββ Load prompt from file ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def _load_prompt() -> str:
|
| 38 |
-
"""Load the system prompt from the versioned prompt file."""
|
| 39 |
-
try:
|
| 40 |
-
return PROMPT_FILE.read_text(encoding="utf-8")
|
| 41 |
-
except FileNotFoundError:
|
| 42 |
-
logger.warning("Prompt file %s not found β using fallback", PROMPT_FILE)
|
| 43 |
-
return (
|
| 44 |
-
"You are a seasoned code reviewer focused exclusively on correctness. "
|
| 45 |
-
"Analyse the PR diff and look for logic errors, edge cases, "
|
| 46 |
-
"off-by-one errors, missing null checks, resource mismanagement, "
|
| 47 |
-
"and concurrency hazards. Return a list of findings."
|
| 48 |
-
)
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
SYSTEM_PROMPT = _load_prompt()
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
# βββ Wrapper schema for structured output βββββββββββββββββββββββββββββββββββ
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
class CorrectnessReview(BaseModel):
|
| 58 |
-
"""A list of correctness issues found during code review.
|
| 59 |
-
|
| 60 |
-
The LLM MUST populate this with every correctness-relevant finding in the
|
| 61 |
-
diff. Return an empty list if no correctness issues are found.
|
| 62 |
-
"""
|
| 63 |
-
findings: list[Finding] = Field(
|
| 64 |
-
default_factory=list,
|
| 65 |
-
description=(
|
| 66 |
-
"Correctness issues found in the PR diff. "
|
| 67 |
-
"Each issue must reference a specific file and line range."
|
| 68 |
-
),
|
| 69 |
-
)
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
# βββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def _build_prompt(state: OpenCodeReviewState) -> str:
|
| 76 |
-
"""Build the user-facing prompt from the current graph state."""
|
| 77 |
-
lines: list[str] = []
|
| 78 |
-
|
| 79 |
-
lines.append("## Diff\n```diff")
|
| 80 |
-
diff = state.diff or ""
|
| 81 |
-
if len(diff) > MAX_DIFF_CHARS:
|
| 82 |
-
diff = diff[:MAX_DIFF_CHARS] + "\n⦠(diff truncated for model context)"
|
| 83 |
-
lines.append(diff)
|
| 84 |
-
lines.append("```\n")
|
| 85 |
-
|
| 86 |
-
# Changed files with full content (truncated per file)
|
| 87 |
-
if state.changed_files:
|
| 88 |
-
lines.append("## Changed files\n")
|
| 89 |
-
for cf in state.changed_files:
|
| 90 |
-
header = f"### {cf.path} ({cf.status})"
|
| 91 |
-
lines.append(header)
|
| 92 |
-
content = changed_context(cf, state.review_mode)
|
| 93 |
-
if len(content) > MAX_FILE_CONTENT_CHARS:
|
| 94 |
-
content = content[:MAX_FILE_CONTENT_CHARS] + "\n⦠(truncated)"
|
| 95 |
-
lines.append(f"```\n{content}\n```\n")
|
| 96 |
-
|
| 97 |
-
# Context chunks (truncated total)
|
| 98 |
-
if state.context_chunks:
|
| 99 |
-
lines.append("## Retrieved context\n")
|
| 100 |
-
ctx_chars = 0
|
| 101 |
-
for chunk in state.context_chunks:
|
| 102 |
-
snippet = chunk.content
|
| 103 |
-
if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
|
| 104 |
-
remaining = MAX_CONTEXT_CHARS - ctx_chars
|
| 105 |
-
if remaining > 200:
|
| 106 |
-
lines.append(f"> {snippet[:remaining]}β¦ (truncated)")
|
| 107 |
-
break
|
| 108 |
-
if chunk.source == "past_pr":
|
| 109 |
-
lines.append(f"> [Past PR β {chunk.file_path}]: {snippet}")
|
| 110 |
-
else:
|
| 111 |
-
lines.append(f"> [{chunk.file_path}]: {snippet}")
|
| 112 |
-
ctx_chars += len(snippet)
|
| 113 |
-
|
| 114 |
-
return "\n".join(lines)
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
def correctness_reviewer_node(state: OpenCodeReviewState) -> dict:
|
| 121 |
-
started = time.monotonic()
|
| 122 |
-
"""Analyse the diff and context chunks for correctness issues using an LLM.
|
| 123 |
-
|
| 124 |
-
Returns state updates for ``findings`` (accumulated via the ``add``
|
| 125 |
-
reducer).
|
| 126 |
-
"""
|
| 127 |
-
# --- Sanity checks -------------------------------------------------------
|
| 128 |
-
if not state.diff:
|
| 129 |
-
logger.info("No diff to review β skipping correctness review")
|
| 130 |
-
return {}
|
| 131 |
-
|
| 132 |
-
# Run deterministic checks before the model call so provider failures do
|
| 133 |
-
# not erase high-confidence findings.
|
| 134 |
-
static_findings = []
|
| 135 |
-
current_file = "unknown"
|
| 136 |
-
current_line = 0
|
| 137 |
-
for raw_line in (state.diff or "").splitlines():
|
| 138 |
-
if raw_line.startswith("+++ b/"):
|
| 139 |
-
current_file = raw_line[6:].strip()
|
| 140 |
-
current_line = 0
|
| 141 |
-
elif raw_line.startswith("@@"):
|
| 142 |
-
match = re.search(r"\+(\d+)", raw_line)
|
| 143 |
-
current_line = int(match.group(1)) if match else current_line
|
| 144 |
-
elif re.search(r"\.forEach\s*\(\s*async\b", raw_line):
|
| 145 |
-
static_findings.append(Finding(
|
| 146 |
-
file_path=current_file,
|
| 147 |
-
line_start=max(1, current_line),
|
| 148 |
-
line_end=max(1, current_line),
|
| 149 |
-
severity=Severity.HIGH,
|
| 150 |
-
category="correctness",
|
| 151 |
-
comment="An async callback passed to forEach is not awaited, so cleanup or side effects can run after the function returns and errors can bypass surrounding try/catch handling.",
|
| 152 |
-
confidence=0.99,
|
| 153 |
-
suggested_fix="Replace forEach(async ...) with a for...of loop or await Promise.all(items.map(async ...)).",
|
| 154 |
-
))
|
| 155 |
-
if raw_line.startswith("+") and not raw_line.startswith("+++"):
|
| 156 |
-
current_line += 1
|
| 157 |
-
|
| 158 |
-
logger.info("Deterministic correctness checks found %d issue(s)", len(static_findings))
|
| 159 |
-
|
| 160 |
-
# --- Build the LLM (Gemini primary β Groq fallback) -----------------------
|
| 161 |
-
try:
|
| 162 |
-
llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
|
| 163 |
-
except ValueError as exc:
|
| 164 |
-
logger.warning("LLM unavailable β skipping correctness review: %s", exc)
|
| 165 |
-
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
|
| 166 |
-
|
| 167 |
-
# --- Build the prompt ----------------------------------------------------
|
| 168 |
-
user_prompt = _build_prompt(state)
|
| 169 |
-
logger.info(
|
| 170 |
-
"Invoking correctness reviewer (diff=%s, context=%d chunks, prompt=%s, prompt_version=%s)",
|
| 171 |
-
_human_size(len(state.diff or "")),
|
| 172 |
-
len(state.context_chunks),
|
| 173 |
-
_human_size(len(user_prompt)),
|
| 174 |
-
PROMPT_VERSION,
|
| 175 |
-
)
|
| 176 |
-
|
| 177 |
-
# --- Invoke --------------------------------------------------------------
|
| 178 |
-
try:
|
| 179 |
-
messages = [
|
| 180 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 181 |
-
{"role": "user", "content": user_prompt},
|
| 182 |
-
]
|
| 183 |
-
result: CorrectnessReview = invoke_review(llm, CorrectnessReview, messages, mode=state.review_mode) # type: ignore[assignment]
|
| 184 |
-
except Exception as exc:
|
| 185 |
-
logger.warning("Correctness review LLM call failed: %s", exc)
|
| 186 |
-
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
|
| 187 |
-
|
| 188 |
-
# Deterministic guard for a high-impact async anti-pattern that LLMs can
|
| 189 |
-
# miss: promises created by forEach are not awaited by the caller.
|
| 190 |
-
result.findings.extend(static_findings)
|
| 191 |
-
|
| 192 |
-
# --- Log and return findings ---------------------------------------------
|
| 193 |
-
if result and result.findings:
|
| 194 |
-
logger.info(
|
| 195 |
-
"Correctness review found %d issue(s)",
|
| 196 |
-
len(result.findings),
|
| 197 |
-
)
|
| 198 |
-
for f in result.findings:
|
| 199 |
-
logger.debug(
|
| 200 |
-
" [%.2f] %s:%dβ%d β %s",
|
| 201 |
-
f.confidence, f.file_path, f.line_start, f.line_end,
|
| 202 |
-
f.comment[:80],
|
| 203 |
-
)
|
| 204 |
-
else:
|
| 205 |
-
logger.info("Correctness review found no issues")
|
| 206 |
-
|
| 207 |
-
return {
|
| 208 |
-
"findings": result.findings,
|
| 209 |
-
"review_stages": [stage_result("correctness", started, llm=llm)],
|
| 210 |
-
}
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
# βββ Utility βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
def _human_size(bytes_: int) -> str:
|
| 217 |
-
if bytes_ < 1024:
|
| 218 |
-
return f"{bytes_} B"
|
| 219 |
-
elif bytes_ < 1024 * 1024:
|
| 220 |
-
return f"{bytes_ / 1024:.1f} KiB"
|
| 221 |
-
else:
|
| 222 |
-
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.review_runtime import changed_context, invoke_review, stage_result
|
| 11 |
+
from pydantic import BaseModel, Field
|
| 12 |
+
|
| 13 |
+
from state import Finding, OpenCodeReviewState, Severity
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
# Model used on Groq β good at function calling / structured output
|
| 18 |
+
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 19 |
+
DEFAULT_TEMPERATURE = 0.0
|
| 20 |
+
|
| 21 |
+
# Prompt version β tied to the file on disk
|
| 22 |
+
PROMPT_VERSION = "v1"
|
| 23 |
+
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"correctness_{PROMPT_VERSION}.txt"
|
| 24 |
+
|
| 25 |
+
# Max characters of context to include in the prompt (soft limit)
|
| 26 |
+
MAX_CONTEXT_CHARS = 2_000
|
| 27 |
+
# Max changed-file content to include per file
|
| 28 |
+
MAX_FILE_CONTENT_CHARS = 600
|
| 29 |
+
# Keep model requests below free-provider token limits. Deterministic checks
|
| 30 |
+
# still inspect the complete diff from state.diff.
|
| 31 |
+
MAX_DIFF_CHARS = 9_000
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# βββ Load prompt from file ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _load_prompt() -> str:
|
| 38 |
+
"""Load the system prompt from the versioned prompt file."""
|
| 39 |
+
try:
|
| 40 |
+
return PROMPT_FILE.read_text(encoding="utf-8")
|
| 41 |
+
except FileNotFoundError:
|
| 42 |
+
logger.warning("Prompt file %s not found β using fallback", PROMPT_FILE)
|
| 43 |
+
return (
|
| 44 |
+
"You are a seasoned code reviewer focused exclusively on correctness. "
|
| 45 |
+
"Analyse the PR diff and look for logic errors, edge cases, "
|
| 46 |
+
"off-by-one errors, missing null checks, resource mismanagement, "
|
| 47 |
+
"and concurrency hazards. Return a list of findings."
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
SYSTEM_PROMPT = _load_prompt()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# βββ Wrapper schema for structured output βββββββββββββββββββββββββββββββββββ
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class CorrectnessReview(BaseModel):
|
| 58 |
+
"""A list of correctness issues found during code review.
|
| 59 |
+
|
| 60 |
+
The LLM MUST populate this with every correctness-relevant finding in the
|
| 61 |
+
diff. Return an empty list if no correctness issues are found.
|
| 62 |
+
"""
|
| 63 |
+
findings: list[Finding] = Field(
|
| 64 |
+
default_factory=list,
|
| 65 |
+
description=(
|
| 66 |
+
"Correctness issues found in the PR diff. "
|
| 67 |
+
"Each issue must reference a specific file and line range."
|
| 68 |
+
),
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# βββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _build_prompt(state: OpenCodeReviewState) -> str:
|
| 76 |
+
"""Build the user-facing prompt from the current graph state."""
|
| 77 |
+
lines: list[str] = []
|
| 78 |
+
|
| 79 |
+
lines.append("## Diff\n```diff")
|
| 80 |
+
diff = state.diff or ""
|
| 81 |
+
if len(diff) > MAX_DIFF_CHARS:
|
| 82 |
+
diff = diff[:MAX_DIFF_CHARS] + "\n⦠(diff truncated for model context)"
|
| 83 |
+
lines.append(diff)
|
| 84 |
+
lines.append("```\n")
|
| 85 |
+
|
| 86 |
+
# Changed files with full content (truncated per file)
|
| 87 |
+
if state.changed_files:
|
| 88 |
+
lines.append("## Changed files\n")
|
| 89 |
+
for cf in state.changed_files:
|
| 90 |
+
header = f"### {cf.path} ({cf.status})"
|
| 91 |
+
lines.append(header)
|
| 92 |
+
content = changed_context(cf, state.review_mode)
|
| 93 |
+
if len(content) > MAX_FILE_CONTENT_CHARS:
|
| 94 |
+
content = content[:MAX_FILE_CONTENT_CHARS] + "\n⦠(truncated)"
|
| 95 |
+
lines.append(f"```\n{content}\n```\n")
|
| 96 |
+
|
| 97 |
+
# Context chunks (truncated total)
|
| 98 |
+
if state.context_chunks:
|
| 99 |
+
lines.append("## Retrieved context\n")
|
| 100 |
+
ctx_chars = 0
|
| 101 |
+
for chunk in state.context_chunks:
|
| 102 |
+
snippet = chunk.content
|
| 103 |
+
if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
|
| 104 |
+
remaining = MAX_CONTEXT_CHARS - ctx_chars
|
| 105 |
+
if remaining > 200:
|
| 106 |
+
lines.append(f"> {snippet[:remaining]}β¦ (truncated)")
|
| 107 |
+
break
|
| 108 |
+
if chunk.source == "past_pr":
|
| 109 |
+
lines.append(f"> [Past PR β {chunk.file_path}]: {snippet}")
|
| 110 |
+
else:
|
| 111 |
+
lines.append(f"> [{chunk.file_path}]: {snippet}")
|
| 112 |
+
ctx_chars += len(snippet)
|
| 113 |
+
|
| 114 |
+
return "\n".join(lines)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def correctness_reviewer_node(state: OpenCodeReviewState) -> dict:
|
| 121 |
+
started = time.monotonic()
|
| 122 |
+
"""Analyse the diff and context chunks for correctness issues using an LLM.
|
| 123 |
+
|
| 124 |
+
Returns state updates for ``findings`` (accumulated via the ``add``
|
| 125 |
+
reducer).
|
| 126 |
+
"""
|
| 127 |
+
# --- Sanity checks -------------------------------------------------------
|
| 128 |
+
if not state.diff:
|
| 129 |
+
logger.info("No diff to review β skipping correctness review")
|
| 130 |
+
return {}
|
| 131 |
+
|
| 132 |
+
# Run deterministic checks before the model call so provider failures do
|
| 133 |
+
# not erase high-confidence findings.
|
| 134 |
+
static_findings = []
|
| 135 |
+
current_file = "unknown"
|
| 136 |
+
current_line = 0
|
| 137 |
+
for raw_line in (state.diff or "").splitlines():
|
| 138 |
+
if raw_line.startswith("+++ b/"):
|
| 139 |
+
current_file = raw_line[6:].strip()
|
| 140 |
+
current_line = 0
|
| 141 |
+
elif raw_line.startswith("@@"):
|
| 142 |
+
match = re.search(r"\+(\d+)", raw_line)
|
| 143 |
+
current_line = int(match.group(1)) if match else current_line
|
| 144 |
+
elif re.search(r"\.forEach\s*\(\s*async\b", raw_line):
|
| 145 |
+
static_findings.append(Finding(
|
| 146 |
+
file_path=current_file,
|
| 147 |
+
line_start=max(1, current_line),
|
| 148 |
+
line_end=max(1, current_line),
|
| 149 |
+
severity=Severity.HIGH,
|
| 150 |
+
category="correctness",
|
| 151 |
+
comment="An async callback passed to forEach is not awaited, so cleanup or side effects can run after the function returns and errors can bypass surrounding try/catch handling.",
|
| 152 |
+
confidence=0.99,
|
| 153 |
+
suggested_fix="Replace forEach(async ...) with a for...of loop or await Promise.all(items.map(async ...)).",
|
| 154 |
+
))
|
| 155 |
+
if raw_line.startswith("+") and not raw_line.startswith("+++"):
|
| 156 |
+
current_line += 1
|
| 157 |
+
|
| 158 |
+
logger.info("Deterministic correctness checks found %d issue(s)", len(static_findings))
|
| 159 |
+
|
| 160 |
+
# --- Build the LLM (Gemini primary β Groq fallback) -----------------------
|
| 161 |
+
try:
|
| 162 |
+
llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
|
| 163 |
+
except ValueError as exc:
|
| 164 |
+
logger.warning("LLM unavailable β skipping correctness review: %s", exc)
|
| 165 |
+
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
|
| 166 |
+
|
| 167 |
+
# --- Build the prompt ----------------------------------------------------
|
| 168 |
+
user_prompt = _build_prompt(state)
|
| 169 |
+
logger.info(
|
| 170 |
+
"Invoking correctness reviewer (diff=%s, context=%d chunks, prompt=%s, prompt_version=%s)",
|
| 171 |
+
_human_size(len(state.diff or "")),
|
| 172 |
+
len(state.context_chunks),
|
| 173 |
+
_human_size(len(user_prompt)),
|
| 174 |
+
PROMPT_VERSION,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
# --- Invoke --------------------------------------------------------------
|
| 178 |
+
try:
|
| 179 |
+
messages = [
|
| 180 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 181 |
+
{"role": "user", "content": user_prompt},
|
| 182 |
+
]
|
| 183 |
+
result: CorrectnessReview = invoke_review(llm, CorrectnessReview, messages, mode=state.review_mode) # type: ignore[assignment]
|
| 184 |
+
except Exception as exc:
|
| 185 |
+
logger.warning("Correctness review LLM call failed: %s", exc)
|
| 186 |
+
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
|
| 187 |
+
|
| 188 |
+
# Deterministic guard for a high-impact async anti-pattern that LLMs can
|
| 189 |
+
# miss: promises created by forEach are not awaited by the caller.
|
| 190 |
+
result.findings.extend(static_findings)
|
| 191 |
+
|
| 192 |
+
# --- Log and return findings ---------------------------------------------
|
| 193 |
+
if result and result.findings:
|
| 194 |
+
logger.info(
|
| 195 |
+
"Correctness review found %d issue(s)",
|
| 196 |
+
len(result.findings),
|
| 197 |
+
)
|
| 198 |
+
for f in result.findings:
|
| 199 |
+
logger.debug(
|
| 200 |
+
" [%.2f] %s:%dβ%d β %s",
|
| 201 |
+
f.confidence, f.file_path, f.line_start, f.line_end,
|
| 202 |
+
f.comment[:80],
|
| 203 |
+
)
|
| 204 |
+
else:
|
| 205 |
+
logger.info("Correctness review found no issues")
|
| 206 |
+
|
| 207 |
+
return {
|
| 208 |
+
"findings": result.findings,
|
| 209 |
+
"review_stages": [stage_result("correctness", started, llm=llm)],
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# βββ Utility βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def _human_size(bytes_: int) -> str:
|
| 217 |
+
if bytes_ < 1024:
|
| 218 |
+
return f"{bytes_} B"
|
| 219 |
+
elif bytes_ < 1024 * 1024:
|
| 220 |
+
return f"{bytes_ / 1024:.1f} KiB"
|
| 221 |
+
else:
|
| 222 |
+
return f"{bytes_ / (1024 * 1024):.1f} MiB"
|
nodes/executor.py
CHANGED
|
@@ -1,330 +1,330 @@
|
|
| 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"**Confidence:** {finding.confidence:.0%} \n\n"
|
| 164 |
-
f"{finding.comment}{fix}"
|
| 165 |
-
)
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
def _finding_fallback_body(finding: Finding) -> str:
|
| 169 |
-
"""Format a finding for a fallback issue comment when the line is stale."""
|
| 170 |
-
return (
|
| 171 |
-
f"*(This comment refers to a previous version of the code β "
|
| 172 |
-
f"the line may no longer exist in the latest diff.)*\n\n"
|
| 173 |
-
f"{_finding_body(finding)}\n\n"
|
| 174 |
-
f"**Original location:** `{finding.file_path}` "
|
| 175 |
-
f"(lines {finding.line_start}\u2013{finding.line_end})"
|
| 176 |
-
)
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
def _verdict_body(verdict_dict: dict) -> str:
|
| 180 |
-
"""Format the overall verdict as a Markdown PR comment."""
|
| 181 |
-
emoji = VERDICT_ICON.get(verdict_dict.get("recommendation", ""), "\U0001f4cb")
|
| 182 |
-
summary = verdict_dict.get("summary", "")
|
| 183 |
-
score = verdict_dict.get("overall_score", 0)
|
| 184 |
-
return (
|
| 185 |
-
f"## OpenCodeReview \u2014 {emoji} "
|
| 186 |
-
f"{verdict_dict['recommendation'].upper()}\n\n"
|
| 187 |
-
f"**Score:** {score}/10 \n"
|
| 188 |
-
f"**Summary:** {summary}\n"
|
| 189 |
-
)
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
def executor_node(state: OpenCodeReviewState) -> dict:
|
| 196 |
-
"""Post approved findings as GitHub **PR review comments** at the correct
|
| 197 |
-
file/line positions.
|
| 198 |
-
|
| 199 |
-
Workflow
|
| 200 |
-
--------
|
| 201 |
-
1. Only runs if ``state.human_approved is True``.
|
| 202 |
-
2. Fetches the latest PR head SHA every time (handles PR updates).
|
| 203 |
-
3. For each finding:
|
| 204 |
-
a. Try ``POST /pulls/{pr}/comments`` (inline review comment).
|
| 205 |
-
b. On **422** (stale line): fall back to
|
| 206 |
-
``POST /issues/{pr}/comments`` (general comment).
|
| 207 |
-
4. Posts the verdict as a general issue comment.
|
| 208 |
-
|
| 209 |
-
Requires ``GITHUB_TOKEN`` to post. Without it, logs what it *would*
|
| 210 |
-
have posted.
|
| 211 |
-
"""
|
| 212 |
-
if state.verdict and state.verdict.recommendation == "incomplete":
|
| 213 |
-
return {"posting_result": {"status": "skipped", "reason": "incomplete_review"}}
|
| 214 |
-
if not state.human_approved:
|
| 215 |
-
logger.info("Not approved \u2014 skipping executor")
|
| 216 |
-
return {"posting_result": {"status": "skipped", "reason": "not_approved"}}
|
| 217 |
-
|
| 218 |
-
_POST_ERRORS.clear()
|
| 219 |
-
|
| 220 |
-
parts = state.repo.split("/")
|
| 221 |
-
if len(parts) != 2:
|
| 222 |
-
logger.warning("Cannot post results: invalid repo '%s'", state.repo)
|
| 223 |
-
return {"posting_result": {"status": "failed", "reason": "invalid_repo"}}
|
| 224 |
-
owner, repo_name = parts
|
| 225 |
-
pr_number = state.pr_number
|
| 226 |
-
|
| 227 |
-
gh_token = os.environ.get("GITHUB_TOKEN", "").strip()
|
| 228 |
-
if not gh_token:
|
| 229 |
-
gh_token = resolve_token() or ""
|
| 230 |
-
if not gh_token:
|
| 231 |
-
logger.warning(
|
| 232 |
-
"No GitHub token available \u2014 cannot post to %s/%s#%d. "
|
| 233 |
-
"Run 'opencodereview auth login' or set GITHUB_TOKEN.",
|
| 234 |
-
owner, repo_name, pr_number,
|
| 235 |
-
)
|
| 236 |
-
if state.verdict:
|
| 237 |
-
logger.info("[WOULD POST] Verdict: %s", state.verdict.summary)
|
| 238 |
-
for f in state.final_findings:
|
| 239 |
-
logger.info(
|
| 240 |
-
"[WOULD POST] %s:%d\u2013%d %s \u2014 %s",
|
| 241 |
-
f.file_path, f.line_start, f.line_end,
|
| 242 |
-
f.severity.value, f.comment[:60],
|
| 243 |
-
)
|
| 244 |
-
return {"posting_result": {"status": "dry_run", "inline_posted": 0, "fallback_posted": 0, "failed": len(state.final_findings)}}
|
| 245 |
-
|
| 246 |
-
# ββ 1. Fetch latest head SHA βββββββββββββββββββββββββββββββββββββββββ
|
| 247 |
-
commit_id = _fetch_pr_head_sha(owner, repo_name, pr_number)
|
| 248 |
-
if commit_id is None:
|
| 249 |
-
logger.warning(
|
| 250 |
-
"Could not fetch PR head SHA \u2014 cannot post inline "
|
| 251 |
-
"comments. Falling back to issue-level comments."
|
| 252 |
-
)
|
| 253 |
-
|
| 254 |
-
# ββ 2. Post each finding βββββββββββββββββββββββββββββββββββββββββββββ
|
| 255 |
-
inline_ok = 0
|
| 256 |
-
inline_failed = 0
|
| 257 |
-
fallback_ok = 0
|
| 258 |
-
|
| 259 |
-
for f in state.final_findings:
|
| 260 |
-
body = _finding_body(f)
|
| 261 |
-
|
| 262 |
-
if commit_id:
|
| 263 |
-
# Try inline review comment
|
| 264 |
-
if f.line_start == f.line_end:
|
| 265 |
-
ok = _post_review_comment(
|
| 266 |
-
owner, repo_name, pr_number,
|
| 267 |
-
commit_id, f.file_path, f.line_start, "RIGHT", body,
|
| 268 |
-
)
|
| 269 |
-
else:
|
| 270 |
-
# Multi-line: end_line is the "line" param, start_line
|
| 271 |
-
# marks the range start.
|
| 272 |
-
ok = _post_review_comment(
|
| 273 |
-
owner, repo_name, pr_number,
|
| 274 |
-
commit_id, f.file_path, f.line_end, "RIGHT", body,
|
| 275 |
-
start_line=f.line_start,
|
| 276 |
-
)
|
| 277 |
-
|
| 278 |
-
if ok:
|
| 279 |
-
inline_ok += 1
|
| 280 |
-
continue
|
| 281 |
-
inline_failed += 1
|
| 282 |
-
|
| 283 |
-
# Fallback: issue-level comment with stale-line context
|
| 284 |
-
fallback_body = (
|
| 285 |
-
_finding_fallback_body(f) if commit_id else body
|
| 286 |
-
)
|
| 287 |
-
if _post_issue_comment(owner, repo_name, pr_number, fallback_body):
|
| 288 |
-
fallback_ok += 1
|
| 289 |
-
|
| 290 |
-
# ββ 3. Post the verdict ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 291 |
-
verdict_posted = False
|
| 292 |
-
if state.verdict:
|
| 293 |
-
verdict_body = _verdict_body(state.verdict.model_dump())
|
| 294 |
-
verdict_posted = _post_issue_comment(owner, repo_name, pr_number, verdict_body)
|
| 295 |
-
|
| 296 |
-
total = len(state.final_findings)
|
| 297 |
-
logger.info(
|
| 298 |
-
"Executor: %d/%d inline, %d/%d fallback, verdict %s \u2014 "
|
| 299 |
-
"%s/%s#%d",
|
| 300 |
-
inline_ok, total, fallback_ok, total - inline_ok,
|
| 301 |
-
"posted" if state.verdict else "skipped",
|
| 302 |
-
owner, repo_name, pr_number,
|
| 303 |
-
)
|
| 304 |
-
finding_failed = total - inline_ok - fallback_ok
|
| 305 |
-
verdict_failed = int(state.verdict is not None and not verdict_posted)
|
| 306 |
-
failed = finding_failed + verdict_failed
|
| 307 |
-
# A review is fully posted only when every finding and the verdict were
|
| 308 |
-
# accepted by GitHub. Keep the per-part counts so the API/UI can explain a
|
| 309 |
-
# partial result instead of reporting a misleading success.
|
| 310 |
-
successful_parts = inline_ok + fallback_ok + int(verdict_posted)
|
| 311 |
-
expected_parts = total + int(state.verdict is not None)
|
| 312 |
-
if expected_parts == 0:
|
| 313 |
-
status = "posted"
|
| 314 |
-
elif successful_parts == expected_parts:
|
| 315 |
-
status = "posted"
|
| 316 |
-
elif successful_parts:
|
| 317 |
-
status = "partially_posted"
|
| 318 |
-
else:
|
| 319 |
-
status = "post_failed"
|
| 320 |
-
return {"posting_result": {
|
| 321 |
-
"status": status,
|
| 322 |
-
"total_findings": total,
|
| 323 |
-
"inline_posted": inline_ok,
|
| 324 |
-
"fallback_posted": fallback_ok,
|
| 325 |
-
"failed": failed,
|
| 326 |
-
"finding_failed": finding_failed,
|
| 327 |
-
"verdict_failed": verdict_failed,
|
| 328 |
-
"verdict_posted": verdict_posted,
|
| 329 |
-
"errors": list(_POST_ERRORS),
|
| 330 |
-
}}
|
|
|
|
| 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"**Confidence:** {finding.confidence:.0%} \n\n"
|
| 164 |
+
f"{finding.comment}{fix}"
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _finding_fallback_body(finding: Finding) -> str:
|
| 169 |
+
"""Format a finding for a fallback issue comment when the line is stale."""
|
| 170 |
+
return (
|
| 171 |
+
f"*(This comment refers to a previous version of the code β "
|
| 172 |
+
f"the line may no longer exist in the latest diff.)*\n\n"
|
| 173 |
+
f"{_finding_body(finding)}\n\n"
|
| 174 |
+
f"**Original location:** `{finding.file_path}` "
|
| 175 |
+
f"(lines {finding.line_start}\u2013{finding.line_end})"
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _verdict_body(verdict_dict: dict) -> str:
|
| 180 |
+
"""Format the overall verdict as a Markdown PR comment."""
|
| 181 |
+
emoji = VERDICT_ICON.get(verdict_dict.get("recommendation", ""), "\U0001f4cb")
|
| 182 |
+
summary = verdict_dict.get("summary", "")
|
| 183 |
+
score = verdict_dict.get("overall_score", 0)
|
| 184 |
+
return (
|
| 185 |
+
f"## OpenCodeReview \u2014 {emoji} "
|
| 186 |
+
f"{verdict_dict['recommendation'].upper()}\n\n"
|
| 187 |
+
f"**Score:** {score}/10 \n"
|
| 188 |
+
f"**Summary:** {summary}\n"
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def executor_node(state: OpenCodeReviewState) -> dict:
|
| 196 |
+
"""Post approved findings as GitHub **PR review comments** at the correct
|
| 197 |
+
file/line positions.
|
| 198 |
+
|
| 199 |
+
Workflow
|
| 200 |
+
--------
|
| 201 |
+
1. Only runs if ``state.human_approved is True``.
|
| 202 |
+
2. Fetches the latest PR head SHA every time (handles PR updates).
|
| 203 |
+
3. For each finding:
|
| 204 |
+
a. Try ``POST /pulls/{pr}/comments`` (inline review comment).
|
| 205 |
+
b. On **422** (stale line): fall back to
|
| 206 |
+
``POST /issues/{pr}/comments`` (general comment).
|
| 207 |
+
4. Posts the verdict as a general issue comment.
|
| 208 |
+
|
| 209 |
+
Requires ``GITHUB_TOKEN`` to post. Without it, logs what it *would*
|
| 210 |
+
have posted.
|
| 211 |
+
"""
|
| 212 |
+
if state.verdict and state.verdict.recommendation == "incomplete":
|
| 213 |
+
return {"posting_result": {"status": "skipped", "reason": "incomplete_review"}}
|
| 214 |
+
if not state.human_approved:
|
| 215 |
+
logger.info("Not approved \u2014 skipping executor")
|
| 216 |
+
return {"posting_result": {"status": "skipped", "reason": "not_approved"}}
|
| 217 |
+
|
| 218 |
+
_POST_ERRORS.clear()
|
| 219 |
+
|
| 220 |
+
parts = state.repo.split("/")
|
| 221 |
+
if len(parts) != 2:
|
| 222 |
+
logger.warning("Cannot post results: invalid repo '%s'", state.repo)
|
| 223 |
+
return {"posting_result": {"status": "failed", "reason": "invalid_repo"}}
|
| 224 |
+
owner, repo_name = parts
|
| 225 |
+
pr_number = state.pr_number
|
| 226 |
+
|
| 227 |
+
gh_token = os.environ.get("GITHUB_TOKEN", "").strip()
|
| 228 |
+
if not gh_token:
|
| 229 |
+
gh_token = resolve_token() or ""
|
| 230 |
+
if not gh_token:
|
| 231 |
+
logger.warning(
|
| 232 |
+
"No GitHub token available \u2014 cannot post to %s/%s#%d. "
|
| 233 |
+
"Run 'opencodereview auth login' or set GITHUB_TOKEN.",
|
| 234 |
+
owner, repo_name, pr_number,
|
| 235 |
+
)
|
| 236 |
+
if state.verdict:
|
| 237 |
+
logger.info("[WOULD POST] Verdict: %s", state.verdict.summary)
|
| 238 |
+
for f in state.final_findings:
|
| 239 |
+
logger.info(
|
| 240 |
+
"[WOULD POST] %s:%d\u2013%d %s \u2014 %s",
|
| 241 |
+
f.file_path, f.line_start, f.line_end,
|
| 242 |
+
f.severity.value, f.comment[:60],
|
| 243 |
+
)
|
| 244 |
+
return {"posting_result": {"status": "dry_run", "inline_posted": 0, "fallback_posted": 0, "failed": len(state.final_findings)}}
|
| 245 |
+
|
| 246 |
+
# ββ 1. Fetch latest head SHA βββββββββββββββββββββββββββββββββββββββββ
|
| 247 |
+
commit_id = _fetch_pr_head_sha(owner, repo_name, pr_number)
|
| 248 |
+
if commit_id is None:
|
| 249 |
+
logger.warning(
|
| 250 |
+
"Could not fetch PR head SHA \u2014 cannot post inline "
|
| 251 |
+
"comments. Falling back to issue-level comments."
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
# ββ 2. Post each finding βββββββββββββββββββββββββββββββββββββββββββββ
|
| 255 |
+
inline_ok = 0
|
| 256 |
+
inline_failed = 0
|
| 257 |
+
fallback_ok = 0
|
| 258 |
+
|
| 259 |
+
for f in state.final_findings:
|
| 260 |
+
body = _finding_body(f)
|
| 261 |
+
|
| 262 |
+
if commit_id:
|
| 263 |
+
# Try inline review comment
|
| 264 |
+
if f.line_start == f.line_end:
|
| 265 |
+
ok = _post_review_comment(
|
| 266 |
+
owner, repo_name, pr_number,
|
| 267 |
+
commit_id, f.file_path, f.line_start, "RIGHT", body,
|
| 268 |
+
)
|
| 269 |
+
else:
|
| 270 |
+
# Multi-line: end_line is the "line" param, start_line
|
| 271 |
+
# marks the range start.
|
| 272 |
+
ok = _post_review_comment(
|
| 273 |
+
owner, repo_name, pr_number,
|
| 274 |
+
commit_id, f.file_path, f.line_end, "RIGHT", body,
|
| 275 |
+
start_line=f.line_start,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
if ok:
|
| 279 |
+
inline_ok += 1
|
| 280 |
+
continue
|
| 281 |
+
inline_failed += 1
|
| 282 |
+
|
| 283 |
+
# Fallback: issue-level comment with stale-line context
|
| 284 |
+
fallback_body = (
|
| 285 |
+
_finding_fallback_body(f) if commit_id else body
|
| 286 |
+
)
|
| 287 |
+
if _post_issue_comment(owner, repo_name, pr_number, fallback_body):
|
| 288 |
+
fallback_ok += 1
|
| 289 |
+
|
| 290 |
+
# ββ 3. Post the verdict ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 291 |
+
verdict_posted = False
|
| 292 |
+
if state.verdict:
|
| 293 |
+
verdict_body = _verdict_body(state.verdict.model_dump())
|
| 294 |
+
verdict_posted = _post_issue_comment(owner, repo_name, pr_number, verdict_body)
|
| 295 |
+
|
| 296 |
+
total = len(state.final_findings)
|
| 297 |
+
logger.info(
|
| 298 |
+
"Executor: %d/%d inline, %d/%d fallback, verdict %s \u2014 "
|
| 299 |
+
"%s/%s#%d",
|
| 300 |
+
inline_ok, total, fallback_ok, total - inline_ok,
|
| 301 |
+
"posted" if state.verdict else "skipped",
|
| 302 |
+
owner, repo_name, pr_number,
|
| 303 |
+
)
|
| 304 |
+
finding_failed = total - inline_ok - fallback_ok
|
| 305 |
+
verdict_failed = int(state.verdict is not None and not verdict_posted)
|
| 306 |
+
failed = finding_failed + verdict_failed
|
| 307 |
+
# A review is fully posted only when every finding and the verdict were
|
| 308 |
+
# accepted by GitHub. Keep the per-part counts so the API/UI can explain a
|
| 309 |
+
# partial result instead of reporting a misleading success.
|
| 310 |
+
successful_parts = inline_ok + fallback_ok + int(verdict_posted)
|
| 311 |
+
expected_parts = total + int(state.verdict is not None)
|
| 312 |
+
if expected_parts == 0:
|
| 313 |
+
status = "posted"
|
| 314 |
+
elif successful_parts == expected_parts:
|
| 315 |
+
status = "posted"
|
| 316 |
+
elif successful_parts:
|
| 317 |
+
status = "partially_posted"
|
| 318 |
+
else:
|
| 319 |
+
status = "post_failed"
|
| 320 |
+
return {"posting_result": {
|
| 321 |
+
"status": status,
|
| 322 |
+
"total_findings": total,
|
| 323 |
+
"inline_posted": inline_ok,
|
| 324 |
+
"fallback_posted": fallback_ok,
|
| 325 |
+
"failed": failed,
|
| 326 |
+
"finding_failed": finding_failed,
|
| 327 |
+
"verdict_failed": verdict_failed,
|
| 328 |
+
"verdict_posted": verdict_posted,
|
| 329 |
+
"errors": list(_POST_ERRORS),
|
| 330 |
+
}}
|
nodes/human_approval.py
CHANGED
|
@@ -1,91 +1,91 @@
|
|
| 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 |
-
}
|
| 70 |
-
for f in findings
|
| 71 |
-
],
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
# This call blocks the graph until the human provides input via resume.
|
| 75 |
-
# The return value is whatever was passed to `Command(resume=...)`.
|
| 76 |
-
human_input: dict = interrupt(interrupt_payload)
|
| 77 |
-
|
| 78 |
-
action: ApprovalAction = human_input.get("action", "reject")
|
| 79 |
-
logger.info("Human decision: %s", action)
|
| 80 |
-
|
| 81 |
-
if action == "reject":
|
| 82 |
-
logger.info("Review rejected by human β no comments will be posted.")
|
| 83 |
-
|
| 84 |
-
if action == "edit":
|
| 85 |
-
edited_findings_raw = human_input.get("findings")
|
| 86 |
-
if edited_findings_raw:
|
| 87 |
-
logger.info("Human edited %d findings before approval.", len(edited_findings_raw))
|
| 88 |
-
|
| 89 |
-
return {
|
| 90 |
-
"human_approved": (action in {"approve", "edit"}) and not (verdict and verdict.recommendation == "incomplete"),
|
| 91 |
-
}
|
|
|
|
| 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 |
+
}
|
| 70 |
+
for f in findings
|
| 71 |
+
],
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
# This call blocks the graph until the human provides input via resume.
|
| 75 |
+
# The return value is whatever was passed to `Command(resume=...)`.
|
| 76 |
+
human_input: dict = interrupt(interrupt_payload)
|
| 77 |
+
|
| 78 |
+
action: ApprovalAction = human_input.get("action", "reject")
|
| 79 |
+
logger.info("Human decision: %s", action)
|
| 80 |
+
|
| 81 |
+
if action == "reject":
|
| 82 |
+
logger.info("Review rejected by human β no comments will be posted.")
|
| 83 |
+
|
| 84 |
+
if action == "edit":
|
| 85 |
+
edited_findings_raw = human_input.get("findings")
|
| 86 |
+
if edited_findings_raw:
|
| 87 |
+
logger.info("Human edited %d findings before approval.", len(edited_findings_raw))
|
| 88 |
+
|
| 89 |
+
return {
|
| 90 |
+
"human_approved": (action in {"approve", "edit"}) and not (verdict and verdict.recommendation == "incomplete"),
|
| 91 |
+
}
|
nodes/ingestion.py
CHANGED
|
@@ -1,228 +1,228 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 4 |
-
import logging
|
| 5 |
-
import time
|
| 6 |
-
from typing import Optional
|
| 7 |
-
|
| 8 |
-
import requests
|
| 9 |
-
|
| 10 |
-
from github_client import GitHubSession, resolve_token
|
| 11 |
-
from state import ChangedFile, OpenCodeReviewState
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
logger = logging.getLogger(__name__)
|
| 15 |
-
|
| 16 |
-
GITHUB_API_BASE = "https://api.github.com"
|
| 17 |
-
RAW_CONTENT_BASE = "https://raw.githubusercontent.com"
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
# βββ Custom Exception ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
class IngestionError(Exception):
|
| 24 |
-
"""Raised when PR data ingestion fails and the graph cannot continue."""
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
def _check_rate_limit(response: requests.Response) -> None:
|
| 28 |
-
"""Raise ``IngestionError`` if the API quota is exhausted."""
|
| 29 |
-
remaining = response.headers.get("X-RateLimit-Remaining")
|
| 30 |
-
if remaining is not None and int(remaining) == 0:
|
| 31 |
-
reset_ts = int(response.headers.get("X-RateLimit-Reset", "0"))
|
| 32 |
-
reset_at = time.strftime("%H:%M:%S UTC", time.gmtime(reset_ts))
|
| 33 |
-
raise IngestionError(
|
| 34 |
-
f"GitHub API rate limit exhausted β resets at {reset_at}. "
|
| 35 |
-
"Set the GITHUB_TOKEN environment variable for a much higher limit."
|
| 36 |
-
)
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def _parse_owner_repo(repo: str) -> tuple[str, str]:
|
| 40 |
-
"""Split ``owner/repo`` returning ``(owner, repo)``."""
|
| 41 |
-
parts = repo.split("/")
|
| 42 |
-
if len(parts) != 2 or not all(parts):
|
| 43 |
-
raise IngestionError(
|
| 44 |
-
f"Invalid repo format: '{repo}'. Expected 'owner/repo' "
|
| 45 |
-
"(e.g. 'psf/requests')."
|
| 46 |
-
)
|
| 47 |
-
return parts[0], parts[1]
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
def _fetch_all_pages(url: str, session: requests.Session) -> list[dict]:
|
| 51 |
-
"""Follow ``Link``-header pagination and return every result item.
|
| 52 |
-
|
| 53 |
-
Uses the provided ``session`` (should be a :class:`GitHubSession`) so
|
| 54 |
-
that 401 handling and auth headers are applied automatically.
|
| 55 |
-
"""
|
| 56 |
-
items: list[dict] = []
|
| 57 |
-
while url:
|
| 58 |
-
resp = session.get(url, timeout=30)
|
| 59 |
-
resp.raise_for_status()
|
| 60 |
-
items.extend(resp.json())
|
| 61 |
-
|
| 62 |
-
link_header = resp.headers.get("Link", "")
|
| 63 |
-
next_url: Optional[str] = None
|
| 64 |
-
for part in link_header.split(","):
|
| 65 |
-
part = part.strip()
|
| 66 |
-
if 'rel="next"' in part:
|
| 67 |
-
start = part.index("<") + 1
|
| 68 |
-
end = part.index(">")
|
| 69 |
-
next_url = part[start:end]
|
| 70 |
-
break
|
| 71 |
-
url = next_url
|
| 72 |
-
return items
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def _fetch_file_content(
|
| 76 |
-
owner: str, repo: str, ref: str, path: str, status: str
|
| 77 |
-
) -> str:
|
| 78 |
-
"""Return the full file content from the head branch of the PR.
|
| 79 |
-
|
| 80 |
-
Deleted/removed files return an empty string. Binary files that fail to
|
| 81 |
-
fetch also return an empty string with a warning.
|
| 82 |
-
"""
|
| 83 |
-
if status == "removed":
|
| 84 |
-
return ""
|
| 85 |
-
|
| 86 |
-
url = f"{RAW_CONTENT_BASE}/{owner}/{repo}/{ref}/{path}"
|
| 87 |
-
try:
|
| 88 |
-
resp = requests.get(url, timeout=30)
|
| 89 |
-
if resp.status_code == 404:
|
| 90 |
-
logger.warning("Content not found at %s (may have been deleted/renamed)", path)
|
| 91 |
-
return ""
|
| 92 |
-
resp.raise_for_status()
|
| 93 |
-
return resp.text
|
| 94 |
-
except requests.exceptions.RequestException as exc:
|
| 95 |
-
logger.warning("Could not fetch content for %s: %s", path, exc)
|
| 96 |
-
return ""
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
def ingestion_node(state: OpenCodeReviewState) -> dict:
|
| 103 |
-
"""Fetch PR metadata, diff, and changed-file contents from the GitHub API.
|
| 104 |
-
|
| 105 |
-
Requires ``state.repo`` (``"owner/repo"``) and ``state.pr_number`` to be
|
| 106 |
-
set. Returns updates for ``diff`` and ``changed_files``.
|
| 107 |
-
|
| 108 |
-
If ``state.diff`` is already populated (e.g. in tests with a synthetic
|
| 109 |
-
payload) the node is a no-op.
|
| 110 |
-
"""
|
| 111 |
-
# --- Early exit when data is already present (e.g. synthetic payloads) ----
|
| 112 |
-
if state.diff:
|
| 113 |
-
logger.info("PR data already populated β skipping ingestion")
|
| 114 |
-
return {}
|
| 115 |
-
|
| 116 |
-
# ββ Token check before any API calls βββββββββββββββββββββββββββββββββ
|
| 117 |
-
if not resolve_token():
|
| 118 |
-
raise IngestionError(
|
| 119 |
-
"No GitHub token found. OpenCodeReview needs a GitHub token to "
|
| 120 |
-
"fetch PR data.\n\n"
|
| 121 |
-
" Authenticate via GitHub OAuth (recommended):\n"
|
| 122 |
-
" opencodereview auth login\n\n"
|
| 123 |
-
" Or set the GITHUB_TOKEN environment variable:\n"
|
| 124 |
-
" export GITHUB_TOKEN=\"ghp_...\"\n"
|
| 125 |
-
)
|
| 126 |
-
|
| 127 |
-
owner, repo_name = _parse_owner_repo(state.repo)
|
| 128 |
-
pr_number = state.pr_number
|
| 129 |
-
|
| 130 |
-
logger.info("Ingesting PR %s/%s#%d β¦", owner, repo_name, pr_number)
|
| 131 |
-
|
| 132 |
-
# Use GitHubSession for automatic auth + 401 interception
|
| 133 |
-
session = GitHubSession()
|
| 134 |
-
|
| 135 |
-
# -- 1. PR metadata (to obtain the head SHA for content URLs) -------------
|
| 136 |
-
pr_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/pulls/{pr_number}"
|
| 137 |
-
pr_resp = session.get(pr_url, timeout=30)
|
| 138 |
-
|
| 139 |
-
if pr_resp.status_code == 404:
|
| 140 |
-
raise IngestionError(
|
| 141 |
-
f"PR {owner}/{repo_name}#{pr_number} was not found."
|
| 142 |
-
)
|
| 143 |
-
if pr_resp.status_code in (403, 401):
|
| 144 |
-
_check_rate_limit(pr_resp)
|
| 145 |
-
raise IngestionError(
|
| 146 |
-
f"Access denied to {owner}/{repo_name}#{pr_number}. "
|
| 147 |
-
"If the repo is private, set a valid GITHUB_TOKEN."
|
| 148 |
-
)
|
| 149 |
-
if pr_resp.status_code == 410:
|
| 150 |
-
raise IngestionError(
|
| 151 |
-
f"PR {owner}/{repo_name}#{pr_number} has been deleted."
|
| 152 |
-
)
|
| 153 |
-
pr_resp.raise_for_status()
|
| 154 |
-
|
| 155 |
-
pr_data = pr_resp.json()
|
| 156 |
-
head_sha = pr_data["head"]["sha"]
|
| 157 |
-
head_ref = pr_data["head"]["ref"]
|
| 158 |
-
base_sha = pr_data["base"]["sha"]
|
| 159 |
-
base_ref = pr_data["base"]["ref"]
|
| 160 |
-
|
| 161 |
-
logger.info(
|
| 162 |
-
"PR #%d β %s β %s β %s (%s)",
|
| 163 |
-
pr_number, pr_data.get("title", "(no title)"),
|
| 164 |
-
base_ref, head_ref, head_sha[:7],
|
| 165 |
-
)
|
| 166 |
-
|
| 167 |
-
# -- 2. Determine where to fetch file content -----------------------------
|
| 168 |
-
# For PRs from forks, the head SHA lives in the fork, not the base repo.
|
| 169 |
-
head_repo_full: str = pr_data["head"]["repo"]["full_name"] # "owner/repo"
|
| 170 |
-
head_owner, head_repo_n = head_repo_full.split("/", 1)
|
| 171 |
-
|
| 172 |
-
# Explicit incremental previews compare immutable commits. Reject truncated
|
| 173 |
-
# comparisons rather than silently reporting a partial review as complete.
|
| 174 |
-
baseline = getattr(state, "incremental_base_sha", "")
|
| 175 |
-
if baseline:
|
| 176 |
-
compare_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/compare/{baseline}...{head_sha}"
|
| 177 |
-
comparison = session.get(compare_url, timeout=30)
|
| 178 |
-
comparison.raise_for_status()
|
| 179 |
-
compared = comparison.json()
|
| 180 |
-
if compared.get("status") not in {"ahead", "identical"}:
|
| 181 |
-
raise IngestionError("Incremental baseline must be an ancestor of the PR head.")
|
| 182 |
-
files_data = compared.get("files", [])
|
| 183 |
-
if len(files_data) >= 300 or compared.get("total_commits", 0) > 250:
|
| 184 |
-
raise IngestionError("Incremental comparison may be truncated; run a full review.")
|
| 185 |
-
diff_url = compare_url
|
| 186 |
-
else:
|
| 187 |
-
diff_url = pr_url
|
| 188 |
-
files_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/pulls/{pr_number}/files"
|
| 189 |
-
files_data = _fetch_all_pages(files_url, session)
|
| 190 |
-
diff_resp = session.get(diff_url, headers={"Accept": "application/vnd.github.v3.diff"}, timeout=30)
|
| 191 |
-
diff_resp.raise_for_status()
|
| 192 |
-
diff_text = diff_resp.text
|
| 193 |
-
logger.info("Fetched %s diff (%s), %d files", "incremental" if baseline else "full", _human_size(len(diff_text)), len(files_data))
|
| 194 |
-
|
| 195 |
-
# -- 5. Build ChangedFile objects (full content from the head branch) -----
|
| 196 |
-
def load_file(file_info: dict) -> ChangedFile:
|
| 197 |
-
path = file_info["filename"]
|
| 198 |
-
status = file_info["status"]
|
| 199 |
-
return ChangedFile(
|
| 200 |
-
path=path, status=status,
|
| 201 |
-
content=_fetch_file_content(head_owner, head_repo_n, head_sha, path, status),
|
| 202 |
-
diff_hunk=file_info.get("patch") or "",
|
| 203 |
-
)
|
| 204 |
-
|
| 205 |
-
# Independent raw-file GETs use separate requests, preserve GitHub file order,
|
| 206 |
-
# and cap concurrency to avoid flooding the upstream service.
|
| 207 |
-
with ThreadPoolExecutor(max_workers=4) as pool:
|
| 208 |
-
changed_files = list(pool.map(load_file, files_data))
|
| 209 |
-
|
| 210 |
-
return {
|
| 211 |
-
"diff": diff_text,
|
| 212 |
-
"changed_files": changed_files,
|
| 213 |
-
"base_sha": base_sha,
|
| 214 |
-
"head_sha": head_sha,
|
| 215 |
-
}
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
# βββ Utility βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
def _human_size(bytes_: int) -> str:
|
| 222 |
-
"""Return a short human-readable string for a byte count."""
|
| 223 |
-
if bytes_ < 1024:
|
| 224 |
-
return f"{bytes_} B"
|
| 225 |
-
elif bytes_ < 1024 * 1024:
|
| 226 |
-
return f"{bytes_ / 1024:.1f} KiB"
|
| 227 |
-
else:
|
| 228 |
-
return f"{bytes_ / (1024 * 1024):.1f} MiB"
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 4 |
+
import logging
|
| 5 |
+
import time
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
import requests
|
| 9 |
+
|
| 10 |
+
from github_client import GitHubSession, resolve_token
|
| 11 |
+
from state import ChangedFile, OpenCodeReviewState
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
GITHUB_API_BASE = "https://api.github.com"
|
| 17 |
+
RAW_CONTENT_BASE = "https://raw.githubusercontent.com"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# βββ Custom Exception ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class IngestionError(Exception):
|
| 24 |
+
"""Raised when PR data ingestion fails and the graph cannot continue."""
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _check_rate_limit(response: requests.Response) -> None:
|
| 28 |
+
"""Raise ``IngestionError`` if the API quota is exhausted."""
|
| 29 |
+
remaining = response.headers.get("X-RateLimit-Remaining")
|
| 30 |
+
if remaining is not None and int(remaining) == 0:
|
| 31 |
+
reset_ts = int(response.headers.get("X-RateLimit-Reset", "0"))
|
| 32 |
+
reset_at = time.strftime("%H:%M:%S UTC", time.gmtime(reset_ts))
|
| 33 |
+
raise IngestionError(
|
| 34 |
+
f"GitHub API rate limit exhausted β resets at {reset_at}. "
|
| 35 |
+
"Set the GITHUB_TOKEN environment variable for a much higher limit."
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _parse_owner_repo(repo: str) -> tuple[str, str]:
|
| 40 |
+
"""Split ``owner/repo`` returning ``(owner, repo)``."""
|
| 41 |
+
parts = repo.split("/")
|
| 42 |
+
if len(parts) != 2 or not all(parts):
|
| 43 |
+
raise IngestionError(
|
| 44 |
+
f"Invalid repo format: '{repo}'. Expected 'owner/repo' "
|
| 45 |
+
"(e.g. 'psf/requests')."
|
| 46 |
+
)
|
| 47 |
+
return parts[0], parts[1]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _fetch_all_pages(url: str, session: requests.Session) -> list[dict]:
|
| 51 |
+
"""Follow ``Link``-header pagination and return every result item.
|
| 52 |
+
|
| 53 |
+
Uses the provided ``session`` (should be a :class:`GitHubSession`) so
|
| 54 |
+
that 401 handling and auth headers are applied automatically.
|
| 55 |
+
"""
|
| 56 |
+
items: list[dict] = []
|
| 57 |
+
while url:
|
| 58 |
+
resp = session.get(url, timeout=30)
|
| 59 |
+
resp.raise_for_status()
|
| 60 |
+
items.extend(resp.json())
|
| 61 |
+
|
| 62 |
+
link_header = resp.headers.get("Link", "")
|
| 63 |
+
next_url: Optional[str] = None
|
| 64 |
+
for part in link_header.split(","):
|
| 65 |
+
part = part.strip()
|
| 66 |
+
if 'rel="next"' in part:
|
| 67 |
+
start = part.index("<") + 1
|
| 68 |
+
end = part.index(">")
|
| 69 |
+
next_url = part[start:end]
|
| 70 |
+
break
|
| 71 |
+
url = next_url
|
| 72 |
+
return items
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _fetch_file_content(
|
| 76 |
+
owner: str, repo: str, ref: str, path: str, status: str
|
| 77 |
+
) -> str:
|
| 78 |
+
"""Return the full file content from the head branch of the PR.
|
| 79 |
+
|
| 80 |
+
Deleted/removed files return an empty string. Binary files that fail to
|
| 81 |
+
fetch also return an empty string with a warning.
|
| 82 |
+
"""
|
| 83 |
+
if status == "removed":
|
| 84 |
+
return ""
|
| 85 |
+
|
| 86 |
+
url = f"{RAW_CONTENT_BASE}/{owner}/{repo}/{ref}/{path}"
|
| 87 |
+
try:
|
| 88 |
+
resp = requests.get(url, timeout=30)
|
| 89 |
+
if resp.status_code == 404:
|
| 90 |
+
logger.warning("Content not found at %s (may have been deleted/renamed)", path)
|
| 91 |
+
return ""
|
| 92 |
+
resp.raise_for_status()
|
| 93 |
+
return resp.text
|
| 94 |
+
except requests.exceptions.RequestException as exc:
|
| 95 |
+
logger.warning("Could not fetch content for %s: %s", path, exc)
|
| 96 |
+
return ""
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def ingestion_node(state: OpenCodeReviewState) -> dict:
|
| 103 |
+
"""Fetch PR metadata, diff, and changed-file contents from the GitHub API.
|
| 104 |
+
|
| 105 |
+
Requires ``state.repo`` (``"owner/repo"``) and ``state.pr_number`` to be
|
| 106 |
+
set. Returns updates for ``diff`` and ``changed_files``.
|
| 107 |
+
|
| 108 |
+
If ``state.diff`` is already populated (e.g. in tests with a synthetic
|
| 109 |
+
payload) the node is a no-op.
|
| 110 |
+
"""
|
| 111 |
+
# --- Early exit when data is already present (e.g. synthetic payloads) ----
|
| 112 |
+
if state.diff:
|
| 113 |
+
logger.info("PR data already populated β skipping ingestion")
|
| 114 |
+
return {}
|
| 115 |
+
|
| 116 |
+
# ββ Token check before any API calls βββββββββββββββββββββββββββββββββ
|
| 117 |
+
if not resolve_token():
|
| 118 |
+
raise IngestionError(
|
| 119 |
+
"No GitHub token found. OpenCodeReview needs a GitHub token to "
|
| 120 |
+
"fetch PR data.\n\n"
|
| 121 |
+
" Authenticate via GitHub OAuth (recommended):\n"
|
| 122 |
+
" opencodereview auth login\n\n"
|
| 123 |
+
" Or set the GITHUB_TOKEN environment variable:\n"
|
| 124 |
+
" export GITHUB_TOKEN=\"ghp_...\"\n"
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
owner, repo_name = _parse_owner_repo(state.repo)
|
| 128 |
+
pr_number = state.pr_number
|
| 129 |
+
|
| 130 |
+
logger.info("Ingesting PR %s/%s#%d β¦", owner, repo_name, pr_number)
|
| 131 |
+
|
| 132 |
+
# Use GitHubSession for automatic auth + 401 interception
|
| 133 |
+
session = GitHubSession()
|
| 134 |
+
|
| 135 |
+
# -- 1. PR metadata (to obtain the head SHA for content URLs) -------------
|
| 136 |
+
pr_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/pulls/{pr_number}"
|
| 137 |
+
pr_resp = session.get(pr_url, timeout=30)
|
| 138 |
+
|
| 139 |
+
if pr_resp.status_code == 404:
|
| 140 |
+
raise IngestionError(
|
| 141 |
+
f"PR {owner}/{repo_name}#{pr_number} was not found."
|
| 142 |
+
)
|
| 143 |
+
if pr_resp.status_code in (403, 401):
|
| 144 |
+
_check_rate_limit(pr_resp)
|
| 145 |
+
raise IngestionError(
|
| 146 |
+
f"Access denied to {owner}/{repo_name}#{pr_number}. "
|
| 147 |
+
"If the repo is private, set a valid GITHUB_TOKEN."
|
| 148 |
+
)
|
| 149 |
+
if pr_resp.status_code == 410:
|
| 150 |
+
raise IngestionError(
|
| 151 |
+
f"PR {owner}/{repo_name}#{pr_number} has been deleted."
|
| 152 |
+
)
|
| 153 |
+
pr_resp.raise_for_status()
|
| 154 |
+
|
| 155 |
+
pr_data = pr_resp.json()
|
| 156 |
+
head_sha = pr_data["head"]["sha"]
|
| 157 |
+
head_ref = pr_data["head"]["ref"]
|
| 158 |
+
base_sha = pr_data["base"]["sha"]
|
| 159 |
+
base_ref = pr_data["base"]["ref"]
|
| 160 |
+
|
| 161 |
+
logger.info(
|
| 162 |
+
"PR #%d β %s β %s β %s (%s)",
|
| 163 |
+
pr_number, pr_data.get("title", "(no title)"),
|
| 164 |
+
base_ref, head_ref, head_sha[:7],
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# -- 2. Determine where to fetch file content -----------------------------
|
| 168 |
+
# For PRs from forks, the head SHA lives in the fork, not the base repo.
|
| 169 |
+
head_repo_full: str = pr_data["head"]["repo"]["full_name"] # "owner/repo"
|
| 170 |
+
head_owner, head_repo_n = head_repo_full.split("/", 1)
|
| 171 |
+
|
| 172 |
+
# Explicit incremental previews compare immutable commits. Reject truncated
|
| 173 |
+
# comparisons rather than silently reporting a partial review as complete.
|
| 174 |
+
baseline = getattr(state, "incremental_base_sha", "")
|
| 175 |
+
if baseline:
|
| 176 |
+
compare_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/compare/{baseline}...{head_sha}"
|
| 177 |
+
comparison = session.get(compare_url, timeout=30)
|
| 178 |
+
comparison.raise_for_status()
|
| 179 |
+
compared = comparison.json()
|
| 180 |
+
if compared.get("status") not in {"ahead", "identical"}:
|
| 181 |
+
raise IngestionError("Incremental baseline must be an ancestor of the PR head.")
|
| 182 |
+
files_data = compared.get("files", [])
|
| 183 |
+
if len(files_data) >= 300 or compared.get("total_commits", 0) > 250:
|
| 184 |
+
raise IngestionError("Incremental comparison may be truncated; run a full review.")
|
| 185 |
+
diff_url = compare_url
|
| 186 |
+
else:
|
| 187 |
+
diff_url = pr_url
|
| 188 |
+
files_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/pulls/{pr_number}/files"
|
| 189 |
+
files_data = _fetch_all_pages(files_url, session)
|
| 190 |
+
diff_resp = session.get(diff_url, headers={"Accept": "application/vnd.github.v3.diff"}, timeout=30)
|
| 191 |
+
diff_resp.raise_for_status()
|
| 192 |
+
diff_text = diff_resp.text
|
| 193 |
+
logger.info("Fetched %s diff (%s), %d files", "incremental" if baseline else "full", _human_size(len(diff_text)), len(files_data))
|
| 194 |
+
|
| 195 |
+
# -- 5. Build ChangedFile objects (full content from the head branch) -----
|
| 196 |
+
def load_file(file_info: dict) -> ChangedFile:
|
| 197 |
+
path = file_info["filename"]
|
| 198 |
+
status = file_info["status"]
|
| 199 |
+
return ChangedFile(
|
| 200 |
+
path=path, status=status,
|
| 201 |
+
content=_fetch_file_content(head_owner, head_repo_n, head_sha, path, status),
|
| 202 |
+
diff_hunk=file_info.get("patch") or "",
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
# Independent raw-file GETs use separate requests, preserve GitHub file order,
|
| 206 |
+
# and cap concurrency to avoid flooding the upstream service.
|
| 207 |
+
with ThreadPoolExecutor(max_workers=4) as pool:
|
| 208 |
+
changed_files = list(pool.map(load_file, files_data))
|
| 209 |
+
|
| 210 |
+
return {
|
| 211 |
+
"diff": diff_text,
|
| 212 |
+
"changed_files": changed_files,
|
| 213 |
+
"base_sha": base_sha,
|
| 214 |
+
"head_sha": head_sha,
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# βββ Utility βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _human_size(bytes_: int) -> str:
|
| 222 |
+
"""Return a short human-readable string for a byte count."""
|
| 223 |
+
if bytes_ < 1024:
|
| 224 |
+
return f"{bytes_} B"
|
| 225 |
+
elif bytes_ < 1024 * 1024:
|
| 226 |
+
return f"{bytes_ / 1024:.1f} KiB"
|
| 227 |
+
else:
|
| 228 |
+
return f"{bytes_ / (1024 * 1024):.1f} MiB"
|
nodes/review_runtime.py
CHANGED
|
@@ -1,81 +1,81 @@
|
|
| 1 |
-
"""Bound reviewer latency and validate provider responses without hiding failures."""
|
| 2 |
-
from __future__ import annotations
|
| 3 |
-
|
| 4 |
-
from contextvars import copy_context
|
| 5 |
-
import json
|
| 6 |
-
import os
|
| 7 |
-
import queue
|
| 8 |
-
import re
|
| 9 |
-
import threading
|
| 10 |
-
import time
|
| 11 |
-
|
| 12 |
-
from pydantic import ValidationError
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def changed_context(changed_file, mode):
|
| 16 |
-
"""Fast mode includes numbered windows around changes, not repeated whole files."""
|
| 17 |
-
content = changed_file.content or ''
|
| 18 |
-
if mode != 'fast' or not changed_file.diff_hunk:
|
| 19 |
-
return content
|
| 20 |
-
lines = content.splitlines()
|
| 21 |
-
selected = set()
|
| 22 |
-
for start, count in re.findall(r'@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@', changed_file.diff_hunk):
|
| 23 |
-
first = max(0, int(start) - 1)
|
| 24 |
-
selected.update(range(max(0, first - 12), min(len(lines), first + int(count or 1) + 12)))
|
| 25 |
-
return '\n'.join(f'{index + 1}: {lines[index]}' for index in sorted(selected)) if selected else content
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def invoke_review(llm, schema, messages, mode="thorough"):
|
| 29 |
-
"""One request plus one format repair, within a total wall-clock budget.
|
| 30 |
-
|
| 31 |
-
A daemon worker makes the caller deadline effective even with a provider
|
| 32 |
-
SDK that ignores its native request timeout. Native timeouts still close
|
| 33 |
-
underlying connections; timed-out workers never modify graph state.
|
| 34 |
-
"""
|
| 35 |
-
budget = float(os.getenv("OCR_REVIEWER_TIMEOUT_SECONDS", "90"))
|
| 36 |
-
if mode == "fast":
|
| 37 |
-
budget = min(budget, 45.0)
|
| 38 |
-
deadline = time.monotonic() + budget
|
| 39 |
-
instructions = (
|
| 40 |
-
"Return ONLY a JSON object matching this schema, never a bare list. "
|
| 41 |
-
"If there are no findings, return {\"findings\": []}. Schema: "
|
| 42 |
-
+ json.dumps(schema.model_json_schema())
|
| 43 |
-
)
|
| 44 |
-
messages = [*messages, {"role": "user", "content": instructions}]
|
| 45 |
-
structured = llm.with_structured_output(schema)
|
| 46 |
-
for attempt in range(2):
|
| 47 |
-
result_queue = queue.Queue(maxsize=1)
|
| 48 |
-
def run(target=result_queue, request=list(messages)):
|
| 49 |
-
try:
|
| 50 |
-
target.put((True, structured.invoke(request)))
|
| 51 |
-
except Exception as exc:
|
| 52 |
-
target.put((False, exc))
|
| 53 |
-
threading.Thread(target=copy_context().run, args=(run,), daemon=True).start()
|
| 54 |
-
remaining = deadline - time.monotonic()
|
| 55 |
-
if remaining <= 0:
|
| 56 |
-
raise TimeoutError(f"Reviewer exceeded {budget:g}s deadline")
|
| 57 |
-
try:
|
| 58 |
-
ok, result = result_queue.get(timeout=remaining)
|
| 59 |
-
except queue.Empty:
|
| 60 |
-
raise TimeoutError(f"Reviewer exceeded {budget:g}s deadline") from None
|
| 61 |
-
if ok:
|
| 62 |
-
try:
|
| 63 |
-
if isinstance(result, schema):
|
| 64 |
-
return result
|
| 65 |
-
return schema.model_validate(result)
|
| 66 |
-
except ValidationError as exc:
|
| 67 |
-
result = exc
|
| 68 |
-
# No retries for auth, rate limits, transport errors or timeouts.
|
| 69 |
-
if attempt or not (isinstance(result, ValidationError) or
|
| 70 |
-
type(result).__name__ == "OutputParserException"):
|
| 71 |
-
raise result
|
| 72 |
-
messages.append({"role": "user", "content":
|
| 73 |
-
"The previous response did not match the schema. Return the required JSON object with a findings array."})
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
def stage_result(reviewer, started, *, error=None, llm=None):
|
| 77 |
-
"""Safe stage metadata; exception text may contain secrets, so omit it."""
|
| 78 |
-
return {"reviewer": reviewer, "status": "failed" if error else "completed",
|
| 79 |
-
"error": type(error).__name__ if error else None,
|
| 80 |
-
"duration_seconds": round(time.monotonic() - started, 3),
|
| 81 |
-
"model": str(getattr(llm, "model_name", None) or getattr(llm, "model", "")) if llm else ""}
|
|
|
|
| 1 |
+
"""Bound reviewer latency and validate provider responses without hiding failures."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from contextvars import copy_context
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import queue
|
| 8 |
+
import re
|
| 9 |
+
import threading
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
from pydantic import ValidationError
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def changed_context(changed_file, mode):
|
| 16 |
+
"""Fast mode includes numbered windows around changes, not repeated whole files."""
|
| 17 |
+
content = changed_file.content or ''
|
| 18 |
+
if mode != 'fast' or not changed_file.diff_hunk:
|
| 19 |
+
return content
|
| 20 |
+
lines = content.splitlines()
|
| 21 |
+
selected = set()
|
| 22 |
+
for start, count in re.findall(r'@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@', changed_file.diff_hunk):
|
| 23 |
+
first = max(0, int(start) - 1)
|
| 24 |
+
selected.update(range(max(0, first - 12), min(len(lines), first + int(count or 1) + 12)))
|
| 25 |
+
return '\n'.join(f'{index + 1}: {lines[index]}' for index in sorted(selected)) if selected else content
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def invoke_review(llm, schema, messages, mode="thorough"):
|
| 29 |
+
"""One request plus one format repair, within a total wall-clock budget.
|
| 30 |
+
|
| 31 |
+
A daemon worker makes the caller deadline effective even with a provider
|
| 32 |
+
SDK that ignores its native request timeout. Native timeouts still close
|
| 33 |
+
underlying connections; timed-out workers never modify graph state.
|
| 34 |
+
"""
|
| 35 |
+
budget = float(os.getenv("OCR_REVIEWER_TIMEOUT_SECONDS", "90"))
|
| 36 |
+
if mode == "fast":
|
| 37 |
+
budget = min(budget, 45.0)
|
| 38 |
+
deadline = time.monotonic() + budget
|
| 39 |
+
instructions = (
|
| 40 |
+
"Return ONLY a JSON object matching this schema, never a bare list. "
|
| 41 |
+
"If there are no findings, return {\"findings\": []}. Schema: "
|
| 42 |
+
+ json.dumps(schema.model_json_schema())
|
| 43 |
+
)
|
| 44 |
+
messages = [*messages, {"role": "user", "content": instructions}]
|
| 45 |
+
structured = llm.with_structured_output(schema)
|
| 46 |
+
for attempt in range(2):
|
| 47 |
+
result_queue = queue.Queue(maxsize=1)
|
| 48 |
+
def run(target=result_queue, request=list(messages)):
|
| 49 |
+
try:
|
| 50 |
+
target.put((True, structured.invoke(request)))
|
| 51 |
+
except Exception as exc:
|
| 52 |
+
target.put((False, exc))
|
| 53 |
+
threading.Thread(target=copy_context().run, args=(run,), daemon=True).start()
|
| 54 |
+
remaining = deadline - time.monotonic()
|
| 55 |
+
if remaining <= 0:
|
| 56 |
+
raise TimeoutError(f"Reviewer exceeded {budget:g}s deadline")
|
| 57 |
+
try:
|
| 58 |
+
ok, result = result_queue.get(timeout=remaining)
|
| 59 |
+
except queue.Empty:
|
| 60 |
+
raise TimeoutError(f"Reviewer exceeded {budget:g}s deadline") from None
|
| 61 |
+
if ok:
|
| 62 |
+
try:
|
| 63 |
+
if isinstance(result, schema):
|
| 64 |
+
return result
|
| 65 |
+
return schema.model_validate(result)
|
| 66 |
+
except ValidationError as exc:
|
| 67 |
+
result = exc
|
| 68 |
+
# No retries for auth, rate limits, transport errors or timeouts.
|
| 69 |
+
if attempt or not (isinstance(result, ValidationError) or
|
| 70 |
+
type(result).__name__ == "OutputParserException"):
|
| 71 |
+
raise result
|
| 72 |
+
messages.append({"role": "user", "content":
|
| 73 |
+
"The previous response did not match the schema. Return the required JSON object with a findings array."})
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def stage_result(reviewer, started, *, error=None, llm=None):
|
| 77 |
+
"""Safe stage metadata; exception text may contain secrets, so omit it."""
|
| 78 |
+
return {"reviewer": reviewer, "status": "failed" if error else "completed",
|
| 79 |
+
"error": type(error).__name__ if error else None,
|
| 80 |
+
"duration_seconds": round(time.monotonic() - started, 3),
|
| 81 |
+
"model": str(getattr(llm, "model_name", None) or getattr(llm, "model", "")) if llm else ""}
|
nodes/security_reviewer.py
CHANGED
|
@@ -1,143 +1,143 @@
|
|
| 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.review_runtime import changed_context, invoke_review, stage_result
|
| 10 |
-
from pydantic import BaseModel, Field
|
| 11 |
-
|
| 12 |
-
from state import Finding, OpenCodeReviewState
|
| 13 |
-
|
| 14 |
-
logger = logging.getLogger(__name__)
|
| 15 |
-
|
| 16 |
-
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 17 |
-
DEFAULT_TEMPERATURE = 0.0
|
| 18 |
-
MAX_CONTEXT_CHARS = 6_000
|
| 19 |
-
MAX_FILE_CONTENT_CHARS = 4_000
|
| 20 |
-
|
| 21 |
-
# Prompt version β tied to the file on disk
|
| 22 |
-
PROMPT_VERSION = "v1"
|
| 23 |
-
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"security_{PROMPT_VERSION}.txt"
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
# βββ Load prompt from file ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def _load_prompt() -> str:
|
| 30 |
-
"""Load the system prompt from the versioned prompt file."""
|
| 31 |
-
try:
|
| 32 |
-
return PROMPT_FILE.read_text(encoding="utf-8")
|
| 33 |
-
except FileNotFoundError:
|
| 34 |
-
logger.warning("Prompt file %s not found β using fallback", PROMPT_FILE)
|
| 35 |
-
return (
|
| 36 |
-
"You are a security-focused code reviewer. "
|
| 37 |
-
"Analyse the PR diff for security vulnerabilities: injection, "
|
| 38 |
-
"secrets, unsafe deserialisation, auth issues, input validation, "
|
| 39 |
-
"cryptographic misuse, and information disclosure. "
|
| 40 |
-
"Return a list of findings."
|
| 41 |
-
)
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
SYSTEM_PROMPT = _load_prompt()
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
# βββ Wrapper schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
class SecurityReview(BaseModel):
|
| 51 |
-
"""Security issues found during code review."""
|
| 52 |
-
findings: list[Finding] = Field(
|
| 53 |
-
default_factory=list,
|
| 54 |
-
description="Security issues found in the PR diff.",
|
| 55 |
-
)
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
# βββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def _build_prompt(state: OpenCodeReviewState) -> str:
|
| 62 |
-
lines: list[str] = []
|
| 63 |
-
|
| 64 |
-
lines.append("## Diff\n```diff")
|
| 65 |
-
lines.append(state.diff or "")
|
| 66 |
-
lines.append("```\n")
|
| 67 |
-
|
| 68 |
-
if state.changed_files:
|
| 69 |
-
lines.append("## Changed files\n")
|
| 70 |
-
for cf in state.changed_files:
|
| 71 |
-
lines.append(f"### {cf.path} ({cf.status})")
|
| 72 |
-
content = changed_context(cf, state.review_mode)
|
| 73 |
-
if len(content) > MAX_FILE_CONTENT_CHARS:
|
| 74 |
-
content = content[:MAX_FILE_CONTENT_CHARS] + "\n⦠(truncated)"
|
| 75 |
-
lines.append(f"```\n{content}\n```\n")
|
| 76 |
-
|
| 77 |
-
if state.context_chunks:
|
| 78 |
-
lines.append("## Retrieved context\n")
|
| 79 |
-
ctx_chars = 0
|
| 80 |
-
for chunk in state.context_chunks:
|
| 81 |
-
snippet = chunk.content
|
| 82 |
-
if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
|
| 83 |
-
remaining = MAX_CONTEXT_CHARS - ctx_chars
|
| 84 |
-
if remaining > 200:
|
| 85 |
-
lines.append(f"> {snippet[:remaining]}β¦ (truncated)")
|
| 86 |
-
break
|
| 87 |
-
prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
|
| 88 |
-
lines.append(f"> [{prefix}]: {snippet}")
|
| 89 |
-
ctx_chars += len(snippet)
|
| 90 |
-
|
| 91 |
-
return "\n".join(lines)
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def security_reviewer_node(state: OpenCodeReviewState) -> dict:
|
| 98 |
-
started = time.monotonic()
|
| 99 |
-
if not state.diff:
|
| 100 |
-
logger.info("No diff to review β skipping security review")
|
| 101 |
-
return {}
|
| 102 |
-
|
| 103 |
-
try:
|
| 104 |
-
llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
|
| 105 |
-
except ValueError as exc:
|
| 106 |
-
logger.warning("LLM unavailable β skipping security review: %s", exc)
|
| 107 |
-
return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
|
| 108 |
-
|
| 109 |
-
user_prompt = _build_prompt(state)
|
| 110 |
-
logger.info(
|
| 111 |
-
"Invoking security reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
|
| 112 |
-
_human_size(len(state.diff or "")),
|
| 113 |
-
len(state.context_chunks),
|
| 114 |
-
PROMPT_VERSION,
|
| 115 |
-
)
|
| 116 |
-
|
| 117 |
-
try:
|
| 118 |
-
messages = [
|
| 119 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 120 |
-
{"role": "user", "content": user_prompt},
|
| 121 |
-
]
|
| 122 |
-
result: SecurityReview = invoke_review(llm, SecurityReview, messages, mode=state.review_mode) # type: ignore[assignment]
|
| 123 |
-
except Exception as exc:
|
| 124 |
-
logger.warning("Security review LLM call failed: %s", exc)
|
| 125 |
-
return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
|
| 126 |
-
|
| 127 |
-
if result.findings:
|
| 128 |
-
logger.info("Security review found %d issue(s)", len(result.findings))
|
| 129 |
-
for f in result.findings:
|
| 130 |
-
logger.debug(" [%.2f] %s:%dβ%d β %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
|
| 131 |
-
else:
|
| 132 |
-
logger.info("Security review found no issues")
|
| 133 |
-
|
| 134 |
-
return {"findings": result.findings, "review_stages": [stage_result("security", started, llm=llm)]}
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
def _human_size(bytes_: int) -> str:
|
| 138 |
-
if bytes_ < 1024:
|
| 139 |
-
return f"{bytes_} B"
|
| 140 |
-
elif bytes_ < 1024 * 1024:
|
| 141 |
-
return f"{bytes_ / 1024:.1f} KiB"
|
| 142 |
-
else:
|
| 143 |
-
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.review_runtime import changed_context, invoke_review, stage_result
|
| 10 |
+
from pydantic import BaseModel, Field
|
| 11 |
+
|
| 12 |
+
from state import Finding, OpenCodeReviewState
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 17 |
+
DEFAULT_TEMPERATURE = 0.0
|
| 18 |
+
MAX_CONTEXT_CHARS = 6_000
|
| 19 |
+
MAX_FILE_CONTENT_CHARS = 4_000
|
| 20 |
+
|
| 21 |
+
# Prompt version β tied to the file on disk
|
| 22 |
+
PROMPT_VERSION = "v1"
|
| 23 |
+
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"security_{PROMPT_VERSION}.txt"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# βββ Load prompt from file ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _load_prompt() -> str:
|
| 30 |
+
"""Load the system prompt from the versioned prompt file."""
|
| 31 |
+
try:
|
| 32 |
+
return PROMPT_FILE.read_text(encoding="utf-8")
|
| 33 |
+
except FileNotFoundError:
|
| 34 |
+
logger.warning("Prompt file %s not found β using fallback", PROMPT_FILE)
|
| 35 |
+
return (
|
| 36 |
+
"You are a security-focused code reviewer. "
|
| 37 |
+
"Analyse the PR diff for security vulnerabilities: injection, "
|
| 38 |
+
"secrets, unsafe deserialisation, auth issues, input validation, "
|
| 39 |
+
"cryptographic misuse, and information disclosure. "
|
| 40 |
+
"Return a list of findings."
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
SYSTEM_PROMPT = _load_prompt()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# βββ Wrapper schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class SecurityReview(BaseModel):
|
| 51 |
+
"""Security issues found during code review."""
|
| 52 |
+
findings: list[Finding] = Field(
|
| 53 |
+
default_factory=list,
|
| 54 |
+
description="Security issues found in the PR diff.",
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# βββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _build_prompt(state: OpenCodeReviewState) -> str:
|
| 62 |
+
lines: list[str] = []
|
| 63 |
+
|
| 64 |
+
lines.append("## Diff\n```diff")
|
| 65 |
+
lines.append(state.diff or "")
|
| 66 |
+
lines.append("```\n")
|
| 67 |
+
|
| 68 |
+
if state.changed_files:
|
| 69 |
+
lines.append("## Changed files\n")
|
| 70 |
+
for cf in state.changed_files:
|
| 71 |
+
lines.append(f"### {cf.path} ({cf.status})")
|
| 72 |
+
content = changed_context(cf, state.review_mode)
|
| 73 |
+
if len(content) > MAX_FILE_CONTENT_CHARS:
|
| 74 |
+
content = content[:MAX_FILE_CONTENT_CHARS] + "\n⦠(truncated)"
|
| 75 |
+
lines.append(f"```\n{content}\n```\n")
|
| 76 |
+
|
| 77 |
+
if state.context_chunks:
|
| 78 |
+
lines.append("## Retrieved context\n")
|
| 79 |
+
ctx_chars = 0
|
| 80 |
+
for chunk in state.context_chunks:
|
| 81 |
+
snippet = chunk.content
|
| 82 |
+
if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
|
| 83 |
+
remaining = MAX_CONTEXT_CHARS - ctx_chars
|
| 84 |
+
if remaining > 200:
|
| 85 |
+
lines.append(f"> {snippet[:remaining]}β¦ (truncated)")
|
| 86 |
+
break
|
| 87 |
+
prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
|
| 88 |
+
lines.append(f"> [{prefix}]: {snippet}")
|
| 89 |
+
ctx_chars += len(snippet)
|
| 90 |
+
|
| 91 |
+
return "\n".join(lines)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def security_reviewer_node(state: OpenCodeReviewState) -> dict:
|
| 98 |
+
started = time.monotonic()
|
| 99 |
+
if not state.diff:
|
| 100 |
+
logger.info("No diff to review β skipping security review")
|
| 101 |
+
return {}
|
| 102 |
+
|
| 103 |
+
try:
|
| 104 |
+
llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
|
| 105 |
+
except ValueError as exc:
|
| 106 |
+
logger.warning("LLM unavailable β skipping security review: %s", exc)
|
| 107 |
+
return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
|
| 108 |
+
|
| 109 |
+
user_prompt = _build_prompt(state)
|
| 110 |
+
logger.info(
|
| 111 |
+
"Invoking security reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
|
| 112 |
+
_human_size(len(state.diff or "")),
|
| 113 |
+
len(state.context_chunks),
|
| 114 |
+
PROMPT_VERSION,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
messages = [
|
| 119 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 120 |
+
{"role": "user", "content": user_prompt},
|
| 121 |
+
]
|
| 122 |
+
result: SecurityReview = invoke_review(llm, SecurityReview, messages, mode=state.review_mode) # type: ignore[assignment]
|
| 123 |
+
except Exception as exc:
|
| 124 |
+
logger.warning("Security review LLM call failed: %s", exc)
|
| 125 |
+
return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
|
| 126 |
+
|
| 127 |
+
if result.findings:
|
| 128 |
+
logger.info("Security review found %d issue(s)", len(result.findings))
|
| 129 |
+
for f in result.findings:
|
| 130 |
+
logger.debug(" [%.2f] %s:%dβ%d β %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
|
| 131 |
+
else:
|
| 132 |
+
logger.info("Security review found no issues")
|
| 133 |
+
|
| 134 |
+
return {"findings": result.findings, "review_stages": [stage_result("security", started, llm=llm)]}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _human_size(bytes_: int) -> str:
|
| 138 |
+
if bytes_ < 1024:
|
| 139 |
+
return f"{bytes_} B"
|
| 140 |
+
elif bytes_ < 1024 * 1024:
|
| 141 |
+
return f"{bytes_ / 1024:.1f} KiB"
|
| 142 |
+
else:
|
| 143 |
+
return f"{bytes_ / (1024 * 1024):.1f} MiB"
|
nodes/test_coverage_reviewer.py
CHANGED
|
@@ -1,141 +1,150 @@
|
|
| 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.review_runtime import changed_context, invoke_review, stage_result
|
| 10 |
-
from pydantic import BaseModel, Field
|
| 11 |
-
|
| 12 |
-
from state import Finding, OpenCodeReviewState
|
| 13 |
-
|
| 14 |
-
logger = logging.getLogger(__name__)
|
| 15 |
-
|
| 16 |
-
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 17 |
-
DEFAULT_TEMPERATURE = 0.0
|
| 18 |
-
MAX_CONTEXT_CHARS = 6_000
|
| 19 |
-
MAX_FILE_CONTENT_CHARS = 4_000
|
| 20 |
-
|
| 21 |
-
# Prompt version β tied to the file on disk
|
| 22 |
-
PROMPT_VERSION = "v1"
|
| 23 |
-
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"test_coverage_{PROMPT_VERSION}.txt"
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
# βββ Load prompt from file ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def _load_prompt() -> str:
|
| 30 |
-
"""Load the system prompt from the versioned prompt file."""
|
| 31 |
-
try:
|
| 32 |
-
return PROMPT_FILE.read_text(encoding="utf-8")
|
| 33 |
-
except FileNotFoundError:
|
| 34 |
-
logger.warning("Prompt file %s not found β using fallback", PROMPT_FILE)
|
| 35 |
-
return (
|
| 36 |
-
"You are a code reviewer focused on test coverage. "
|
| 37 |
-
"Analyse the PR diff and determine whether the changed logic "
|
| 38 |
-
"has adequate test coverage. Return a list of findings."
|
| 39 |
-
)
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
SYSTEM_PROMPT = _load_prompt()
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
# βββ Wrapper schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
class TestCoverageReview(BaseModel):
|
| 49 |
-
"""Test-coverage gaps found during code review."""
|
| 50 |
-
findings: list[Finding] = Field(
|
| 51 |
-
default_factory=list,
|
| 52 |
-
description="Test-coverage issues found in the PR diff.",
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
# βββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
def _build_prompt(state: OpenCodeReviewState) -> str:
|
| 60 |
-
lines: list[str] = []
|
| 61 |
-
|
| 62 |
-
lines.append("## Diff\n```diff")
|
| 63 |
-
lines.append(state.diff or "")
|
| 64 |
-
lines.append("```\n")
|
| 65 |
-
|
| 66 |
-
if state.changed_files:
|
| 67 |
-
lines.append("## Changed files\n")
|
| 68 |
-
for cf in state.changed_files:
|
| 69 |
-
lines.append(f"### {cf.path} ({cf.status})")
|
| 70 |
-
content = changed_context(cf, state.review_mode)
|
| 71 |
-
if len(content) > MAX_FILE_CONTENT_CHARS:
|
| 72 |
-
content = content[:MAX_FILE_CONTENT_CHARS] + "\n⦠(truncated)"
|
| 73 |
-
lines.append(f"```\n{content}\n```\n")
|
| 74 |
-
|
| 75 |
-
if state.context_chunks:
|
| 76 |
-
lines.append("## Retrieved context\n")
|
| 77 |
-
ctx_chars = 0
|
| 78 |
-
for chunk in state.context_chunks:
|
| 79 |
-
snippet = chunk.content
|
| 80 |
-
if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
|
| 81 |
-
remaining = MAX_CONTEXT_CHARS - ctx_chars
|
| 82 |
-
if remaining > 200:
|
| 83 |
-
lines.append(f"> {snippet[:remaining]}β¦ (truncated)")
|
| 84 |
-
break
|
| 85 |
-
prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
|
| 86 |
-
lines.append(f"> [{prefix}]: {snippet}")
|
| 87 |
-
ctx_chars += len(snippet)
|
| 88 |
-
|
| 89 |
-
return "\n".join(lines)
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
def test_coverage_reviewer_node(state: OpenCodeReviewState) -> dict:
|
| 96 |
-
started = time.monotonic()
|
| 97 |
-
if not state.diff:
|
| 98 |
-
logger.info("No diff to review β skipping test-coverage review")
|
| 99 |
-
return {}
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.review_runtime import changed_context, invoke_review, stage_result
|
| 10 |
+
from pydantic import BaseModel, Field
|
| 11 |
+
|
| 12 |
+
from state import Finding, OpenCodeReviewState
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 17 |
+
DEFAULT_TEMPERATURE = 0.0
|
| 18 |
+
MAX_CONTEXT_CHARS = 6_000
|
| 19 |
+
MAX_FILE_CONTENT_CHARS = 4_000
|
| 20 |
+
|
| 21 |
+
# Prompt version β tied to the file on disk
|
| 22 |
+
PROMPT_VERSION = "v1"
|
| 23 |
+
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"test_coverage_{PROMPT_VERSION}.txt"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# βββ Load prompt from file ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _load_prompt() -> str:
|
| 30 |
+
"""Load the system prompt from the versioned prompt file."""
|
| 31 |
+
try:
|
| 32 |
+
return PROMPT_FILE.read_text(encoding="utf-8")
|
| 33 |
+
except FileNotFoundError:
|
| 34 |
+
logger.warning("Prompt file %s not found β using fallback", PROMPT_FILE)
|
| 35 |
+
return (
|
| 36 |
+
"You are a code reviewer focused on test coverage. "
|
| 37 |
+
"Analyse the PR diff and determine whether the changed logic "
|
| 38 |
+
"has adequate test coverage. Return a list of findings."
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
SYSTEM_PROMPT = _load_prompt()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# βββ Wrapper schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class TestCoverageReview(BaseModel):
|
| 49 |
+
"""Test-coverage gaps found during code review."""
|
| 50 |
+
findings: list[Finding] = Field(
|
| 51 |
+
default_factory=list,
|
| 52 |
+
description="Test-coverage issues found in the PR diff.",
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# βββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _build_prompt(state: OpenCodeReviewState) -> str:
|
| 60 |
+
lines: list[str] = []
|
| 61 |
+
|
| 62 |
+
lines.append("## Diff\n```diff")
|
| 63 |
+
lines.append(state.diff or "")
|
| 64 |
+
lines.append("```\n")
|
| 65 |
+
|
| 66 |
+
if state.changed_files:
|
| 67 |
+
lines.append("## Changed files\n")
|
| 68 |
+
for cf in state.changed_files:
|
| 69 |
+
lines.append(f"### {cf.path} ({cf.status})")
|
| 70 |
+
content = changed_context(cf, state.review_mode)
|
| 71 |
+
if len(content) > MAX_FILE_CONTENT_CHARS:
|
| 72 |
+
content = content[:MAX_FILE_CONTENT_CHARS] + "\n⦠(truncated)"
|
| 73 |
+
lines.append(f"```\n{content}\n```\n")
|
| 74 |
+
|
| 75 |
+
if state.context_chunks:
|
| 76 |
+
lines.append("## Retrieved context\n")
|
| 77 |
+
ctx_chars = 0
|
| 78 |
+
for chunk in state.context_chunks:
|
| 79 |
+
snippet = chunk.content
|
| 80 |
+
if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
|
| 81 |
+
remaining = MAX_CONTEXT_CHARS - ctx_chars
|
| 82 |
+
if remaining > 200:
|
| 83 |
+
lines.append(f"> {snippet[:remaining]}β¦ (truncated)")
|
| 84 |
+
break
|
| 85 |
+
prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
|
| 86 |
+
lines.append(f"> [{prefix}]: {snippet}")
|
| 87 |
+
ctx_chars += len(snippet)
|
| 88 |
+
|
| 89 |
+
return "\n".join(lines)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_coverage_reviewer_node(state: OpenCodeReviewState) -> dict:
|
| 96 |
+
started = time.monotonic()
|
| 97 |
+
if not state.diff:
|
| 98 |
+
logger.info("No diff to review β skipping test-coverage review")
|
| 99 |
+
return {}
|
| 100 |
+
|
| 101 |
+
# Fast mode avoids a test specialist for documentation-only changes.
|
| 102 |
+
# Security and correctness still run; executable/config/unknown files
|
| 103 |
+
# always retain all reviewers, as does Thorough mode.
|
| 104 |
+
if state.review_mode == 'fast' and state.changed_files and all(
|
| 105 |
+
cf.path.lower().endswith(('.md', '.rst', '.txt')) for cf in state.changed_files
|
| 106 |
+
):
|
| 107 |
+
return {'review_stages': [{'reviewer': 'test_coverage', 'status': 'skipped',
|
| 108 |
+
'reason': 'Fast mode: documentation-only changes', 'duration_seconds': 0.0, 'model': ''}]}
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
|
| 112 |
+
except ValueError as exc:
|
| 113 |
+
logger.warning("LLM unavailable β skipping test-coverage review: %s", exc)
|
| 114 |
+
return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
|
| 115 |
+
|
| 116 |
+
user_prompt = _build_prompt(state)
|
| 117 |
+
logger.info(
|
| 118 |
+
"Invoking test-coverage reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
|
| 119 |
+
_human_size(len(state.diff or "")),
|
| 120 |
+
len(state.context_chunks),
|
| 121 |
+
PROMPT_VERSION,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
try:
|
| 125 |
+
messages = [
|
| 126 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 127 |
+
{"role": "user", "content": user_prompt},
|
| 128 |
+
]
|
| 129 |
+
result: TestCoverageReview = invoke_review(llm, TestCoverageReview, messages, mode=state.review_mode) # type: ignore[assignment]
|
| 130 |
+
except Exception as exc:
|
| 131 |
+
logger.warning("Test-coverage review LLM call failed: %s", exc)
|
| 132 |
+
return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
|
| 133 |
+
|
| 134 |
+
if result.findings:
|
| 135 |
+
logger.info("Test-coverage review found %d issue(s)", len(result.findings))
|
| 136 |
+
for f in result.findings:
|
| 137 |
+
logger.debug(" [%.2f] %s:%dβ%d β %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
|
| 138 |
+
else:
|
| 139 |
+
logger.info("Test-coverage review found no issues")
|
| 140 |
+
|
| 141 |
+
return {"findings": result.findings, "review_stages": [stage_result("test_coverage", started, llm=llm)]}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _human_size(bytes_: int) -> str:
|
| 145 |
+
if bytes_ < 1024:
|
| 146 |
+
return f"{bytes_} B"
|
| 147 |
+
elif bytes_ < 1024 * 1024:
|
| 148 |
+
return f"{bytes_ / 1024:.1f} KiB"
|
| 149 |
+
else:
|
| 150 |
+
return f"{bytes_ / (1024 * 1024):.1f} MiB"
|
state.py
CHANGED
|
@@ -1,95 +1,95 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import enum
|
| 4 |
-
from operator import add
|
| 5 |
-
from typing import Annotated, 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 |
-
|
| 48 |
-
|
| 49 |
-
class Verdict(BaseModel):
|
| 50 |
-
"""Aggregated final verdict across all findings."""
|
| 51 |
-
summary: str
|
| 52 |
-
approved: bool
|
| 53 |
-
overall_score: Optional[float] = Field(default=None, ge=0.0, le=10.0)
|
| 54 |
-
critical_count: int = 0
|
| 55 |
-
high_count: int = 0
|
| 56 |
-
recommendation: str # "approve" | "request_changes" | "block"
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
# βββ Graph State βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
class OpenCodeReviewState(BaseModel):
|
| 63 |
-
"""Shared state for the OpenCodeReview LangGraph agent."""
|
| 64 |
-
|
| 65 |
-
# PR metadata: set-once, single values
|
| 66 |
-
repo: str = ""
|
| 67 |
-
pr_number: int = 0
|
| 68 |
-
head_sha: str = ""
|
| 69 |
-
incremental_base_sha: str = ""
|
| 70 |
-
base_sha: str = "" # SHA of the base branch (used as vector-store cache key)
|
| 71 |
-
diff: Optional[str] = None
|
| 72 |
-
changed_files: list[ChangedFile] = Field(default_factory=list)
|
| 73 |
-
|
| 74 |
-
# Custom LLM endpoint chosen for this run (name from OCR_ENDPOINT_* env
|
| 75 |
-
# configs). Empty string means "use the built-in default provider".
|
| 76 |
-
endpoint: str = ""
|
| 77 |
-
review_mode: str = "thorough"
|
| 78 |
-
|
| 79 |
-
# Retrieved context: accumulated across parallel retrieval nodes
|
| 80 |
-
context_chunks: Annotated[list[ContextChunk], add] = Field(default_factory=list)
|
| 81 |
-
|
| 82 |
-
# Review findings: accumulated across parallel review agents
|
| 83 |
-
findings: Annotated[list[Finding], add] = Field(default_factory=list)
|
| 84 |
-
|
| 85 |
-
review_stages: Annotated[list[dict], add] = Field(default_factory=list)
|
| 86 |
-
|
| 87 |
-
# Aggregated (deduped, noise-filtered) findings: set-once by aggregator
|
| 88 |
-
final_findings: list[Finding] = Field(default_factory=list)
|
| 89 |
-
|
| 90 |
-
# Final verdict: set-once by the aggregation node
|
| 91 |
-
verdict: Optional[Verdict] = None
|
| 92 |
-
|
| 93 |
-
# Human-in-the-loop: set by the human_approval node
|
| 94 |
-
human_approved: bool = False
|
| 95 |
-
posting_result: Optional[dict] = None
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import enum
|
| 4 |
+
from operator import add
|
| 5 |
+
from typing import Annotated, 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 |
+
|
| 48 |
+
|
| 49 |
+
class Verdict(BaseModel):
|
| 50 |
+
"""Aggregated final verdict across all findings."""
|
| 51 |
+
summary: str
|
| 52 |
+
approved: bool
|
| 53 |
+
overall_score: Optional[float] = Field(default=None, ge=0.0, le=10.0)
|
| 54 |
+
critical_count: int = 0
|
| 55 |
+
high_count: int = 0
|
| 56 |
+
recommendation: str # "approve" | "request_changes" | "block"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# βββ Graph State βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class OpenCodeReviewState(BaseModel):
|
| 63 |
+
"""Shared state for the OpenCodeReview LangGraph agent."""
|
| 64 |
+
|
| 65 |
+
# PR metadata: set-once, single values
|
| 66 |
+
repo: str = ""
|
| 67 |
+
pr_number: int = 0
|
| 68 |
+
head_sha: str = ""
|
| 69 |
+
incremental_base_sha: str = ""
|
| 70 |
+
base_sha: str = "" # SHA of the base branch (used as vector-store cache key)
|
| 71 |
+
diff: Optional[str] = None
|
| 72 |
+
changed_files: list[ChangedFile] = Field(default_factory=list)
|
| 73 |
+
|
| 74 |
+
# Custom LLM endpoint chosen for this run (name from OCR_ENDPOINT_* env
|
| 75 |
+
# configs). Empty string means "use the built-in default provider".
|
| 76 |
+
endpoint: str = ""
|
| 77 |
+
review_mode: str = "thorough"
|
| 78 |
+
|
| 79 |
+
# Retrieved context: accumulated across parallel retrieval nodes
|
| 80 |
+
context_chunks: Annotated[list[ContextChunk], add] = Field(default_factory=list)
|
| 81 |
+
|
| 82 |
+
# Review findings: accumulated across parallel review agents
|
| 83 |
+
findings: Annotated[list[Finding], add] = Field(default_factory=list)
|
| 84 |
+
|
| 85 |
+
review_stages: Annotated[list[dict], add] = Field(default_factory=list)
|
| 86 |
+
|
| 87 |
+
# Aggregated (deduped, noise-filtered) findings: set-once by aggregator
|
| 88 |
+
final_findings: list[Finding] = Field(default_factory=list)
|
| 89 |
+
|
| 90 |
+
# Final verdict: set-once by the aggregation node
|
| 91 |
+
verdict: Optional[Verdict] = None
|
| 92 |
+
|
| 93 |
+
# Human-in-the-loop: set by the human_approval node
|
| 94 |
+
human_approved: bool = False
|
| 95 |
+
posting_result: Optional[dict] = None
|
tests/test_review_runtime.py
CHANGED
|
@@ -9,6 +9,8 @@ from nodes.review_runtime import invoke_review
|
|
| 9 |
from nodes.aggregator import aggregator_node
|
| 10 |
from nodes.security_reviewer import security_reviewer_node
|
| 11 |
from state import OpenCodeReviewState
|
|
|
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
class Review(BaseModel):
|
|
@@ -29,6 +31,12 @@ def test_tracing_context_survives_deadline_worker():
|
|
| 29 |
trace.reset(token)
|
| 30 |
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
def model_with_results(*results):
|
| 33 |
model = Mock()
|
| 34 |
model.with_structured_output.return_value.invoke.side_effect = results
|
|
|
|
| 9 |
from nodes.aggregator import aggregator_node
|
| 10 |
from nodes.security_reviewer import security_reviewer_node
|
| 11 |
from state import OpenCodeReviewState
|
| 12 |
+
from state import ChangedFile
|
| 13 |
+
from nodes.test_coverage_reviewer import test_coverage_reviewer_node as coverage_node
|
| 14 |
|
| 15 |
|
| 16 |
class Review(BaseModel):
|
|
|
|
| 31 |
trace.reset(token)
|
| 32 |
|
| 33 |
|
| 34 |
+
def test_fast_documentation_routes_without_test_specialist():
|
| 35 |
+
state = OpenCodeReviewState(diff='+documentation', review_mode='fast', changed_files=[
|
| 36 |
+
ChangedFile(path='README.md', status='modified', content='documentation', diff_hunk='+documentation')])
|
| 37 |
+
assert coverage_node(state)['review_stages'][0]['status'] == 'skipped'
|
| 38 |
+
|
| 39 |
+
|
| 40 |
def model_with_results(*results):
|
| 41 |
model = Mock()
|
| 42 |
model.with_structured_output.return_value.invoke.side_effect = results
|