File size: 17,059 Bytes
83d78dc
fcacca9
 
 
 
a227681
 
fcacca9
 
 
 
 
3c1d02c
 
 
 
 
40fbcd7
 
 
 
3c1d02c
647916c
 
83d78dc
 
6df6a13
6d546c8
 
83d78dc
 
 
 
 
6d546c8
fcacca9
6df6a13
fcacca9
 
 
 
 
 
 
 
83d78dc
 
 
fcacca9
6df6a13
 
 
 
 
 
 
fcacca9
 
 
 
6df6a13
 
fcacca9
 
 
 
 
 
 
 
6d546c8
 
 
 
 
 
fcacca9
 
 
 
 
 
 
 
 
 
83d78dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcacca9
 
 
 
 
 
 
 
 
 
 
 
 
647916c
fcacca9
647916c
 
83d78dc
fcacca9
 
 
 
 
 
 
 
 
 
647916c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83d78dc
40fbcd7
 
83d78dc
fcacca9
647916c
6df6a13
 
ca6e6d9
647916c
 
ca6e6d9
 
 
 
 
 
40fbcd7
 
83d78dc
ca6e6d9
fcacca9
 
a227681
 
 
fcacca9
 
 
 
a227681
 
fcacca9
 
ca6e6d9
 
fcacca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6df6a13
fcacca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83d78dc
6df6a13
83d78dc
 
6df6a13
 
 
 
 
a227681
fcacca9
 
 
647916c
fcacca9
 
 
 
 
 
 
83d78dc
fcacca9
 
a227681
 
ca6e6d9
fcacca9
3c1d02c
 
 
647916c
3c1d02c
fcacca9
647916c
fcacca9
 
 
 
 
 
 
 
 
 
 
83d78dc
fcacca9
 
 
3c1d02c
fcacca9
 
 
 
 
 
ca6e6d9
 
 
fcacca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6df6a13
fcacca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca6e6d9
 
fcacca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
"""PatchBench row verification + context expansion harness (v0.8).

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

P2P scoping: PASS_TO_PASS is evaluated over tests that PASS in BOTH pre-fix runs in
this environment. Tests upstream lists in P2P that fail pre-fix here (e.g. tests
needing docker/k8s) are recorded in p2p_env_dropped and excluded from grading --
they are not evaluable natively, not regressions.

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`; the row's print_cmds list is often empty)
  - JS/TS: if package.json exists without node_modules, deps are installed with the
    repo's own package manager (detected from lockfile)
  - rust: cargo target dirs are wiped between rows AND all builds go to one shared
    CARGO_TARGET_DIR outside the repo, so disk usage is monitorable and reclaimable

v0.7: TimeoutExpired.stdout/stderr can be bytes (python quirk under capture_output) --
decode before concatenating. This crashed slow maven builds at the 2100s timeout.
v0.8: disk guard. Three rust jobs died on the 50G ephemeral-storage quota mid-row.
Now: shared CARGO_TARGET_DIR, a check before every test phase that wipes build
caches when free space < 6G (raising "disk_pressure" instead of getting the pod
evicted, which loses every remaining row), and df/du logging after each phase so
the next quota failure is diagnosable from the log.

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
DISK_FREE_MIN_BYTES = 6 * 1024**3   # reclaim below this
DISK_ABORT_BYTES = 2 * 1024**3      # abort row below this after reclaim
RUST_SHARED_TARGET = "/tmp/pb-cargo-target"

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:
        so, se = e.stdout or "", e.stderr or ""
        if isinstance(so, bytes):
            so = so.decode("utf-8", "replace")
        if isinstance(se, bytes):
            se = se.decode("utf-8", "replace")
        return 124, so + se + 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 free_bytes(path="/tmp"):
    try:
        st = os.statvfs(path)
        return st.f_bavail * st.f_frsize
    except OSError:
        return 1 << 62


def log_disk(tag):
    _, out, _ = run("df -h /tmp 2>/dev/null | tail -n +2; "
                    "du -sh /tmp/pb-cargo-target /tmp/cache /usr/local/cargo/registry 2>/dev/null",
                    "/tmp", 120)
    print(f"[disk:{tag}] free={free_bytes() >> 30}G | {out.strip()[:400]}", flush=True)


def reclaim_disk():
    """Wipe build artifacts (not .git clones, not the registry) to free space."""
    run("rm -rf /tmp/pb-cargo-target", "/tmp", 600)


def disk_guard(tag):
    """Raise instead of letting the pod get evicted -- an eviction loses all rows."""
    if free_bytes() < DISK_FREE_MIN_BYTES:
        print(f"[disk:{tag}] low, reclaiming shared target dir", flush=True)
        reclaim_disk()
    if free_bytes() < DISK_ABORT_BYTES:
        raise RuntimeError(f"disk_pressure: only {free_bytes() >> 30}G free after reclaim "
                           f"(tag={tag}); aborting row to save the remaining rows")


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, lang=None):
    run("git checkout -f HEAD -- . && git clean -fdxq", repo_dir, 120)
    if lang == "rust":
        run("find . -name target -type d -prune -exec rm -rf {} +", repo_dir, 300)
        run(f"rm -rf {RUST_SHARED_TARGET}", "/tmp", 300)


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 ensure_js_deps(repo_dir):
    """Upstream JS/TS images ship node_modules; natively we must install them.
    Detect the package manager from the lockfile. Returns error string or None."""
    if not os.path.exists(os.path.join(repo_dir, "package.json")):
        return None
    if os.path.exists(os.path.join(repo_dir, "node_modules")):
        return None
    if os.path.exists(os.path.join(repo_dir, "pnpm-lock.yaml")):
        cmds = ["corepack enable 2>/dev/null; corepack prepare pnpm@latest --activate 2>/dev/null || npm install -g pnpm",
                "pnpm install --frozen-lockfile || pnpm install"]
    elif os.path.exists(os.path.join(repo_dir, "yarn.lock")):
        cmds = ["yarn install --frozen-lockfile || yarn install"]
    elif os.path.exists(os.path.join(repo_dir, "package-lock.json")):
        cmds = ["npm ci || npm install"]
    else:
        cmds = ["npm install"]
    ok, err = sh(cmds, repo_dir, 1800)
    return None if ok else f"js deps install failed: {err}"


def run_tests(row, repo_dir, lang, phase_tag=""):
    """Run rebuild_cmds, test_cmds, print_cmds, then surface any reports/* the test
    commands wrote. Returns (tests_dict, combined_output_tail)."""
    disk_guard(f"{phase_tag}-pre")
    parser = get_parser(row)
    dep_err = ensure_js_deps(repo_dir)
    sh(row.get("rebuild_cmds"), repo_dir)
    run("mkdir -p reports", repo_dir, 30)
    out = ""
    if dep_err:
        out += dep_err + "\n"
    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"
    log_disk(f"{phase_tag}-post")
    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
    log_disk(f"cloned:{row['id']}")

    if lang == "rust":
        os.environ["CARGO_TARGET_DIR"] = RUST_SHARED_TARGET
    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, lang)
    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, lang, f"pre{i}:{row['id']}")
        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

    # P2P scoped to this environment: keep only tests that pass in BOTH pre-fix runs
    p2p_scoped = [t for t in row["pass_to_pass"]
                  if pre_runs[0][0].get(t) == "pass" and pre_runs[1][0].get(t) == "pass"]
    rec["p2p_env_dropped_count"] = len(row["pass_to_pass"]) - len(p2p_scoped)

    # ---- POST-FIX (twice) ----
    clean_state(repo_dir, lang)
    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, lang, f"post{i}:{row['id']}")
        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, p2p_scoped, "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()