patchbench / scripts /verify.py
rootxhacker's picture
verify.py v0.4: cat reports/*.json after test_cmds (upstream harness reads the report dir itself; print_cmds is often empty)
40fbcd7 verified
Raw History Blame
12.7 kB
"""PatchBench row verification + context expansion harness (v0.4).
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 pre-fix in both runs (a test that does not
exist because its package fails to build counts as failing -- upstream semantics)
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
Native (non-Docker) reproduction of the upstream env:
- toolchain dirs are prepended to PATH per language
- the upstream /testbed convention is rewritten to the local checkout path
- after test_cmds, the harness cats reports/* (rows redirect `go test -json >
reports/<lang>-test-results.json` and upstream's harness reads that report
itself; the row's print_cmds list is often empty)
Usage (inside a job with the right language toolchain image):
python verify.py --lang go --file pilot/candidates/go.jsonl --limit 6
"""
import argparse, json, os, subprocess, sys, time, traceback
REPO_ID = "rootxhacker/patchbench"
CACHE = "/tmp/cache/repos"
CMD_TIMEOUT_S = 2100
GIT_TIMEOUT_S = 900
MAX_CONTEXT_LINES = 1500
LANG_PATH_PREPEND = {
"go": ["/usr/local/go/bin"],
"rust": ["/usr/local/cargo/bin", "/usr/local/rustup/bin"],
"java": [],
"javascript": [],
"typescript": [],
}
EXTS = {"go": [".go"], "rust": [".rs"], "java": [".java"],
"javascript": [".js", ".mjs"], "typescript": [".ts", ".tsx"]}
SKIP_DIRS = {".git", "node_modules", "vendor", "target", "dist", "build", "__pycache__", ".idea"}
TESTBED = "/testbed"
def run(cmd, cwd, timeout):
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):
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 rebuild_cmds, test_cmds, print_cmds, then surface any reports/* the test
commands wrote. Returns (tests_dict, combined_output_tail)."""
parser = get_parser(row)
sh(row.get("rebuild_cmds"), repo_dir)
run("mkdir -p reports", repo_dir, 30)
out = ""
for c in (row.get("test_cmds") or []):
_, o, _ = run(c, repo_dir, CMD_TIMEOUT_S)
out += o + "\n"
for c in (row.get("print_cmds") or []):
_, o, _ = run(c, repo_dir, 120)
out += o + "\n"
_, o, _ = run("for f in reports/*; do [ -f \"$f\" ] && cat \"$f\"; done", repo_dir, 120)
out += o + "\n"
return parser(out), out[-3000:]
def grade(tests, want, expect, allow_missing=False):
"""allow_missing=True for pre-fix 'fail' checks: a test that never ran (build
failure in its package) is not passing, which is what upstream means by fail."""
missing, wrong = [], []
for t in want:
s = tests.get(t)
if s is None:
if not allow_missing:
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[:5], "parsed_count": len(tests)}
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:
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
os.environ["PATH"] = ":".join(LANG_PATH_PREPEND.get(lang, [])) + ":" + os.environ["PATH"]
def tb(cmds):
return [c.replace(TESTBED, repo_dir) for c in (cmds or [])]
row = {**row, "test_cmds": tb(row["test_cmds"]), "rebuild_cmds": tb(row.get("rebuild_cmds")),
"print_cmds": tb(row.get("print_cmds"))}
rec["test_cmds"], rec["rebuild_cmds"], rec["print_cmds"] = row["test_cmds"], row["rebuild_cmds"], row["print_cmds"]
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)
pre_detail = grade(pre_runs[0][0], row["fail_to_pass"], "fail", allow_missing=True)[1]
f2p_ok_pre = all(grade(t, row["fail_to_pass"], "fail", allow_missing=True)[0] for t, _ in pre_runs)
rec["f2p_pre_ok"], rec["pre_detail"] = f2p_ok_pre, pre_detail
# ---- 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 len(pre_runs[0][0]) == 0:
rec["status"] = "no_tests_parsed"
elif 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"
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=6)
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]:
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')} parsed={rec.get('pre_detail', {}).get('parsed_count', '?')} "
f"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()