rootxhacker commited on
Commit
fcacca9
·
verified ·
1 Parent(s): 720ed65

verify.py: per-row verification + context expansion harness (v0)

Browse files
Files changed (1) hide show
  1. scripts/verify.py +297 -0
scripts/verify.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PatchBench row verification + context expansion harness (v0).
2
+
3
+ For each candidate row:
4
+ 1. clone the repo at base_commit
5
+ 2. apply test_patch -> run rebuild_cmds -> run test_cmds (twice) -> parse per-test results
6
+ verify: every FAIL_TO_PASS test FAILS in both pre-fix runs
7
+ 3. apply gold_patch -> rebuild -> run test_cmds (twice) -> parse
8
+ verify: every FAIL_TO_PASS PASSES and every PASS_TO_PASS still PASSES in both runs
9
+ 4. slice a 500-1500 line context window around the buggy files
10
+ 5. write a result record; verified rows additionally carry the full patchbench schema
11
+
12
+ Usage (inside a job with the right language toolchain image):
13
+ python verify.py --lang go --file pilot/candidates/go.jsonl --limit 8
14
+ """
15
+ import argparse, json, os, subprocess, sys, time, traceback
16
+
17
+ REPO_ID = "rootxhacker/patchbench"
18
+ CACHE = "/tmp/cache/repos"
19
+ WORK = "/tmp/work"
20
+ ROW_TIMEOUT_S = 2700 # hard cap per row so one slow repo can't eat the job
21
+ CMD_TIMEOUT_S = 2100
22
+ GIT_TIMEOUT_S = 900
23
+ MAX_CONTEXT_LINES = 1500
24
+
25
+ EXTS = {"go": [".go"], "rust": [".rs"], "java": [".java"],
26
+ "javascript": [".js", ".mjs"], "typescript": [".ts", ".tsx"]}
27
+ SKIP_DIRS = {".git", "node_modules", "vendor", "target", "dist", "build", "__pycache__", ".idea"}
28
+
29
+
30
+ def run(cmd, cwd, timeout):
31
+ """cmd: string -> bash -c. Returns (returncode, combined_output, duration)."""
32
+ t0 = time.time()
33
+ try:
34
+ p = subprocess.run(["bash", "-c", cmd], cwd=cwd, capture_output=True,
35
+ timeout=timeout, text=True, errors="replace")
36
+ return p.returncode, (p.stdout or "") + (p.stderr or ""), time.time() - t0
37
+ except subprocess.TimeoutExpired as e:
38
+ out = (e.stdout or "") + (e.stderr or "")
39
+ return 124, out + f"\n[TIMEOUT after {timeout}s]", time.time() - t0
40
+
41
+
42
+ def sh(cmds, cwd, timeout=CMD_TIMEOUT_S):
43
+ for c in (cmds or []):
44
+ rc, out, _ = run(c, cwd, timeout)
45
+ if rc != 0:
46
+ return False, out[-4000:]
47
+ return True, ""
48
+
49
+
50
+ def apply_patch(text, cwd):
51
+ """Try git apply, then patch -p1. Returns error string or None."""
52
+ pf = os.path.join(cwd, ".pb_patch")
53
+ with open(pf, "w") as f:
54
+ f.write(text)
55
+ rc, out, _ = run(f"git apply --whitespace=nowarn < {pf}", cwd, 120)
56
+ if rc == 0:
57
+ return None
58
+ rc2, out2, _ = run(f"patch -p1 --forward --no-backup-if-mismatch < {pf}", cwd, 120)
59
+ if rc2 == 0:
60
+ return None
61
+ return (out + out2)[-2000:]
62
+
63
+
64
+ def clean_state(repo_dir):
65
+ run("git checkout -f HEAD -- . && git clean -fdxq", repo_dir, 120)
66
+
67
+
68
+ def get_parser(row):
69
+ ns = {}
70
+ src = row.get("log_parser") or ""
71
+ assert "def parser" in src, f"no log_parser for {row['id']}"
72
+ exec(src, ns)
73
+ return ns["parser"]
74
+
75
+
76
+ def run_tests(row, repo_dir):
77
+ """Run test_cmds then print_cmds, parse with the row's parser. Returns (tests_dict, raw_tail, err)."""
78
+ parser = get_parser(row)
79
+ ok, err = sh(row.get("test_cmds"), repo_dir)
80
+ if not ok:
81
+ pass # test cmd exit code is not authoritative; the parse decides
82
+ log = ""
83
+ if row.get("print_cmds"):
84
+ for c in row["print_cmds"]:
85
+ _, out, _ = run(c, repo_dir, 120)
86
+ log += out + "\n"
87
+ else:
88
+ _, log, _ = run(" && ".join(row.get("test_cmds") or ["true"]), repo_dir, 120)
89
+ tests = parser(log)
90
+ if not tests:
91
+ # last resort: parse the test_cmds output itself
92
+ allout = ""
93
+ for c in row.get("test_cmds") or []:
94
+ _, o, _ = run(c, repo_dir, 120)
95
+ allout += o + "\n"
96
+ tests = parser(allout) or {}
97
+ return tests, log[-3000:], err
98
+
99
+
100
+ def grade(tests, want, expect):
101
+ """Return (ok, details). want: list of test ids, expect: 'pass'|'fail'."""
102
+ missing, wrong = [], []
103
+ for t in want:
104
+ s = tests.get(t)
105
+ if s is None:
106
+ missing.append(t)
107
+ elif s != expect:
108
+ wrong.append((t, s))
109
+ return (not missing and not wrong), {"missing": len(missing), "wrong": wrong[:10], "missing_ids": missing[:10]}
110
+
111
+
112
+ def touched_paths(patch):
113
+ paths = set()
114
+ for line in patch.splitlines():
115
+ if line.startswith("+++ b/"):
116
+ paths.add(line[6:].split("\t")[0])
117
+ elif line.startswith("--- a/"):
118
+ paths.add(line[6:].split("\t")[0])
119
+ return {p for p in paths if p != "/dev/null"}
120
+
121
+
122
+ def collect_context(repo_dir, buggy_paths, test_paths, lang, cap=MAX_CONTEXT_LINES):
123
+ exts = tuple(EXTS[lang])
124
+ prio = {"buggy": [], "same_dir": [], "tests": [], "other": []}
125
+ buggy_dirs = {os.path.dirname(p) for p in buggy_paths}
126
+ for root, dirs, files in os.walk(repo_dir):
127
+ dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
128
+ for fn in files:
129
+ if not fn.endswith(exts):
130
+ continue
131
+ p = os.path.relpath(os.path.join(root, fn), repo_dir)
132
+ try:
133
+ n = sum(1 for _ in open(os.path.join(repo_dir, p), errors="replace"))
134
+ except OSError:
135
+ continue
136
+ if n > 600: # skip giant files entirely; they blow the window
137
+ continue
138
+ if p in buggy_paths:
139
+ prio["buggy"].append(p)
140
+ elif p in test_paths:
141
+ prio["tests"].append(p)
142
+ elif os.path.dirname(p) in buggy_dirs:
143
+ prio["same_dir"].append(p)
144
+ else:
145
+ prio["other"].append(p)
146
+ chosen, total = [], 0
147
+ for group in ["buggy", "same_dir", "tests", "other"]:
148
+ for p in sorted(prio[group]):
149
+ with open(os.path.join(repo_dir, p), errors="replace") as f:
150
+ content = f.read()
151
+ n = content.count("\n") + 1
152
+ if total + n > cap:
153
+ continue
154
+ chosen.append({"path": p, "content": content})
155
+ total += n
156
+ if total > cap * 0.9:
157
+ break
158
+ return chosen, total
159
+
160
+
161
+ def verify_row(row, lang):
162
+ t0 = time.time()
163
+ rec = {"id": row["id"], "repo": row["repo"], "base_commit": row["base_commit"],
164
+ "status": "env_failed", "verify_status": None, "error": None, "timing": {}}
165
+ repo_dir = os.path.join(CACHE, row["repo"].replace("/", "__"))
166
+ sha = row["base_commit"]
167
+ if not os.path.isdir(repo_dir):
168
+ os.makedirs(CACHE, exist_ok=True)
169
+ rc, out, _ = run(f"git clone --filter=blob:none https://github.com/{row['repo']}.git {repo_dir}", CACHE, GIT_TIMEOUT_S)
170
+ if rc != 0:
171
+ rec["error"] = f"clone failed: {out[-500:]}"
172
+ return rec
173
+ for cmd in [f"git fetch origin {sha} --quiet", f"git checkout -f {sha} --quiet"]:
174
+ rc, out, _ = run(cmd, repo_dir, GIT_TIMEOUT_S)
175
+ if rc != 0:
176
+ rec["error"] = f"checkout failed: {out[-500:]}"
177
+ return rec
178
+ rec["timing"]["setup"] = round(time.time() - t0, 1)
179
+
180
+ # ---- PRE-FIX (twice) ----
181
+ clean_state(repo_dir)
182
+ err = apply_patch(row["test_patch"], repo_dir)
183
+ if err:
184
+ rec["error"] = f"test_patch failed to apply: {err}"
185
+ return rec
186
+ pre_runs = []
187
+ for i in range(2):
188
+ s = time.time()
189
+ tests, tail, _ = run_tests(row, repo_dir)
190
+ pre_runs.append((tests, tail))
191
+ rec["timing"][f"pre_test_{i}"] = round(time.time() - s, 1)
192
+ f2p_ok_pre = all(grade(t, row["fail_to_pass"], "fail")[0] for t, _ in pre_runs)
193
+ rec["f2p_pre_ok"] = f2p_ok_pre
194
+ rec["pre_missing"] = pre_runs[0][0].get and None # placeholder, details below
195
+ pre_detail = grade(pre_runs[0][0], row["fail_to_pass"], "fail")[1]
196
+
197
+ # ---- POST-FIX (twice) ----
198
+ clean_state(repo_dir)
199
+ err = apply_patch(row["test_patch"], repo_dir)
200
+ if err:
201
+ rec["error"] = f"test_patch re-apply failed: {err}"
202
+ return rec
203
+ err = apply_patch(row["gold_patch"], repo_dir)
204
+ if err:
205
+ rec["error"] = f"gold_patch failed to apply: {err}"
206
+ return rec
207
+ post_runs = []
208
+ for i in range(2):
209
+ s = time.time()
210
+ tests, tail, _ = run_tests(row, repo_dir)
211
+ post_runs.append((tests, tail))
212
+ rec["timing"][f"post_test_{i}"] = round(time.time() - s, 1)
213
+ f2p_ok_post = all(grade(t, row["fail_to_pass"], "pass")[0] for t, _ in post_runs)
214
+ p2p_ok_post = all(grade(t, row["pass_to_pass"], "pass")[0] for t, _ in post_runs)
215
+ rec["f2p_post_ok"], rec["p2p_post_ok"] = f2p_ok_post, p2p_ok_post
216
+ rec["post_detail"] = grade(post_runs[0][0], row["fail_to_pass"], "pass")[1]
217
+
218
+ rec["timing"]["total"] = round(time.time() - t0, 1)
219
+ rec["raw_tail"] = pre_runs[0][1][-1500:]
220
+
221
+ if not f2p_ok_pre:
222
+ rec["status"] = "f2p_not_failing_prefix"
223
+ elif not f2p_ok_post:
224
+ rec["status"] = "f2p_not_passing_postfix"
225
+ elif not p2p_ok_post:
226
+ rec["status"] = "p2p_regression"
227
+ else:
228
+ rec["status"] = "verified"
229
+
230
+ # context expansion only for rows worth publishing
231
+ if rec["status"] == "verified":
232
+ buggy = touched_paths(row["gold_patch"])
233
+ tfiles = touched_paths(row["test_patch"])
234
+ ctx, nlines = collect_context(repo_dir, buggy, tfiles, lang)
235
+ rec["verify_status"] = "verified"
236
+ rec["context_files"] = ctx
237
+ rec["context_lines"] = nlines
238
+ rec["buggy_files"] = sorted(buggy - tfiles)
239
+ rec["test_files"] = [{"path": p, "content": open(os.path.join(repo_dir, p), errors="replace").read()}
240
+ for p in sorted(tfiles)]
241
+ rec["eval"] = {"test_cmds": row["test_cmds"], "print_cmds": row.get("print_cmds"),
242
+ "log_parser": row["log_parser"], "rebuild_cmds": row.get("rebuild_cmds")}
243
+ return rec
244
+
245
+
246
+ def main():
247
+ ap = argparse.ArgumentParser()
248
+ ap.add_argument("--lang", required=True)
249
+ ap.add_argument("--file", required=True)
250
+ ap.add_argument("--limit", type=int, default=8)
251
+ ap.add_argument("--out", default=None)
252
+ args = ap.parse_args()
253
+
254
+ from huggingface_hub import hf_hub_download, HfApi
255
+ token = os.environ.get("HF_TOKEN")
256
+ cand_path = hf_hub_download(REPO_ID, args.file, repo_type="dataset", token=token)
257
+ rows = [json.loads(l) for l in open(cand_path)]
258
+ api = HfApi(token=token)
259
+ out_path = args.out or f"/tmp/results_{args.lang}.jsonl"
260
+ verified_path = f"/tmp/verified_{args.lang}.jsonl"
261
+
262
+ done = 0
263
+ with open(out_path, "w") as fo, open(verified_path, "w") as fv:
264
+ for row in rows[:args.limit]:
265
+ if row["language"] != {"go": "go", "rust": "rust", "java": "java",
266
+ "js": "javascript", "ts": "typescript"}.get(args.lang):
267
+ continue
268
+ try:
269
+ rec = verify_row(row, row["language"])
270
+ except Exception as e:
271
+ rec = {"id": row["id"], "status": "harness_crash", "error": repr(e)[:500],
272
+ "tb": traceback.format_exc()[-1500:]}
273
+ fo.write(json.dumps(rec) + "\n")
274
+ fo.flush()
275
+ if rec.get("verify_status") == "verified":
276
+ fv.write(json.dumps({**row, "result": {k: rec[k] for k in
277
+ ["timing", "context_lines", "buggy_files"]}}) + "\n")
278
+ fv.flush()
279
+ print(f"[{row['id']}] {rec['status']} "
280
+ f"pre_ok={rec.get('f2p_pre_ok')} post_ok={rec.get('f2p_post_ok')} "
281
+ f"p2p_ok={rec.get('p2p_post_ok')} err={(rec.get('error') or '')[:200]}",
282
+ flush=True)
283
+ done += 1
284
+
285
+ for path, dest in [(out_path, f"pilot/results/{args.lang}.jsonl"),
286
+ (verified_path, f"pilot/verified/{args.lang}.jsonl")]:
287
+ if os.path.getsize(path) > 0:
288
+ api.upload_file(path_or_fileobj=path, path_in_repo=dest, repo_id=REPO_ID,
289
+ repo_type="dataset", commit_message=f"pilot {args.lang}: {dest.split('/')[-2]}")
290
+ counts = {}
291
+ for l in open(out_path):
292
+ counts[json.loads(l)["status"]] = counts.get(json.loads(l)["status"], 0) + 1
293
+ print(f"VERIFY_DONE lang={args.lang} rows={done} statuses={json.dumps(counts)}", flush=True)
294
+
295
+
296
+ if __name__ == "__main__":
297
+ main()