"""PatchBench row verification + context expansion harness (v0). For each candidate row: 1. clone the repo at base_commit 2. apply test_patch -> run rebuild_cmds -> run test_cmds (twice) -> parse per-test results verify: every FAIL_TO_PASS test FAILS in both pre-fix runs 3. apply gold_patch -> rebuild -> run test_cmds (twice) -> parse verify: every FAIL_TO_PASS PASSES and every PASS_TO_PASS still PASSES in both runs 4. slice a 500-1500 line context window around the buggy files 5. write a result record; verified rows additionally carry the full patchbench schema Usage (inside a job with the right language toolchain image): python verify.py --lang go --file pilot/candidates/go.jsonl --limit 8 """ import argparse, json, os, subprocess, sys, time, traceback REPO_ID = "rootxhacker/patchbench" CACHE = "/tmp/cache/repos" WORK = "/tmp/work" ROW_TIMEOUT_S = 2700 # hard cap per row so one slow repo can't eat the job CMD_TIMEOUT_S = 2100 GIT_TIMEOUT_S = 900 MAX_CONTEXT_LINES = 1500 EXTS = {"go": [".go"], "rust": [".rs"], "java": [".java"], "javascript": [".js", ".mjs"], "typescript": [".ts", ".tsx"]} SKIP_DIRS = {".git", "node_modules", "vendor", "target", "dist", "build", "__pycache__", ".idea"} def run(cmd, cwd, timeout): """cmd: string -> bash -c. Returns (returncode, combined_output, duration).""" t0 = time.time() try: p = subprocess.run(["bash", "-c", cmd], cwd=cwd, capture_output=True, timeout=timeout, text=True, errors="replace") return p.returncode, (p.stdout or "") + (p.stderr or ""), time.time() - t0 except subprocess.TimeoutExpired as e: out = (e.stdout or "") + (e.stderr or "") return 124, out + f"\n[TIMEOUT after {timeout}s]", time.time() - t0 def sh(cmds, cwd, timeout=CMD_TIMEOUT_S): for c in (cmds or []): rc, out, _ = run(c, cwd, timeout) if rc != 0: return False, out[-4000:] return True, "" def apply_patch(text, cwd): """Try git apply, then patch -p1. Returns error string or None.""" pf = os.path.join(cwd, ".pb_patch") with open(pf, "w") as f: f.write(text) rc, out, _ = run(f"git apply --whitespace=nowarn < {pf}", cwd, 120) if rc == 0: return None rc2, out2, _ = run(f"patch -p1 --forward --no-backup-if-mismatch < {pf}", cwd, 120) if rc2 == 0: return None return (out + out2)[-2000:] def clean_state(repo_dir): run("git checkout -f HEAD -- . && git clean -fdxq", repo_dir, 120) def get_parser(row): ns = {} src = row.get("log_parser") or "" assert "def parser" in src, f"no log_parser for {row['id']}" exec(src, ns) return ns["parser"] def run_tests(row, repo_dir): """Run test_cmds then print_cmds, parse with the row's parser. Returns (tests_dict, raw_tail, err).""" parser = get_parser(row) ok, err = sh(row.get("test_cmds"), repo_dir) if not ok: pass # test cmd exit code is not authoritative; the parse decides log = "" if row.get("print_cmds"): for c in row["print_cmds"]: _, out, _ = run(c, repo_dir, 120) log += out + "\n" else: _, log, _ = run(" && ".join(row.get("test_cmds") or ["true"]), repo_dir, 120) tests = parser(log) if not tests: # last resort: parse the test_cmds output itself allout = "" for c in row.get("test_cmds") or []: _, o, _ = run(c, repo_dir, 120) allout += o + "\n" tests = parser(allout) or {} return tests, log[-3000:], err def grade(tests, want, expect): """Return (ok, details). want: list of test ids, expect: 'pass'|'fail'.""" missing, wrong = [], [] for t in want: s = tests.get(t) if s is None: missing.append(t) elif s != expect: wrong.append((t, s)) return (not missing and not wrong), {"missing": len(missing), "wrong": wrong[:10], "missing_ids": missing[:10]} def touched_paths(patch): paths = set() for line in patch.splitlines(): if line.startswith("+++ b/"): paths.add(line[6:].split("\t")[0]) elif line.startswith("--- a/"): paths.add(line[6:].split("\t")[0]) return {p for p in paths if p != "/dev/null"} def collect_context(repo_dir, buggy_paths, test_paths, lang, cap=MAX_CONTEXT_LINES): exts = tuple(EXTS[lang]) prio = {"buggy": [], "same_dir": [], "tests": [], "other": []} buggy_dirs = {os.path.dirname(p) for p in buggy_paths} for root, dirs, files in os.walk(repo_dir): dirs[:] = [d for d in dirs if d not in SKIP_DIRS] for fn in files: if not fn.endswith(exts): continue p = os.path.relpath(os.path.join(root, fn), repo_dir) try: n = sum(1 for _ in open(os.path.join(repo_dir, p), errors="replace")) except OSError: continue if n > 600: # skip giant files entirely; they blow the window continue if p in buggy_paths: prio["buggy"].append(p) elif p in test_paths: prio["tests"].append(p) elif os.path.dirname(p) in buggy_dirs: prio["same_dir"].append(p) else: prio["other"].append(p) chosen, total = [], 0 for group in ["buggy", "same_dir", "tests", "other"]: for p in sorted(prio[group]): with open(os.path.join(repo_dir, p), errors="replace") as f: content = f.read() n = content.count("\n") + 1 if total + n > cap: continue chosen.append({"path": p, "content": content}) total += n if total > cap * 0.9: break return chosen, total def verify_row(row, lang): t0 = time.time() rec = {"id": row["id"], "repo": row["repo"], "base_commit": row["base_commit"], "status": "env_failed", "verify_status": None, "error": None, "timing": {}} repo_dir = os.path.join(CACHE, row["repo"].replace("/", "__")) sha = row["base_commit"] if not os.path.isdir(repo_dir): os.makedirs(CACHE, exist_ok=True) rc, out, _ = run(f"git clone --filter=blob:none https://github.com/{row['repo']}.git {repo_dir}", CACHE, GIT_TIMEOUT_S) if rc != 0: rec["error"] = f"clone failed: {out[-500:]}" return rec for cmd in [f"git fetch origin {sha} --quiet", f"git checkout -f {sha} --quiet"]: rc, out, _ = run(cmd, repo_dir, GIT_TIMEOUT_S) if rc != 0: rec["error"] = f"checkout failed: {out[-500:]}" return rec rec["timing"]["setup"] = round(time.time() - t0, 1) # ---- PRE-FIX (twice) ---- clean_state(repo_dir) err = apply_patch(row["test_patch"], repo_dir) if err: rec["error"] = f"test_patch failed to apply: {err}" return rec pre_runs = [] for i in range(2): s = time.time() tests, tail, _ = run_tests(row, repo_dir) pre_runs.append((tests, tail)) rec["timing"][f"pre_test_{i}"] = round(time.time() - s, 1) f2p_ok_pre = all(grade(t, row["fail_to_pass"], "fail")[0] for t, _ in pre_runs) rec["f2p_pre_ok"] = f2p_ok_pre rec["pre_missing"] = pre_runs[0][0].get and None # placeholder, details below pre_detail = grade(pre_runs[0][0], row["fail_to_pass"], "fail")[1] # ---- POST-FIX (twice) ---- clean_state(repo_dir) err = apply_patch(row["test_patch"], repo_dir) if err: rec["error"] = f"test_patch re-apply failed: {err}" return rec err = apply_patch(row["gold_patch"], repo_dir) if err: rec["error"] = f"gold_patch failed to apply: {err}" return rec post_runs = [] for i in range(2): s = time.time() tests, tail, _ = run_tests(row, repo_dir) post_runs.append((tests, tail)) rec["timing"][f"post_test_{i}"] = round(time.time() - s, 1) f2p_ok_post = all(grade(t, row["fail_to_pass"], "pass")[0] for t, _ in post_runs) p2p_ok_post = all(grade(t, row["pass_to_pass"], "pass")[0] for t, _ in post_runs) rec["f2p_post_ok"], rec["p2p_post_ok"] = f2p_ok_post, p2p_ok_post rec["post_detail"] = grade(post_runs[0][0], row["fail_to_pass"], "pass")[1] rec["timing"]["total"] = round(time.time() - t0, 1) rec["raw_tail"] = pre_runs[0][1][-1500:] if not f2p_ok_pre: rec["status"] = "f2p_not_failing_prefix" elif not f2p_ok_post: rec["status"] = "f2p_not_passing_postfix" elif not p2p_ok_post: rec["status"] = "p2p_regression" else: rec["status"] = "verified" # context expansion only for rows worth publishing if rec["status"] == "verified": buggy = touched_paths(row["gold_patch"]) tfiles = touched_paths(row["test_patch"]) ctx, nlines = collect_context(repo_dir, buggy, tfiles, lang) rec["verify_status"] = "verified" rec["context_files"] = ctx rec["context_lines"] = nlines rec["buggy_files"] = sorted(buggy - tfiles) rec["test_files"] = [{"path": p, "content": open(os.path.join(repo_dir, p), errors="replace").read()} for p in sorted(tfiles)] rec["eval"] = {"test_cmds": row["test_cmds"], "print_cmds": row.get("print_cmds"), "log_parser": row["log_parser"], "rebuild_cmds": row.get("rebuild_cmds")} return rec def main(): ap = argparse.ArgumentParser() ap.add_argument("--lang", required=True) ap.add_argument("--file", required=True) ap.add_argument("--limit", type=int, default=8) ap.add_argument("--out", default=None) args = ap.parse_args() from huggingface_hub import hf_hub_download, HfApi token = os.environ.get("HF_TOKEN") cand_path = hf_hub_download(REPO_ID, args.file, repo_type="dataset", token=token) rows = [json.loads(l) for l in open(cand_path)] api = HfApi(token=token) out_path = args.out or f"/tmp/results_{args.lang}.jsonl" verified_path = f"/tmp/verified_{args.lang}.jsonl" done = 0 with open(out_path, "w") as fo, open(verified_path, "w") as fv: for row in rows[:args.limit]: if row["language"] != {"go": "go", "rust": "rust", "java": "java", "js": "javascript", "ts": "typescript"}.get(args.lang): continue try: rec = verify_row(row, row["language"]) except Exception as e: rec = {"id": row["id"], "status": "harness_crash", "error": repr(e)[:500], "tb": traceback.format_exc()[-1500:]} fo.write(json.dumps(rec) + "\n") fo.flush() if rec.get("verify_status") == "verified": fv.write(json.dumps({**row, "result": {k: rec[k] for k in ["timing", "context_lines", "buggy_files"]}}) + "\n") fv.flush() print(f"[{row['id']}] {rec['status']} " f"pre_ok={rec.get('f2p_pre_ok')} post_ok={rec.get('f2p_post_ok')} " f"p2p_ok={rec.get('p2p_post_ok')} err={(rec.get('error') or '')[:200]}", flush=True) done += 1 for path, dest in [(out_path, f"pilot/results/{args.lang}.jsonl"), (verified_path, f"pilot/verified/{args.lang}.jsonl")]: if os.path.getsize(path) > 0: api.upload_file(path_or_fileobj=path, path_in_repo=dest, repo_id=REPO_ID, repo_type="dataset", commit_message=f"pilot {args.lang}: {dest.split('/')[-2]}") counts = {} for l in open(out_path): counts[json.loads(l)["status"]] = counts.get(json.loads(l)["status"], 0) + 1 print(f"VERIFY_DONE lang={args.lang} rows={done} statuses={json.dumps(counts)}", flush=True) if __name__ == "__main__": main()