Spaces:
Running
Download FIXES.md from Sdm0/opencodereview: direct link, hf CLI and curl.
- Browser
- Download file 20.9 kB
-
https://huggingface.co/spaces/Sdm0/opencodereview/resolve/main/FIXES.md
- Command line
-
hf download hf://spaces/Sdm0/opencodereview/FIXES.md
-
curl -L -o FIXES.md https://huggingface.co/spaces/Sdm0/opencodereview/resolve/main/FIXES.md
π§ OpenCodeReview β Necessary Fixes Guide
A plain-English, verified guide to the issues found in
CODE_REVIEW.md. Every issue below was independently confirmed against the actual code and the installed packages (langfuse 4.13.1, langchain 1.3.14, langgraph 1.2.9, langgraph-checkpoint-sqlite 3.1.0, langchain-groq 1.1.2, chromadb 1.5.8, ragas 0.3.8) on 2026-07-31.β οΈ Two claims in the original review turned out to be wrong β see Β§8 "Claims that are NOT true".
π Table of Contents
- Fix Summary (TL;DR)
- π Real bugs β high priority
- π¦ Dependency hardening
- π Observability & Langfuse
- π§Ή Code quality, eval & docs
- π§ͺ Testing
- Suggested order of work
- Claims in CODE_REVIEW.md that are NOT true
- Master checklist
ποΈ Fix Summary (TL;DR)
| # | Fix | Priority | Effort | Verified? |
|---|---|---|---|---|
| 1 | Add missing import requests in nodes/executor.py |
π High | 1 line | β |
| 2 | Close the SQLite connection in graph.py |
π High | ~10 lines | β |
| 3 | Pin langfuse + other unpinned dependencies |
π High | 5 min | β |
| 4 | Stop swallowing Langfuse/RAGAS errors silently | π High | ~20 lines | β |
| 5 | Link Langfuse scores to a real trace id (the reported bug) | π High | ~30 lines | β |
| 6 | One canonical RAGAS-score name (ragas_ prefix everywhere) |
π‘ Medium | ~15 lines | β |
| 7 | Forward observability env vars in docker-compose.yml |
π‘ Medium | 5 lines | β |
| 8 | RAGAS: use None for failed metrics (NOT 0.0) β with all consumers updated |
π‘ Medium | ~40 lines | β |
| 9 | Remove dead passthrough.py / post_results.py nodes |
π‘ Medium | delete 2 files | β |
| 10 | Centralise duplicated constants (GROQ_MODEL, _human_size, β¦) |
π’ Low | ~30 lines | β |
| 11 | Add Gemini pricing to cost tracking | π’ Low | ~10 lines | β |
| 12 | Fix README Python-version mismatch + docstring nits | π’ Low | 2 lines | β |
| 13 | Fix executor PR-head-SHA race logging | π’ Low | 3 lines | β |
| 14 | Add automated tests (pytest) | π’ Low | ongoing | β |
π Real bugs β high priority
Fix 1 β Missing import requests in nodes/executor.py (latent crash)
What's the problem? nodes/executor.py uses requests.RequestException
at lines 46, 104 and 127 (in _fetch_pr_head_sha, _post_review_comment,
_post_issue_comment), but never imports requests.
Why it matters? The moment a GitHub API call fails with a network error, the
except requests.RequestException clause itself raises
NameError: name 'requests' is not defined β crashing the executor instead of
degrading gracefully. It hasn't bitten you only because the happy path never hits it.
The fix β add one line to the imports:
# nodes/executor.py, at the top with the other imports
import logging
import os
import requests # β ADD THIS
from typing import Any
How to verify: python -c "import ast; ast.parse(open('nodes/executor.py').read())" and grep that requests is imported before use.
Fix 2 β SQLite connection never closed in graph.py
What's the problem? graph.py opens a SQLite connection
(conn = sqlite3.connect(...), ~line 101) for the SqliteSaver checkpointer and
never closes it. The Gradio UI calls build_graph() on every review, so
each review leaks a file handle + DB.
Why it matters? On Windows, the open handle means _cleanup_db() hits
PermissionError (that's literally why the except PermissionError: pass
exists in main.py:461). Handles accumulate across reviews in the long-running UI.
The fix β close the connection when the checkpointer is done. Note:
SqliteSaver.from_conn_string() is a context manager, but it does not accept
your custom serde= (verified in langgraph 3.1.0), so keep the explicit conn
and close it explicitly. Stash the connection on the compiled graph so callers
can reach it β this works in langgraph 1.x (CompiledStateGraph is a plain
class; no __slots__), though it's an informal pattern:
# graph.py β after compile, expose the conn for cleanup
conn = sqlite3.connect(resolved_path, check_same_thread=False)
saver = SqliteSaver(conn, serde=serde)
compiled = builder.compile(checkpointer=saver)
compiled._opencodereview_conn = conn # informal handle for callers
return compiled
Then close it where each run finishes. CLI (main.py review()):
graph = build_graph(DB_PATH)
try:
if smoke:
_test_offline(graph)
else:
_run_with_hitl(graph, repo, pr_number)
finally:
conn = getattr(graph, "_opencodereview_conn", None)
if conn:
conn.close()
_cleanup_db()
For the Gradio UI (app.py), close the connection after the executor completes
in resume_review(), and in run_smoke() after streaming finishes.
β οΈ Caution (important): do not close while a graph run is still paused at
human_approval β the checkpointer must stay open across the interrupt/resume.
resume_review() builds a fresh graph from the same DB file, so closing the
first connection after _build_and_stream() completes is safe only because
checkpoints are persisted to disk; keep the close in the resume/cleanup path, not
mid-stream.
π¦ Dependency hardening
Fix 3 β Pin dependencies (prevents this whole class of bug)
What's the problem? requirements.txt leaves several packages unpinned, so a
fresh pip install can silently pull breaking major versions. This is why
Langfuse broke: unpinned langfuse now resolves to v4 (4.13.1 installed here),
while parts of the code still use v3-style calls.
The fix β pin to the exact versions verified working in this environment:
langfuse>=4.13,<5 # β pin! (v4 era; see Fix 5 for the API work)
langchain==1.3.14
langgraph==1.2.9
langgraph-checkpoint-sqlite==3.1.0
chromadb==1.5.8
langchain-groq==1.1.2
Then generate a lockfile so builds are reproducible:
pip freeze > requirements.lock
π Observability & Langfuse
Fix 4 β Stop silently swallowing errors (esp. Langfuse)
What's the problem? Several places catch except Exception and only log a
warning (or nothing), hiding real failures:
| Location | What's swallowed |
|---|---|
observability.py:652 log_langfuse_score |
ALL Langfuse errors β score silently dropped |
observability.py:532 TokenCostCallback.on_llm_end |
cost-tracking errors (fine) |
nodes/correctness_reviewer.py:147-149 |
LLM failure β return {} (review silently empty) |
nodes/aggregator.py (~247) |
LLM critic failure β silent rule-based fallback |
eval_data/ragas_eval.py (several) |
metric failure β silently sets 0.0 |
eval_data/evaluate.py (~530) |
whole RAGAS block β warning, continues |
Why it matters? This is exactly why the Langfuse bug survived two "fix" commits: you could never see the real error. Silent bugs are invisible bugs.
The fix β fail loudly where it matters:
log_langfuse_scoreβ log at ERROR with the full payload, and add a debug mode that re-raises:except Exception as exc: if os.environ.get("OCR_OBSERVABILITY_STRICT") == "1": raise logger.error( "Failed to log Langfuse score '%s'=%.4f (trace_id=%s, comment=%s): %s", name, value, resolved_trace_id, comment, exc, )- Reviewer nodes β when the LLM fails, emit a clear INFO so a missing review
is obvious in the run log:
except Exception as exc: logger.warning("Correctness review LLM call failed: %s β skipping reviewer", exc)
Fix 5 β Make RAGAS/Langfuse scores actually appear on traces
The verified picture (differs from CODE_REVIEW.md's "confirmed" root cause):
- β
Real:
langfuseis unpinned β v4 (4.13.1) is installed while the code mixes v3+v4 idioms. - β
Real:
log_langfuse_scorebuilds a newLangfuse()per call, swallows all errors, andcreate_scorewithtrace_id=Nonecreates an orphaned score (won't show on the trace page). - β
Real: the
run_trace_idis captured once right after the graph completes β and the code's own comment admits it "can return None after ~60s delays because contextvars may be lost". - β NOT true (verified against installed v4.13.1): "v4 ignores
LANGFUSE_HOST" β v4.13.1 still honours it (deprecated fallback); "the trace-ID accessors don't exist in v4" βhandler.last_trace_idandLangfuse().get_current_trace_id()both exist in 4.13.1.
The fix (practical, low-risk):
- Pin langfuse (Fix 3) so the API can't shift under you again.
- Capture the trace id as early as possible β the code already does this
(
run_trace_id = _resolve_langfuse_trace_id(handler)right after streaming); keep it, and add a log line so you can see whether it'sNone:logger.info("Langfuse trace_id resolved: %s", run_trace_id) - Use one shared client instead of a fresh
Langfuse()per score call:from langfuse import get_client # v4 singleton β verified available in 4.13.1 lf = get_client() - Flush once per run, not per score. Current code calls
lf.flush()insidelog_langfuse_score(every score). Move flushing to the end of the run (main.pyafter RAGAS block;app.pyafter_build_and_stream). - Set both env vars (harmless, future-proof): in
.envsetLANGFUSE_BASE_URLand keepLANGFUSE_HOSTas an alias. - Remove the silent swallow (see Fix 4) so a failing score is visible.
How to verify: run a review with Langfuse keys set, then check:
- the log prints a non-
Nonetrace_id; - the Langfuse UI trace page shows
ragas_*scores; - no
ERROR Failed to log Langfuse scorelines appear.
Fix 6 β One canonical RAGAS-score naming path
What's the problem? The same metric is logged under different names depending on entry point:
app.py/main.pyβragas_<metric>β (canonical)eval_data/ragas_eval.pylog_ragas_scores_to_langfuseβ alsoragas_<metric>βeval_data/evaluate.py_log_to_observabilityβ rawlf.create_score(name=ragas_key, β¦)β no prefix
So ragas_context_precision vs context_precision appear as different scores
in dashboards.
The fix: route everything through observability.log_langfuse_score with the
ragas_ prefix. In evaluate.py _log_to_observability, replace the direct
lf.create_score(name=ragas_key, ...) loop with:
from observability import log_langfuse_score
for ragas_key in ("context_precision", "context_recall",
"faithfulness", "answer_relevancy", "mmr"):
if ragas_key in r:
log_langfuse_score(
name=f"ragas_{ragas_key}",
value=r[ragas_key],
comment=pr_comment,
trace_id=pr_trace_id,
)
Fix 7 β Forward observability env vars in docker-compose.yml
What's the problem? docker-compose.yml (lines 33-40) only forwards
GROQ_API_KEY, OPENCODEREVIEW_ANTHROPIC_KEY, GITHUB_TOKEN, and LANG β so
Gemini, Langfuse and LangSmith are silently off inside Docker/HF Spaces.
The fix β add the missing lines to the environment: block:
environment:
# AI provider keys
- GROQ_API_KEY=${GROQ_API_KEY:-}
- GEMINI_API_KEY=${GEMINI_API_KEY:-}
- OPENCODEREVIEW_ANTHROPIC_KEY=${OPENCODEREVIEW_ANTHROPIC_KEY:-}
# GitHub
- GITHUB_TOKEN=${GITHUB_TOKEN:-}
# Observability (optional)
- LANGFUSE_PUBLIC_KEY=${LANGFUSE_PUBLIC_KEY:-}
- LANGFUSE_SECRET_KEY=${LANGFUSE_SECRET_KEY:-}
- LANGFUSE_HOST=${LANGFUSE_HOST:-}
- LANGFUSE_BASE_URL=${LANGFUSE_BASE_URL:-}
- LANGSMITH_API_KEY=${LANGSMITH_API_KEY:-}
- LANGSMITH_PROJECT=${LANGSMITH_PROJECT:-}
# Language
- LANG=en_US.UTF-8
On Hugging Face Spaces, add the same keys as Secrets (Settings β Secrets).
π§Ή Code quality, eval & docs
Fix 8 β RAGAS: failed metric = None, not 0.0 (update ALL consumers)
What's the problem? In eval_data/ragas_eval.py, when a metric fails
(rate limit, LLM error) it sets that metric to 0.0. A real failure becomes
indistinguishable from a genuine score of zero, and the averages in
evaluate.py / ragas_eval.py main() silently include these fake zeros.
β οΈ Do this as a set β changing only ragas_eval.py will crash the UI and the
standalone CLI. Five other places assume every value is a float:
1. eval_data/ragas_eval.py β set None on failure and widen the type:
scores: dict[str, float | None] = {}
# inside each except block:
except Exception as exc:
logger.warning("RAGAS context_precision failed: %s", exc)
scores["context_precision"] = None # β not 0.0
2. app.py _format_ragas_scores β skip None values (it currently does
int(value * 100) β TypeError on None):
for key, value in scores.items():
if value is None:
continue # β skip failed metrics in the UI card
...
3. main.py / app.py RAGAS-logging loops β skip None before logging:
for metric_name, value in ragas_scores.items():
if value is None:
continue # β don't send None to create_score
log_langfuse_score(name=f"ragas_{metric_name}", value=value, ...)
4. eval_data/evaluate.py + ragas_eval.py main() averages β exclude None:
values = [s.get(metric) for s in all_scores if s.get(metric) is not None]
avg = sum(values) / len(values) if values else None
5. ragas_eval.py standalone CLI β its per-PR print does f"{k}={v:.3f}"
which raises TypeError on None; filter them out:
print(f" {repo}#{pr}: " + " | ".join(
f"{k}={v:.3f}" for k, v in scores.items()
if k not in ("repo", "pr_number", "id") and v is not None
))
6. Widen the function signatures so type checkers stay happy:
# ragas_eval.py
def compute_ragas_retrieval_scores(...) -> dict[str, float | None]: ...
def log_ragas_scores_to_langfuse(scores: dict[str, float | None], ...) -> None: ...
# app.py
ragas_scores: dict[str, float | None] = {}
Fix 9 β Remove dead nodes
What's the problem? nodes/__init__.py imports passthrough_node and
post_results_node, but graph.py never wires them into the graph β they are
dead code (and post_results.py duplicates executor logic that was superseded).
The fix: delete nodes/passthrough.py and nodes/post_results.py, and remove
their two import/__all__ lines from nodes/__init__.py.
Fix 10 β Centralise duplicated constants
What's the problem? GROQ_MODEL, DEFAULT_TEMPERATURE, and _human_size
are copy-pasted across llm_factory.py, nodes/aggregator.py,
nodes/correctness_reviewer.py, and nodes/retrieval.py. Drift is inevitable.
The fix: create constants.py with the shared values, import everywhere:
# constants.py
GROQ_MODEL = "llama-3.3-70b-versatile"
GEMINI_MODEL = "gemini-3.1-flash-lite"
DEFAULT_TEMPERATURE = 0.0
def human_size(bytes_: int) -> str: ...
Fix 11 β Add Gemini pricing to cost tracking
What's the problem? observability.py:275 GROQ_PRICING only knows
llama-3.3-70b-versatile + a pessimistic default. The primary LLM is Gemini
(gemini-3.1-flash-lite), so every Gemini run is costed at the wrong default rate.
The fix: add a MODEL_PRICING table keyed by model name (add Gemini's
published per-1M-token rates) and look up by model from llm_output (already
captured at observability.py:514).
Fix 12 β README / docstring nits
README.md:22badge says Python 3.11+ butDockerfile:25,56uses python:3.12-slim β align both on 3.12.observability.pymodule docstring has a malformedBackends -------- *header β tidy it.
Fix 13 β Executor stale-SHA logging
What's the problem? executor.py fetches the PR head SHA right before posting;
a force-push in between can make the SHA fetch fail or target stale lines. The 422
fallback already handles it, but the failure reason is only a generic warning.
The fix: log the specific failure reason in _fetch_pr_head_sha and count
fallback occurrences (a small counter like inline_failed already exists β add
metrics for the 422 path).
π§ͺ Testing
Fix 14 β Add automated tests
What's the problem? There are no tests (README:566 admits it). Bugs like the Langfuse one survive multiple fix attempts because nothing guards them.
The fix β start with the cheap, pure-function tests:
pip install pytest
mkdir tests
# tests/test_observability.py
def test_estimate_groq_cost():
from observability import estimate_groq_cost
assert estimate_groq_cost("llama-3.3-70b-versatile", 1_000_000, 0) == 0.59
Cover first: aggregator._deduplicate, evaluate._fuzzy_match,
observability.estimate_groq_cost, config._mask_key. Then add a
Langfuse-score test with a mocked client asserting create_score is called
with a non-None trace_id β that single test would have caught the reported bug.
ποΈ Suggested order of work
- This week: Fix 1 (
import requests) β Fix 2 (SQLite close) β Fix 3 (pin deps). - Then: Fix 4 + Fix 5 (Langfuse visibility & score linking) β Fix 6 (naming).
- When time allows: Fixes 7β13, then Fix 14 (tests) as the safety net.
β Claims in CODE_REVIEW.md that are NOT true
| Claim | Reality (verified) |
|---|---|
"v4 doesn't read LANGFUSE_HOST β host var is ignored" |
β False. langfuse 4.13.1 reads LANGFUSE_BASE_URL or falls back to LANGFUSE_HOST (client.py:317-319). HOST is deprecated, not ignored. |
"v4 handler doesn't expose trace_id/last_trace_id; get_current_trace_id() is not a v4 idiom β all resolve to None" |
β Mostly false. In 4.13.1, handler.last_trace_id exists (set in CallbackHandler.py:638) and Langfuse().get_current_trace_id() exists (client.py:2271). Only handler.trace_id is v3-only. |
"P1.5: evaluate.py never stores per-PR trace_id, so scores are always orphaned" |
β Already fixed. evaluate.py _run_graph_for_pr returns trace_id and main() stores it (metrics["trace_id"] = trace_id), passed to lf.create_score(trace_id=β¦). (Commit a24aa92 fixed this.) |
"Unpinned langfuse pulls v4.14.2" |
β οΈ Version number off β installed here is 4.13.1 (still v4, so the v3/v4 mixing point stands). |
π Master checklist
- 1. Add
import requeststonodes/executor.py - 2. Expose + close the checkpointer connection in
graph.py/main.py/app.py - 3. Pin
langfuse,langchain,langgraph,langgraph-checkpoint-sqlite,chromadb,langchain-groq; addrequirements.lock - 4. ERROR-log Langfuse failures (+
OCR_OBSERVABILITY_STRICT=1re-raise); INFO-log skipped reviewers - 5. Verify
run_trace_idis non-None; useget_client(); flush once per run; setLANGFUSE_BASE_URLtoo - 6. Route
evaluate.pyRAGAS scores throughlog_langfuse_scorewithragas_prefix - 7. Add
GEMINI_API_KEY+LANGFUSE_*+LANGSMITH_*todocker-compose.yml+ HF Secrets - 8. RAGAS failed metrics β
Noneand guard app.py formatter, log loops, and averages - 9. Delete
nodes/passthrough.py+nodes/post_results.py(+__init__lines) - 10. Centralise
GROQ_MODEL/GEMINI_MODEL/DEFAULT_TEMPERATURE/human_size - 11. Add Gemini pricing table to
observability.py - 12. Align README badge β Dockerfile on Python 3.12; tidy docstring
- 13. Log executor 422/stale-SHA fallback metrics
- 14. Add
pytest+tests/(pure functions first, then a mocked Langfuse score test)
Verification commands after any change:
python -m compileall . # syntax check python -m main review --smoke # offline graph smoke test python -m main doctor # health check pip check # dependency consistency