Spaces:
Running
Running
Deploy f3485b9c
Browse files- api.py +589 -589
- app.py +0 -0
- llm_factory.py +269 -269
- nodes/correctness_reviewer.py +198 -198
- nodes/review_runtime.py +88 -88
- tests/test_job_speed.py +9 -0
- tests/test_review_runtime.py +32 -0
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": "Review incomplete; scoring was not started" if result.get("status") == "incomplete" else "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": "Review incomplete; scoring was not started" if result.get("status") == "incomplete" else "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
|
|
|
llm_factory.py
CHANGED
|
@@ -1,269 +1,269 @@
|
|
| 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 |
-
# MiniMax M3.1 requires reasoning and OpenRouter defaults to max effort.
|
| 126 |
-
# Reserve room for reasoning + visible JSON rather than truncating at 1200.
|
| 127 |
-
if 'minimax-m3.1' in model.lower():
|
| 128 |
-
kwargs['max_tokens'] = max(int(kwargs.get('max_tokens') or 0), 8192)
|
| 129 |
-
if endpoint.base_url and 'openrouter.ai' in endpoint.base_url:
|
| 130 |
-
extra = dict(kwargs.get('extra_body') or {})
|
| 131 |
-
extra['reasoning'] = {'effort': 'low'}
|
| 132 |
-
kwargs['extra_body'] = extra
|
| 133 |
-
temperature = kwargs.pop("temperature", DEFAULT_TEMPERATURE)
|
| 134 |
-
|
| 135 |
-
if provider == "anthropic":
|
| 136 |
-
try:
|
| 137 |
-
from langchain_anthropic import ChatAnthropic
|
| 138 |
-
except ImportError:
|
| 139 |
-
raise ValueError(
|
| 140 |
-
"langchain-anthropic is not installed — cannot use endpoint "
|
| 141 |
-
f"'{endpoint.name}'. Run: pip install langchain-anthropic"
|
| 142 |
-
) from None
|
| 143 |
-
params: dict[str, Any] = {
|
| 144 |
-
"model": model,
|
| 145 |
-
"api_key": endpoint.api_key,
|
| 146 |
-
"temperature": temperature,
|
| 147 |
-
}
|
| 148 |
-
if endpoint.base_url:
|
| 149 |
-
params["base_url"] = endpoint.base_url
|
| 150 |
-
params.update(kwargs)
|
| 151 |
-
return ChatAnthropic(**params)
|
| 152 |
-
|
| 153 |
-
if provider == "google":
|
| 154 |
-
try:
|
| 155 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 156 |
-
except ImportError:
|
| 157 |
-
raise ValueError(
|
| 158 |
-
"langchain-google-genai is not installed — cannot use endpoint "
|
| 159 |
-
f"'{endpoint.name}'. Run: pip install langchain-google-genai"
|
| 160 |
-
) from None
|
| 161 |
-
params = {
|
| 162 |
-
"model": model,
|
| 163 |
-
"google_api_key": endpoint.api_key,
|
| 164 |
-
"temperature": temperature,
|
| 165 |
-
}
|
| 166 |
-
params.update(kwargs)
|
| 167 |
-
return ChatGoogleGenerativeAI(**params)
|
| 168 |
-
|
| 169 |
-
# Default: OpenAI-compatible
|
| 170 |
-
try:
|
| 171 |
-
from langchain_openai import ChatOpenAI
|
| 172 |
-
except ImportError:
|
| 173 |
-
raise ValueError(
|
| 174 |
-
"langchain-openai is not installed — cannot use endpoint "
|
| 175 |
-
f"'{endpoint.name}'. Run: pip install langchain-openai"
|
| 176 |
-
) from None
|
| 177 |
-
params = {
|
| 178 |
-
"model": model,
|
| 179 |
-
"api_key": endpoint.api_key,
|
| 180 |
-
"temperature": temperature,
|
| 181 |
-
}
|
| 182 |
-
if endpoint.base_url:
|
| 183 |
-
params["base_url"] = endpoint.base_url
|
| 184 |
-
params.update(kwargs)
|
| 185 |
-
return ChatOpenAI(**params)
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
def create_llm(endpoint=None, **kwargs: Any) -> Any:
|
| 189 |
-
"""Create a chat LLM — custom endpoint first, else Gemini → Groq.
|
| 190 |
-
|
| 191 |
-
Parameters
|
| 192 |
-
----------
|
| 193 |
-
endpoint : EndpointConfig or str or None
|
| 194 |
-
A custom endpoint to run on (``EndpointConfig`` object or its name).
|
| 195 |
-
``None`` (default) falls back to the built-in providers.
|
| 196 |
-
**kwargs
|
| 197 |
-
Passed through to the underlying LangChain constructor.
|
| 198 |
-
Common overrides: ``model``, ``temperature``.
|
| 199 |
-
|
| 200 |
-
Returns
|
| 201 |
-
-------
|
| 202 |
-
Any
|
| 203 |
-
A LangChain chat model instance (``ChatOpenAI``/``ChatAnthropic``/
|
| 204 |
-
``ChatGoogleGenerativeAI`` from a custom endpoint, or the built-in
|
| 205 |
-
``ChatGoogleGenerativeAI`` / ``ChatGroq``).
|
| 206 |
-
|
| 207 |
-
Raises
|
| 208 |
-
------
|
| 209 |
-
ValueError
|
| 210 |
-
If a custom endpoint is named but not found, or no provider key is set.
|
| 211 |
-
"""
|
| 212 |
-
if endpoint:
|
| 213 |
-
from endpoints import EndpointConfig, get_endpoint
|
| 214 |
-
|
| 215 |
-
ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
|
| 216 |
-
if ep is not None:
|
| 217 |
-
if getattr(ep, "builtin", False):
|
| 218 |
-
# Built-in providers use their native constructors so the
|
| 219 |
-
# behaviour is identical to the default (no-endpoint) path.
|
| 220 |
-
if ep.name == "Gemini":
|
| 221 |
-
llm = _get_gemini_chat(**kwargs)
|
| 222 |
-
if llm is not None:
|
| 223 |
-
logger.info(
|
| 224 |
-
"Using built-in Gemini endpoint (model=%s)",
|
| 225 |
-
kwargs.get("model", GEMINI_MODEL),
|
| 226 |
-
)
|
| 227 |
-
return llm
|
| 228 |
-
raise ValueError(
|
| 229 |
-
"Gemini selected but GEMINI_API_KEY is not set."
|
| 230 |
-
)
|
| 231 |
-
if ep.name == "Grok":
|
| 232 |
-
llm = _get_groq_chat(**kwargs)
|
| 233 |
-
if llm is not None:
|
| 234 |
-
logger.info(
|
| 235 |
-
"Using built-in Grok endpoint (model=%s)",
|
| 236 |
-
kwargs.get("model", GROQ_MODEL),
|
| 237 |
-
)
|
| 238 |
-
return llm
|
| 239 |
-
raise ValueError(
|
| 240 |
-
"Grok selected but GROQ_API_KEY is not set."
|
| 241 |
-
)
|
| 242 |
-
try:
|
| 243 |
-
llm = create_endpoint_llm(ep, **kwargs)
|
| 244 |
-
logger.info("Using custom endpoint %s (%s/%s)", ep.name, ep.provider, ep.model)
|
| 245 |
-
return llm
|
| 246 |
-
except ValueError:
|
| 247 |
-
raise
|
| 248 |
-
else:
|
| 249 |
-
raise ValueError(
|
| 250 |
-
f"Custom endpoint '{endpoint}' not found. "
|
| 251 |
-
"Configure it via OCR_ENDPOINT_* environment variables "
|
| 252 |
-
"or add it in the UI."
|
| 253 |
-
)
|
| 254 |
-
|
| 255 |
-
# Prefer Groq when configured: it has a separate quota pool and avoids
|
| 256 |
-
# stalling the review pipeline on Gemini free-tier exhaustion.
|
| 257 |
-
llm = _get_groq_chat(**kwargs)
|
| 258 |
-
if llm is not None:
|
| 259 |
-
logger.debug("Using Groq (model=%s)", kwargs.get("model", GROQ_MODEL))
|
| 260 |
-
return llm
|
| 261 |
-
|
| 262 |
-
llm = _get_gemini_chat(**kwargs)
|
| 263 |
-
if llm is not None:
|
| 264 |
-
logger.debug("Falling back to Gemini (model=%s)", kwargs.get("model", GEMINI_MODEL))
|
| 265 |
-
return llm
|
| 266 |
-
|
| 267 |
-
raise ValueError(
|
| 268 |
-
"No LLM available. Set GEMINI_API_KEY (primary) or GROQ_API_KEY (fallback)."
|
| 269 |
-
)
|
|
|
|
| 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 |
+
# MiniMax M3.1 requires reasoning and OpenRouter defaults to max effort.
|
| 126 |
+
# Reserve room for reasoning + visible JSON rather than truncating at 1200.
|
| 127 |
+
if 'minimax-m3.1' in model.lower():
|
| 128 |
+
kwargs['max_tokens'] = max(int(kwargs.get('max_tokens') or 0), 8192)
|
| 129 |
+
if endpoint.base_url and 'openrouter.ai' in endpoint.base_url:
|
| 130 |
+
extra = dict(kwargs.get('extra_body') or {})
|
| 131 |
+
extra['reasoning'] = {'effort': 'low'}
|
| 132 |
+
kwargs['extra_body'] = extra
|
| 133 |
+
temperature = kwargs.pop("temperature", DEFAULT_TEMPERATURE)
|
| 134 |
+
|
| 135 |
+
if provider == "anthropic":
|
| 136 |
+
try:
|
| 137 |
+
from langchain_anthropic import ChatAnthropic
|
| 138 |
+
except ImportError:
|
| 139 |
+
raise ValueError(
|
| 140 |
+
"langchain-anthropic is not installed — cannot use endpoint "
|
| 141 |
+
f"'{endpoint.name}'. Run: pip install langchain-anthropic"
|
| 142 |
+
) from None
|
| 143 |
+
params: dict[str, Any] = {
|
| 144 |
+
"model": model,
|
| 145 |
+
"api_key": endpoint.api_key,
|
| 146 |
+
"temperature": temperature,
|
| 147 |
+
}
|
| 148 |
+
if endpoint.base_url:
|
| 149 |
+
params["base_url"] = endpoint.base_url
|
| 150 |
+
params.update(kwargs)
|
| 151 |
+
return ChatAnthropic(**params)
|
| 152 |
+
|
| 153 |
+
if provider == "google":
|
| 154 |
+
try:
|
| 155 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 156 |
+
except ImportError:
|
| 157 |
+
raise ValueError(
|
| 158 |
+
"langchain-google-genai is not installed — cannot use endpoint "
|
| 159 |
+
f"'{endpoint.name}'. Run: pip install langchain-google-genai"
|
| 160 |
+
) from None
|
| 161 |
+
params = {
|
| 162 |
+
"model": model,
|
| 163 |
+
"google_api_key": endpoint.api_key,
|
| 164 |
+
"temperature": temperature,
|
| 165 |
+
}
|
| 166 |
+
params.update(kwargs)
|
| 167 |
+
return ChatGoogleGenerativeAI(**params)
|
| 168 |
+
|
| 169 |
+
# Default: OpenAI-compatible
|
| 170 |
+
try:
|
| 171 |
+
from langchain_openai import ChatOpenAI
|
| 172 |
+
except ImportError:
|
| 173 |
+
raise ValueError(
|
| 174 |
+
"langchain-openai is not installed — cannot use endpoint "
|
| 175 |
+
f"'{endpoint.name}'. Run: pip install langchain-openai"
|
| 176 |
+
) from None
|
| 177 |
+
params = {
|
| 178 |
+
"model": model,
|
| 179 |
+
"api_key": endpoint.api_key,
|
| 180 |
+
"temperature": temperature,
|
| 181 |
+
}
|
| 182 |
+
if endpoint.base_url:
|
| 183 |
+
params["base_url"] = endpoint.base_url
|
| 184 |
+
params.update(kwargs)
|
| 185 |
+
return ChatOpenAI(**params)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def create_llm(endpoint=None, **kwargs: Any) -> Any:
|
| 189 |
+
"""Create a chat LLM — custom endpoint first, else Gemini → Groq.
|
| 190 |
+
|
| 191 |
+
Parameters
|
| 192 |
+
----------
|
| 193 |
+
endpoint : EndpointConfig or str or None
|
| 194 |
+
A custom endpoint to run on (``EndpointConfig`` object or its name).
|
| 195 |
+
``None`` (default) falls back to the built-in providers.
|
| 196 |
+
**kwargs
|
| 197 |
+
Passed through to the underlying LangChain constructor.
|
| 198 |
+
Common overrides: ``model``, ``temperature``.
|
| 199 |
+
|
| 200 |
+
Returns
|
| 201 |
+
-------
|
| 202 |
+
Any
|
| 203 |
+
A LangChain chat model instance (``ChatOpenAI``/``ChatAnthropic``/
|
| 204 |
+
``ChatGoogleGenerativeAI`` from a custom endpoint, or the built-in
|
| 205 |
+
``ChatGoogleGenerativeAI`` / ``ChatGroq``).
|
| 206 |
+
|
| 207 |
+
Raises
|
| 208 |
+
------
|
| 209 |
+
ValueError
|
| 210 |
+
If a custom endpoint is named but not found, or no provider key is set.
|
| 211 |
+
"""
|
| 212 |
+
if endpoint:
|
| 213 |
+
from endpoints import EndpointConfig, get_endpoint
|
| 214 |
+
|
| 215 |
+
ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
|
| 216 |
+
if ep is not None:
|
| 217 |
+
if getattr(ep, "builtin", False):
|
| 218 |
+
# Built-in providers use their native constructors so the
|
| 219 |
+
# behaviour is identical to the default (no-endpoint) path.
|
| 220 |
+
if ep.name == "Gemini":
|
| 221 |
+
llm = _get_gemini_chat(**kwargs)
|
| 222 |
+
if llm is not None:
|
| 223 |
+
logger.info(
|
| 224 |
+
"Using built-in Gemini endpoint (model=%s)",
|
| 225 |
+
kwargs.get("model", GEMINI_MODEL),
|
| 226 |
+
)
|
| 227 |
+
return llm
|
| 228 |
+
raise ValueError(
|
| 229 |
+
"Gemini selected but GEMINI_API_KEY is not set."
|
| 230 |
+
)
|
| 231 |
+
if ep.name == "Grok":
|
| 232 |
+
llm = _get_groq_chat(**kwargs)
|
| 233 |
+
if llm is not None:
|
| 234 |
+
logger.info(
|
| 235 |
+
"Using built-in Grok endpoint (model=%s)",
|
| 236 |
+
kwargs.get("model", GROQ_MODEL),
|
| 237 |
+
)
|
| 238 |
+
return llm
|
| 239 |
+
raise ValueError(
|
| 240 |
+
"Grok selected but GROQ_API_KEY is not set."
|
| 241 |
+
)
|
| 242 |
+
try:
|
| 243 |
+
llm = create_endpoint_llm(ep, **kwargs)
|
| 244 |
+
logger.info("Using custom endpoint %s (%s/%s)", ep.name, ep.provider, ep.model)
|
| 245 |
+
return llm
|
| 246 |
+
except ValueError:
|
| 247 |
+
raise
|
| 248 |
+
else:
|
| 249 |
+
raise ValueError(
|
| 250 |
+
f"Custom endpoint '{endpoint}' not found. "
|
| 251 |
+
"Configure it via OCR_ENDPOINT_* environment variables "
|
| 252 |
+
"or add it in the UI."
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# Prefer Groq when configured: it has a separate quota pool and avoids
|
| 256 |
+
# stalling the review pipeline on Gemini free-tier exhaustion.
|
| 257 |
+
llm = _get_groq_chat(**kwargs)
|
| 258 |
+
if llm is not None:
|
| 259 |
+
logger.debug("Using Groq (model=%s)", kwargs.get("model", GROQ_MODEL))
|
| 260 |
+
return llm
|
| 261 |
+
|
| 262 |
+
llm = _get_gemini_chat(**kwargs)
|
| 263 |
+
if llm is not None:
|
| 264 |
+
logger.debug("Falling back to Gemini (model=%s)", kwargs.get("model", GEMINI_MODEL))
|
| 265 |
+
return llm
|
| 266 |
+
|
| 267 |
+
raise ValueError(
|
| 268 |
+
"No LLM available. Set GEMINI_API_KEY (primary) or GROQ_API_KEY (fallback)."
|
| 269 |
+
)
|
nodes/correctness_reviewer.py
CHANGED
|
@@ -1,198 +1,198 @@
|
|
| 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 |
-
# A regex match cannot establish whether async side effects must be awaited.
|
| 133 |
-
# Retain findings only when the reviewer has evaluated the surrounding code.
|
| 134 |
-
static_findings = []
|
| 135 |
-
|
| 136 |
-
# --- Build the LLM (Gemini primary → Groq fallback) -----------------------
|
| 137 |
-
try:
|
| 138 |
-
llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
|
| 139 |
-
except ValueError as exc:
|
| 140 |
-
logger.warning("LLM unavailable — skipping correctness review: %s", exc)
|
| 141 |
-
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
|
| 142 |
-
|
| 143 |
-
# --- Build the prompt ----------------------------------------------------
|
| 144 |
-
user_prompt = _build_prompt(state)
|
| 145 |
-
logger.info(
|
| 146 |
-
"Invoking correctness reviewer (diff=%s, context=%d chunks, prompt=%s, prompt_version=%s)",
|
| 147 |
-
_human_size(len(state.diff or "")),
|
| 148 |
-
len(state.context_chunks),
|
| 149 |
-
_human_size(len(user_prompt)),
|
| 150 |
-
PROMPT_VERSION,
|
| 151 |
-
)
|
| 152 |
-
|
| 153 |
-
# --- Invoke --------------------------------------------------------------
|
| 154 |
-
try:
|
| 155 |
-
messages = [
|
| 156 |
-
{"role": "system", "content": SYSTEM_PROMPT},
|
| 157 |
-
{"role": "user", "content": user_prompt},
|
| 158 |
-
]
|
| 159 |
-
result: CorrectnessReview = invoke_review(llm, CorrectnessReview, messages, mode=state.review_mode) # type: ignore[assignment]
|
| 160 |
-
except Exception as exc:
|
| 161 |
-
logger.warning("Correctness review LLM call failed: %s", exc)
|
| 162 |
-
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
|
| 163 |
-
|
| 164 |
-
# Deterministic guard for a high-impact async anti-pattern that LLMs can
|
| 165 |
-
# miss: promises created by forEach are not awaited by the caller.
|
| 166 |
-
result.findings.extend(static_findings)
|
| 167 |
-
|
| 168 |
-
# --- Log and return findings ---------------------------------------------
|
| 169 |
-
if result and result.findings:
|
| 170 |
-
logger.info(
|
| 171 |
-
"Correctness review found %d issue(s)",
|
| 172 |
-
len(result.findings),
|
| 173 |
-
)
|
| 174 |
-
for f in result.findings:
|
| 175 |
-
logger.debug(
|
| 176 |
-
" [%.2f] %s:%d–%d — %s",
|
| 177 |
-
f.confidence, f.file_path, f.line_start, f.line_end,
|
| 178 |
-
f.comment[:80],
|
| 179 |
-
)
|
| 180 |
-
else:
|
| 181 |
-
logger.info("Correctness review found no issues")
|
| 182 |
-
|
| 183 |
-
return {
|
| 184 |
-
"findings": result.findings,
|
| 185 |
-
"review_stages": [stage_result("correctness", started, llm=llm)],
|
| 186 |
-
}
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
# ─── Utility ─────────────────────────────────────────────────────────────────
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
def _human_size(bytes_: int) -> str:
|
| 193 |
-
if bytes_ < 1024:
|
| 194 |
-
return f"{bytes_} B"
|
| 195 |
-
elif bytes_ < 1024 * 1024:
|
| 196 |
-
return f"{bytes_ / 1024:.1f} KiB"
|
| 197 |
-
else:
|
| 198 |
-
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 |
+
# A regex match cannot establish whether async side effects must be awaited.
|
| 133 |
+
# Retain findings only when the reviewer has evaluated the surrounding code.
|
| 134 |
+
static_findings = []
|
| 135 |
+
|
| 136 |
+
# --- Build the LLM (Gemini primary → Groq fallback) -----------------------
|
| 137 |
+
try:
|
| 138 |
+
llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200, "timeout": 40} if state.review_mode == "fast" else {}))
|
| 139 |
+
except ValueError as exc:
|
| 140 |
+
logger.warning("LLM unavailable — skipping correctness review: %s", exc)
|
| 141 |
+
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
|
| 142 |
+
|
| 143 |
+
# --- Build the prompt ----------------------------------------------------
|
| 144 |
+
user_prompt = _build_prompt(state)
|
| 145 |
+
logger.info(
|
| 146 |
+
"Invoking correctness reviewer (diff=%s, context=%d chunks, prompt=%s, prompt_version=%s)",
|
| 147 |
+
_human_size(len(state.diff or "")),
|
| 148 |
+
len(state.context_chunks),
|
| 149 |
+
_human_size(len(user_prompt)),
|
| 150 |
+
PROMPT_VERSION,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# --- Invoke --------------------------------------------------------------
|
| 154 |
+
try:
|
| 155 |
+
messages = [
|
| 156 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 157 |
+
{"role": "user", "content": user_prompt},
|
| 158 |
+
]
|
| 159 |
+
result: CorrectnessReview = invoke_review(llm, CorrectnessReview, messages, mode=state.review_mode) # type: ignore[assignment]
|
| 160 |
+
except Exception as exc:
|
| 161 |
+
logger.warning("Correctness review LLM call failed: %s", exc)
|
| 162 |
+
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
|
| 163 |
+
|
| 164 |
+
# Deterministic guard for a high-impact async anti-pattern that LLMs can
|
| 165 |
+
# miss: promises created by forEach are not awaited by the caller.
|
| 166 |
+
result.findings.extend(static_findings)
|
| 167 |
+
|
| 168 |
+
# --- Log and return findings ---------------------------------------------
|
| 169 |
+
if result and result.findings:
|
| 170 |
+
logger.info(
|
| 171 |
+
"Correctness review found %d issue(s)",
|
| 172 |
+
len(result.findings),
|
| 173 |
+
)
|
| 174 |
+
for f in result.findings:
|
| 175 |
+
logger.debug(
|
| 176 |
+
" [%.2f] %s:%d–%d — %s",
|
| 177 |
+
f.confidence, f.file_path, f.line_start, f.line_end,
|
| 178 |
+
f.comment[:80],
|
| 179 |
+
)
|
| 180 |
+
else:
|
| 181 |
+
logger.info("Correctness review found no issues")
|
| 182 |
+
|
| 183 |
+
return {
|
| 184 |
+
"findings": result.findings,
|
| 185 |
+
"review_stages": [stage_result("correctness", started, llm=llm)],
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# ─── Utility ─────────────────────────────────────────────────────────────────
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _human_size(bytes_: int) -> str:
|
| 193 |
+
if bytes_ < 1024:
|
| 194 |
+
return f"{bytes_} B"
|
| 195 |
+
elif bytes_ < 1024 * 1024:
|
| 196 |
+
return f"{bytes_ / 1024:.1f} KiB"
|
| 197 |
+
else:
|
| 198 |
+
return f"{bytes_ / (1024 * 1024):.1f} MiB"
|
nodes/review_runtime.py
CHANGED
|
@@ -1,88 +1,88 @@
|
|
| 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 not attempt and type(result).__name__ == 'LengthFinishReasonError':
|
| 70 |
-
# Override the underlying model call on the structured runnable.
|
| 71 |
-
# This shares the original deadline and the single repair allowance.
|
| 72 |
-
current_limit = getattr(llm, 'max_tokens', None) or 2000
|
| 73 |
-
structured = structured.bind(max_tokens=min(max(int(current_limit) * 2, 8192), 16384))
|
| 74 |
-
messages.append({'role': 'user', 'content': 'Return concise JSON only. Limit to the five most important findings, brief evidence and fixes.'})
|
| 75 |
-
continue
|
| 76 |
-
if attempt or not (isinstance(result, ValidationError) or
|
| 77 |
-
type(result).__name__ == "OutputParserException"):
|
| 78 |
-
raise result
|
| 79 |
-
messages.append({"role": "user", "content":
|
| 80 |
-
"The previous response did not match the schema. Return the required JSON object with a findings array."})
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
def stage_result(reviewer, started, *, error=None, llm=None):
|
| 84 |
-
"""Safe stage metadata; exception text may contain secrets, so omit it."""
|
| 85 |
-
return {"reviewer": reviewer, "status": "failed" if error else "completed",
|
| 86 |
-
"error": type(error).__name__ if error else None,
|
| 87 |
-
"duration_seconds": round(time.monotonic() - started, 3),
|
| 88 |
-
"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 not attempt and type(result).__name__ == 'LengthFinishReasonError':
|
| 70 |
+
# Override the underlying model call on the structured runnable.
|
| 71 |
+
# This shares the original deadline and the single repair allowance.
|
| 72 |
+
current_limit = getattr(llm, 'max_tokens', None) or 2000
|
| 73 |
+
structured = structured.bind(max_tokens=min(max(int(current_limit) * 2, 8192), 16384))
|
| 74 |
+
messages.append({'role': 'user', 'content': 'Return concise JSON only. Limit to the five most important findings, brief evidence and fixes.'})
|
| 75 |
+
continue
|
| 76 |
+
if attempt or not (isinstance(result, ValidationError) or
|
| 77 |
+
type(result).__name__ == "OutputParserException"):
|
| 78 |
+
raise result
|
| 79 |
+
messages.append({"role": "user", "content":
|
| 80 |
+
"The previous response did not match the schema. Return the required JSON object with a findings array."})
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def stage_result(reviewer, started, *, error=None, llm=None):
|
| 84 |
+
"""Safe stage metadata; exception text may contain secrets, so omit it."""
|
| 85 |
+
return {"reviewer": reviewer, "status": "failed" if error else "completed",
|
| 86 |
+
"error": type(error).__name__ if error else None,
|
| 87 |
+
"duration_seconds": round(time.monotonic() - started, 3),
|
| 88 |
+
"model": str(getattr(llm, "model_name", None) or getattr(llm, "model", "")) if llm else ""}
|
tests/test_job_speed.py
CHANGED
|
@@ -16,6 +16,15 @@ import pytest
|
|
| 16 |
from fastapi import HTTPException
|
| 17 |
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
def scheduler():
|
| 20 |
tree = ast.parse(Path('api.py').read_text(encoding='utf-8'))
|
| 21 |
names = {'create_review', 'cancel_review', '_public_job', 'get_review', 'decide_review'}
|
|
|
|
| 16 |
from fastapi import HTTPException
|
| 17 |
|
| 18 |
|
| 19 |
+
def test_incomplete_review_never_starts_ragas():
|
| 20 |
+
tree = ast.parse(Path('app.py').read_text(encoding='utf-8'))
|
| 21 |
+
function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == '_ragas_inputs_from_state')
|
| 22 |
+
ns = {}
|
| 23 |
+
exec(compile(ast.Module(body=[function], type_ignores=[]), 'app.py', 'exec'), ns)
|
| 24 |
+
state = SimpleNamespace(values={'verdict': SimpleNamespace(recommendation='incomplete'), 'diff': 'change'})
|
| 25 |
+
assert ns['_ragas_inputs_from_state'](state, 'custom') is None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
def scheduler():
|
| 29 |
tree = ast.parse(Path('api.py').read_text(encoding='utf-8'))
|
| 30 |
names = {'create_review', 'cancel_review', '_public_job', 'get_review', 'decide_review'}
|
tests/test_review_runtime.py
CHANGED
|
@@ -11,6 +11,8 @@ 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):
|
|
@@ -37,6 +39,36 @@ def test_fast_documentation_routes_without_test_specialist():
|
|
| 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
|
|
|
|
| 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 |
+
from nodes.correctness_reviewer import correctness_reviewer_node
|
| 15 |
+
from types import SimpleNamespace
|
| 16 |
|
| 17 |
|
| 18 |
class Review(BaseModel):
|
|
|
|
| 39 |
assert coverage_node(state)['review_stages'][0]['status'] == 'skipped'
|
| 40 |
|
| 41 |
|
| 42 |
+
def test_length_error_gets_one_larger_budget_retry():
|
| 43 |
+
class LengthFinishReasonError(Exception):
|
| 44 |
+
pass
|
| 45 |
+
model = model_with_results(LengthFinishReasonError())
|
| 46 |
+
model.max_tokens = 8192
|
| 47 |
+
structured = model.with_structured_output.return_value
|
| 48 |
+
structured.bind.return_value.invoke.return_value = {'findings': []}
|
| 49 |
+
assert invoke_review(model, Review, []).findings == []
|
| 50 |
+
structured.bind.assert_called_once_with(max_tokens=16384)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_minimax_has_room_for_reasoning_and_json(monkeypatch):
|
| 54 |
+
import sys
|
| 55 |
+
constructor = Mock(side_effect=lambda **kwargs: SimpleNamespace(**kwargs))
|
| 56 |
+
monkeypatch.setitem(sys.modules, 'langchain_openai', SimpleNamespace(ChatOpenAI=constructor))
|
| 57 |
+
from llm_factory import create_endpoint_llm
|
| 58 |
+
model = create_endpoint_llm(SimpleNamespace(name='test', provider='openai',
|
| 59 |
+
model='minimax/minimax-m3.1-flash:free', api_key='fake-key',
|
| 60 |
+
base_url='https://openrouter.ai/api/v1'), max_tokens=1200)
|
| 61 |
+
assert model.max_tokens == 8192
|
| 62 |
+
assert model.extra_body['reasoning']['effort'] == 'low'
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_async_foreach_match_is_not_a_confirmed_finding_when_model_fails(monkeypatch):
|
| 66 |
+
monkeypatch.setattr('nodes.correctness_reviewer.create_llm', Mock(side_effect=ValueError('unavailable')))
|
| 67 |
+
result = correctness_reviewer_node(OpenCodeReviewState(diff='+++ b/test.ts\n@@ -1 +1 @@\n+items.forEach(async (x) => { await save(x); });'))
|
| 68 |
+
assert result['findings'] == []
|
| 69 |
+
assert result['review_stages'][0]['status'] == 'failed'
|
| 70 |
+
|
| 71 |
+
|
| 72 |
def model_with_results(*results):
|
| 73 |
model = Mock()
|
| 74 |
model.with_structured_output.return_value.invoke.side_effect = results
|