#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ForgeBench v2 driver: run the dual-target evaluation over an answers.jsonl file. answers.jsonl rows: {"task_id": "...", "answer": ""} {"task_id": "...", "files": {"src/main/java/...": "", ...}} # multi-file Usage: python3 run_benchmark.py --data forgebench_v2_full.jsonl --answers answers.jsonl \ [--workdir build_ws] [--out report.json] [--skip-compile] [--dry-run] Routing per task (v2): * must_compile=true -> ast_eval static gate (target-aware) + sandbox_runner compile check against the task's own target (forge-1.20.1 or neoforge-1.21.1, auto-derived) * module=debug -> judge_prompt.txt contract; static JSON-shape check here * module=build -> static required-token + forbidden check (no Gradle) * multi_file answers -> staged via --candidate-dir; single-file via --code-file * gametest_required -> gametest_runner (only when --run-gametests AND >=8G RAM) Aggregate: per-target x per-module Pass@1, AST pass rate, judge pass rate. """ from __future__ import annotations import argparse import json import subprocess import sys import tempfile from pathlib import Path HERE = Path(__file__).resolve().parent def load_jsonl(path: Path) -> list[dict]: return [json.loads(l) for l in path.read_text(encoding="utf-8").splitlines() if l.strip()] def run_ast(task: dict, answer_files: dict[str, str] | None, answer: str | None, workdir: Path) -> dict: tf = workdir / "task.json" tf.write_text(json.dumps(task, ensure_ascii=False), encoding="utf-8") cmd = [sys.executable, str(HERE / "ast_eval.py"), "--task", str(tf)] if answer_files is not None: cdir = workdir / "candidate" cdir.mkdir(exist_ok=True) for rel, content in answer_files.items(): dest = cdir / rel dest.parent.mkdir(parents=True, exist_ok=True) dest.write_text(content, encoding="utf-8") cmd += ["--candidate-dir", str(cdir)] else: cf = workdir / "answer.java" cf.write_text(answer or "", encoding="utf-8") cmd += ["--code", str(cf)] proc = subprocess.run(cmd, capture_output=True, text=True) try: return json.loads(proc.stdout) except json.JSONDecodeError: return {"passed": False, "score": 0.0, "error": proc.stderr[-500:]} def run_sandbox(task: dict, answer_files: dict[str, str] | None, answer: str | None, workdir: Path, dry: bool) -> dict: tf = workdir / "task.json" tf.write_text(json.dumps(task, ensure_ascii=False), encoding="utf-8") cmd = [sys.executable, str(HERE / "sandbox_runner.py"), "--task-file", str(tf), "--workdir", str(workdir / "ws")] if answer_files is not None: cdir = workdir / "candidate" cmd += ["--candidate-dir", str(cdir)] else: cf = workdir / "answer.java" cf.write_text(answer or "", encoding="utf-8") cmd += ["--code-file", str(cf)] if dry: cmd.append("--dry-run") proc = subprocess.run(cmd, capture_output=True, text=True) try: return json.loads(proc.stdout) except json.JSONDecodeError: return {"passed": False, "error": proc.stderr[-500:]} def main() -> int: p = argparse.ArgumentParser() p.add_argument("--data", required=True) p.add_argument("--answers", required=True) p.add_argument("--out", default=None) p.add_argument("--workdir", default=None) p.add_argument("--dry-run", action="store_true") p.add_argument("--skip-compile", action="store_true", help="AST/static gate only (no Gradle) - offline mode") p.add_argument("--scores", default=None, help="JSON {task_id: {score, verdict,...}} for debug/build tasks") args = p.parse_args() tasks = {t["task_id"]: t for t in load_jsonl(Path(args.data))} answers = load_jsonl(Path(args.answers)) scores = json.loads(Path(args.scores).read_text()) if args.scores else {} workdir = Path(args.workdir or tempfile.mkdtemp(prefix="forgebench_run_")) workdir.mkdir(parents=True, exist_ok=True) rows, by_bucket = [], {} for row in answers: task = tasks.get(row["task_id"]) if task is None: continue answer_files = row.get("files") answer = row.get("answer") module = task["module"] target = (f"{task.get('target_loader')}-{task.get('target_version')}" if task.get("target_loader") else "neoforge-1.21.1") rec = {"task_id": task["task_id"], "module": module, "target": target} if module == "debug": try: obj = json.loads(answer or "") ok = all(k in obj for k in ("root_cause", "fix_explanation", "code_patch")) rec.update(static_json_ok=ok, **scores.get(task["task_id"], {})) except json.JSONDecodeError: rec.update(static_json_ok=False, verdict="fail") else: ast = run_ast(task, answer_files, answer, workdir) rec["ast_passed"] = ast.get("passed") rec["ast_score"] = ast.get("score") if task["eval_criteria"]["must_compile"] and not args.skip_compile and not args.dry_run: sb = run_sandbox(task, answer_files, answer, workdir, dry=False) rec["compile_pass@1"] = sb.get("passed") rec["sandbox_target"] = sb.get("target") elif args.dry_run: sb = run_sandbox(task, answer_files, answer, workdir, dry=True) rec["compile_pass@1"] = None rec["sandbox_dry_run"] = True final = scores.get(task["task_id"], {}).get("verdict") rec["verdict"] = final or ("pass" if rec.get("compile_pass@1") is not False and rec.get("ast_passed") else "fail") rows.append(rec) by_bucket.setdefault((module, target), []).append(rec) summary = {} for (module, target), recs in sorted(by_bucket.items()): n = len(recs) summary[f"{module}@{target}"] = { "n": n, "pass@1": round(sum(1 for r in recs if r.get("compile_pass@1") is True) / n, 3) if any("compile_pass@1" in r for r in recs) else None, "ast_pass_rate": round(sum(1 for r in recs if r.get("ast_passed")) / n, 3), "judge_pass_rate": round(sum(1 for r in recs if r.get("verdict") == "pass") / n, 3), } report = {"summary": summary, "rows": rows} payload = json.dumps(report, ensure_ascii=False, indent=2) if args.out: Path(args.out).write_text(payload, encoding="utf-8") print(payload) return 0 if __name__ == "__main__": sys.exit(main())