Spaces:
Running
Running
Deploy 57f76af1
Browse files- .env.example +5 -0
- nodes/correctness_reviewer.py +4 -4
- nodes/review_runtime.py +19 -3
- nodes/security_reviewer.py +2 -2
- nodes/test_coverage_reviewer.py +2 -2
- tests/test_review_runtime.py +24 -0
.env.example
CHANGED
|
@@ -108,3 +108,8 @@ GITHUB_TOKEN=ghp_your_token_here
|
|
| 108 |
#
|
| 109 |
# [Recommended] Comma-separated browser origins allowed to call the API.
|
| 110 |
# OCR_ALLOWED_ORIGINS=https://your-frontend.example.com
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
#
|
| 109 |
# [Recommended] Comma-separated browser origins allowed to call the API.
|
| 110 |
# OCR_ALLOWED_ORIGINS=https://your-frontend.example.com
|
| 111 |
+
|
| 112 |
+
# Reviewer wall-clock budgets, including any response-format repair.
|
| 113 |
+
# Fast mode reduces input/output size; it does not impose a hidden 45s cap.
|
| 114 |
+
# OCR_REVIEWER_TIMEOUT_SECONDS=90
|
| 115 |
+
# OCR_FAST_REVIEWER_TIMEOUT_SECONDS=90
|
nodes/correctness_reviewer.py
CHANGED
|
@@ -8,7 +8,7 @@ from pathlib import Path
|
|
| 8 |
|
| 9 |
from llm_factory import create_llm
|
| 10 |
from nodes.finding_quality import calibrate_findings
|
| 11 |
-
from nodes.review_runtime import changed_context, invoke_review, stage_result
|
| 12 |
from pydantic import BaseModel, Field
|
| 13 |
|
| 14 |
from state import Finding, OpenCodeReviewState, Severity
|
|
@@ -136,10 +136,10 @@ def correctness_reviewer_node(state: OpenCodeReviewState) -> dict:
|
|
| 136 |
|
| 137 |
# --- Build the LLM (Gemini primary → Groq fallback) -----------------------
|
| 138 |
try:
|
| 139 |
-
llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200
|
| 140 |
except ValueError as exc:
|
| 141 |
logger.warning("LLM unavailable — skipping correctness review: %s", exc)
|
| 142 |
-
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
|
| 143 |
|
| 144 |
# --- Build the prompt ----------------------------------------------------
|
| 145 |
user_prompt = _build_prompt(state)
|
|
@@ -160,7 +160,7 @@ def correctness_reviewer_node(state: OpenCodeReviewState) -> dict:
|
|
| 160 |
result: CorrectnessReview = invoke_review(llm, CorrectnessReview, messages, mode=state.review_mode) # type: ignore[assignment]
|
| 161 |
except Exception as exc:
|
| 162 |
logger.warning("Correctness review LLM call failed: %s", exc)
|
| 163 |
-
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc)]}
|
| 164 |
|
| 165 |
# Deterministic guard for a high-impact async anti-pattern that LLMs can
|
| 166 |
# miss: promises created by forEach are not awaited by the caller.
|
|
|
|
| 8 |
|
| 9 |
from llm_factory import create_llm
|
| 10 |
from nodes.finding_quality import calibrate_findings
|
| 11 |
+
from nodes.review_runtime import changed_context, invoke_review, stage_result, reviewer_timeout
|
| 12 |
from pydantic import BaseModel, Field
|
| 13 |
|
| 14 |
from state import Finding, OpenCodeReviewState, Severity
|
|
|
|
| 136 |
|
| 137 |
# --- Build the LLM (Gemini primary → Groq fallback) -----------------------
|
| 138 |
try:
|
| 139 |
+
llm = create_llm(endpoint=state.endpoint or None, timeout=reviewer_timeout(state.review_mode), **({"max_tokens": 1200} if state.review_mode == "fast" else {}))
|
| 140 |
except ValueError as exc:
|
| 141 |
logger.warning("LLM unavailable — skipping correctness review: %s", exc)
|
| 142 |
+
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc, llm=locals().get("llm"))]}
|
| 143 |
|
| 144 |
# --- Build the prompt ----------------------------------------------------
|
| 145 |
user_prompt = _build_prompt(state)
|
|
|
|
| 160 |
result: CorrectnessReview = invoke_review(llm, CorrectnessReview, messages, mode=state.review_mode) # type: ignore[assignment]
|
| 161 |
except Exception as exc:
|
| 162 |
logger.warning("Correctness review LLM call failed: %s", exc)
|
| 163 |
+
return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc, llm=llm)]}
|
| 164 |
|
| 165 |
# Deterministic guard for a high-impact async anti-pattern that LLMs can
|
| 166 |
# miss: promises created by forEach are not awaited by the caller.
|
nodes/review_runtime.py
CHANGED
|
@@ -25,6 +25,12 @@ def changed_context(changed_file, mode):
|
|
| 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 |
|
|
@@ -32,9 +38,7 @@ def invoke_review(llm, schema, messages, mode="thorough"):
|
|
| 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 =
|
| 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. "
|
|
@@ -82,7 +86,19 @@ def invoke_review(llm, schema, messages, mode="thorough"):
|
|
| 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 ""}
|
|
|
|
| 25 |
return '\n'.join(f'{index + 1}: {lines[index]}' for index in sorted(selected)) if selected else content
|
| 26 |
|
| 27 |
|
| 28 |
+
def reviewer_timeout(mode="thorough"):
|
| 29 |
+
"""Fast controls prompt size; hosted inference gets its own configurable budget."""
|
| 30 |
+
default = os.getenv("OCR_REVIEWER_TIMEOUT_SECONDS", "90")
|
| 31 |
+
return float(os.getenv("OCR_FAST_REVIEWER_TIMEOUT_SECONDS", default)) if mode == "fast" else float(default)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
def invoke_review(llm, schema, messages, mode="thorough"):
|
| 35 |
"""One request plus one format repair, within a total wall-clock budget.
|
| 36 |
|
|
|
|
| 38 |
SDK that ignores its native request timeout. Native timeouts still close
|
| 39 |
underlying connections; timed-out workers never modify graph state.
|
| 40 |
"""
|
| 41 |
+
budget = reviewer_timeout(mode)
|
|
|
|
|
|
|
| 42 |
deadline = time.monotonic() + budget
|
| 43 |
instructions = (
|
| 44 |
"Return ONLY a JSON object matching this schema, never a bare list. "
|
|
|
|
| 86 |
|
| 87 |
def stage_result(reviewer, started, *, error=None, llm=None):
|
| 88 |
"""Safe stage metadata; exception text may contain secrets, so omit it."""
|
| 89 |
+
kind = type(error).__name__ if error else ""
|
| 90 |
+
status = getattr(error, "status_code", None)
|
| 91 |
+
reason = None
|
| 92 |
+
if status == 401 or "AuthenticationError" in kind:
|
| 93 |
+
reason = "Provider rejected authentication. Check the saved API key and API base URL; use a key issued by that provider."
|
| 94 |
+
elif status == 429 or "RateLimitError" in kind:
|
| 95 |
+
reason = "Provider rate limit or shared capacity reached. Retry later or select another saved provider."
|
| 96 |
+
elif isinstance(error, TimeoutError) or "Timeout" in kind:
|
| 97 |
+
reason = "Provider did not finish within the reviewer deadline. Try a smaller PR or increase the server reviewer timeout."
|
| 98 |
+
elif error:
|
| 99 |
+
reason = "Reviewer failed. Check the backend logs for the provider or response-format error."
|
| 100 |
return {"reviewer": reviewer, "status": "failed" if error else "completed",
|
| 101 |
+
"reason": reason,
|
| 102 |
"error": type(error).__name__ if error else None,
|
| 103 |
"duration_seconds": round(time.monotonic() - started, 3),
|
| 104 |
"model": str(getattr(llm, "model_name", None) or getattr(llm, "model", "")) if llm else ""}
|
nodes/security_reviewer.py
CHANGED
|
@@ -7,7 +7,7 @@ from pathlib import Path
|
|
| 7 |
|
| 8 |
from llm_factory import create_llm
|
| 9 |
from nodes.finding_quality import calibrate_findings
|
| 10 |
-
from nodes.review_runtime import changed_context, invoke_review, stage_result
|
| 11 |
from pydantic import BaseModel, Field
|
| 12 |
|
| 13 |
from state import Finding, OpenCodeReviewState
|
|
@@ -102,7 +102,7 @@ def security_reviewer_node(state: OpenCodeReviewState) -> dict:
|
|
| 102 |
return {}
|
| 103 |
|
| 104 |
try:
|
| 105 |
-
llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200
|
| 106 |
except ValueError as exc:
|
| 107 |
logger.warning("LLM unavailable — skipping security review: %s", exc)
|
| 108 |
return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
|
|
|
|
| 7 |
|
| 8 |
from llm_factory import create_llm
|
| 9 |
from nodes.finding_quality import calibrate_findings
|
| 10 |
+
from nodes.review_runtime import changed_context, invoke_review, stage_result, reviewer_timeout
|
| 11 |
from pydantic import BaseModel, Field
|
| 12 |
|
| 13 |
from state import Finding, OpenCodeReviewState
|
|
|
|
| 102 |
return {}
|
| 103 |
|
| 104 |
try:
|
| 105 |
+
llm = create_llm(endpoint=state.endpoint or None, timeout=reviewer_timeout(state.review_mode), **({"max_tokens": 1200} if state.review_mode == "fast" else {}))
|
| 106 |
except ValueError as exc:
|
| 107 |
logger.warning("LLM unavailable — skipping security review: %s", exc)
|
| 108 |
return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
|
nodes/test_coverage_reviewer.py
CHANGED
|
@@ -7,7 +7,7 @@ from pathlib import Path
|
|
| 7 |
|
| 8 |
from llm_factory import create_llm
|
| 9 |
from nodes.finding_quality import calibrate_findings
|
| 10 |
-
from nodes.review_runtime import changed_context, invoke_review, stage_result
|
| 11 |
from pydantic import BaseModel, Field
|
| 12 |
|
| 13 |
from state import Finding, OpenCodeReviewState
|
|
@@ -109,7 +109,7 @@ def test_coverage_reviewer_node(state: OpenCodeReviewState) -> dict:
|
|
| 109 |
'reason': 'Fast mode: documentation-only changes', 'duration_seconds': 0.0, 'model': ''}]}
|
| 110 |
|
| 111 |
try:
|
| 112 |
-
llm = create_llm(endpoint=state.endpoint or None, **({"max_tokens": 1200
|
| 113 |
except ValueError as exc:
|
| 114 |
logger.warning("LLM unavailable — skipping test-coverage review: %s", exc)
|
| 115 |
return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
|
|
|
|
| 7 |
|
| 8 |
from llm_factory import create_llm
|
| 9 |
from nodes.finding_quality import calibrate_findings
|
| 10 |
+
from nodes.review_runtime import changed_context, invoke_review, stage_result, reviewer_timeout
|
| 11 |
from pydantic import BaseModel, Field
|
| 12 |
|
| 13 |
from state import Finding, OpenCodeReviewState
|
|
|
|
| 109 |
'reason': 'Fast mode: documentation-only changes', 'duration_seconds': 0.0, 'model': ''}]}
|
| 110 |
|
| 111 |
try:
|
| 112 |
+
llm = create_llm(endpoint=state.endpoint or None, timeout=reviewer_timeout(state.review_mode), **({"max_tokens": 1200} if state.review_mode == "fast" else {}))
|
| 113 |
except ValueError as exc:
|
| 114 |
logger.warning("LLM unavailable — skipping test-coverage review: %s", exc)
|
| 115 |
return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
|
tests/test_review_runtime.py
CHANGED
|
@@ -6,6 +6,7 @@ import pytest
|
|
| 6 |
from pydantic import BaseModel, Field, ValidationError
|
| 7 |
|
| 8 |
from nodes.review_runtime import invoke_review
|
|
|
|
| 9 |
from nodes.aggregator import aggregator_node
|
| 10 |
from nodes.security_reviewer import security_reviewer_node
|
| 11 |
from state import OpenCodeReviewState
|
|
@@ -19,6 +20,29 @@ class Review(BaseModel):
|
|
| 19 |
findings: list = Field(default_factory=list)
|
| 20 |
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
def test_tracing_context_survives_deadline_worker():
|
| 23 |
trace = ContextVar('test_trace', default='missing')
|
| 24 |
token = trace.set('active-trace')
|
|
|
|
| 6 |
from pydantic import BaseModel, Field, ValidationError
|
| 7 |
|
| 8 |
from nodes.review_runtime import invoke_review
|
| 9 |
+
from nodes.review_runtime import reviewer_timeout, stage_result
|
| 10 |
from nodes.aggregator import aggregator_node
|
| 11 |
from nodes.security_reviewer import security_reviewer_node
|
| 12 |
from state import OpenCodeReviewState
|
|
|
|
| 20 |
findings: list = Field(default_factory=list)
|
| 21 |
|
| 22 |
|
| 23 |
+
def test_fast_timeout_is_configurable_without_hidden_cap(monkeypatch):
|
| 24 |
+
monkeypatch.setenv('OCR_REVIEWER_TIMEOUT_SECONDS', '90')
|
| 25 |
+
monkeypatch.delenv('OCR_FAST_REVIEWER_TIMEOUT_SECONDS', raising=False)
|
| 26 |
+
assert reviewer_timeout('fast') == 90
|
| 27 |
+
monkeypatch.setenv('OCR_FAST_REVIEWER_TIMEOUT_SECONDS', '120')
|
| 28 |
+
assert reviewer_timeout('fast') == 120
|
| 29 |
+
assert reviewer_timeout('thorough') == 90
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@pytest.mark.parametrize('status,expected', [(401, 'authentication'), (429, 'rate limit')])
|
| 33 |
+
def test_error_reason_is_actionable_without_echoing_credentials(status, expected):
|
| 34 |
+
error = RuntimeError('secret-key-in-provider-message')
|
| 35 |
+
error.status_code = status
|
| 36 |
+
result = stage_result('security', time.monotonic(), error=error)
|
| 37 |
+
assert expected in result['reason']
|
| 38 |
+
assert 'secret-key' not in str(result)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_timeout_reason_is_actionable():
|
| 42 |
+
result = stage_result('correctness', time.monotonic(), error=TimeoutError())
|
| 43 |
+
assert 'deadline' in result['reason']
|
| 44 |
+
|
| 45 |
+
|
| 46 |
def test_tracing_context_survives_deadline_worker():
|
| 47 |
trace = ContextVar('test_trace', default='missing')
|
| 48 |
token = trace.set('active-trace')
|