File size: 23,040 Bytes
7876731
fcacca9
 
 
 
a227681
 
fcacca9
 
 
 
 
3c1d02c
 
 
 
 
40fbcd7
 
 
1141942
 
 
647916c
 
83d78dc
 
6df6a13
6d546c8
 
83d78dc
1141942
 
 
85a18f7
6d546c8
bcd65fb
 
f1a1121
 
 
 
 
7876731
 
 
 
 
fcacca9
6df6a13
fcacca9
1141942
fcacca9
 
 
 
 
 
1141942
 
 
85a18f7
83d78dc
bcd65fb
fcacca9
6df6a13
 
 
 
 
 
 
fcacca9
 
 
 
6df6a13
 
fcacca9
 
 
 
 
 
 
 
6d546c8
 
 
 
 
 
fcacca9
 
 
 
 
 
 
 
 
 
1141942
 
 
 
85a18f7
 
 
 
 
 
83d78dc
 
 
1141942
 
 
 
83d78dc
 
 
 
 
 
 
 
1141942
 
 
 
 
 
83d78dc
1141942
 
 
83d78dc
 
 
fcacca9
 
 
 
 
 
 
 
 
 
 
 
 
647916c
fcacca9
647916c
 
83d78dc
fcacca9
 
 
 
 
 
 
 
 
 
647916c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1141942
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcd65fb
1141942
bcd65fb
1141942
 
85a18f7
1141942
 
85a18f7
1141942
 
 
 
 
 
 
83d78dc
1141942
 
 
7876731
 
 
 
 
 
 
 
83d78dc
fcacca9
647916c
1141942
 
 
6df6a13
ca6e6d9
647916c
 
ca6e6d9
1141942
ca6e6d9
 
 
 
1141942
 
83d78dc
ca6e6d9
fcacca9
 
a227681
 
 
fcacca9
 
 
 
a227681
 
fcacca9
 
ca6e6d9
 
fcacca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6df6a13
fcacca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83d78dc
6df6a13
83d78dc
 
bcd65fb
 
 
 
 
 
6df6a13
 
 
 
 
a227681
fcacca9
 
 
647916c
fcacca9
 
 
 
 
 
 
83d78dc
fcacca9
 
a227681
 
ca6e6d9
fcacca9
3c1d02c
 
 
647916c
3c1d02c
fcacca9
647916c
fcacca9
 
 
 
 
 
 
 
 
 
 
83d78dc
fcacca9
 
 
3c1d02c
fcacca9
 
 
 
 
 
ca6e6d9
 
 
fcacca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1a1121
 
 
 
 
 
fcacca9
 
 
 
 
 
 
 
 
6df6a13
fcacca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca6e6d9
 
1141942
 
fcacca9
85a18f7
 
 
 
 
 
 
 
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
"""PatchBench row verification + context expansion harness (v1.3).

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 collects the report files the frameworks wrote
    (surefire/gradle XML, gradle HTML, reports/* go-json dumps) and feeds them to
    the parser alongside console output; 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.
v0.9: java report files (surefire/gradle XML + gradle HTML) are collected and fed
to the parser; disk guard is du-based (container quota) and rust builds run under
a du watchdog so a runaway build kills the row, not the pod.
v1.0: used_bytes() timed out on 40G+ du scans (empty output parsed as 0 => guard blind); limit lowered to 32GiB, watchdog polls 20s and reclaims on kill; results pushed to the Hub incrementally after each row so evictions lose at most one row.

v1.1: one dev-profile cargo build grew the shared target dir 6.7G->43G and evicted the pod before the watchdog's du scan could catch it. Fixed both causes: cargo now strips debuginfo and disables incremental compilation in dev/test profiles (no effect on test outcomes, cuts target-dir size several-fold); the in-run watchdog monitors only /tmp/pb-cargo-target (fast du scans even under pressure) at a 20GiB limit instead of scanning all of /tmp at 32GiB.

v1.2: some rows' test_cmds use a nested repo/ layout (cd repo, --manifest-path
repo/Cargo.toml) from the upstream /testbed/repo convention -- a self-symlink now
makes both layouts resolve. Context expansion skips test files referenced by the
test_patch that don't exist on disk instead of crashing the row (eza 0070).

v1.3: the v1.2 repo-layout symlink was created in verify_row BEFORE clean_state, and
clean_state runs git clean -fdxq which deleted it -- noir rows ran with no repo/
self-link and parsed 0 tests. The symlink is now created inside run_tests, after
every clean_state, so both layouts resolve in every phase.

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, shlex, subprocess, sys, time, traceback

REPO_ID = "rootxhacker/patchbench"
CACHE = "/tmp/cache/repos"
CMD_TIMEOUT_S = 2100
GIT_TIMEOUT_S = 900
MAX_CONTEXT_LINES = 1500
# The 50G limit is a per-container ephemeral-storage quota. df/statvfs report the
# host filesystem and never see it, so disk accounting must be du-based.
CONTAINER_QUOTA_BYTES = 50 * 1024**3
DU_LIMIT_BYTES = 32 * 1024**3
RUST_SHARED_TARGET = "/tmp/pb-cargo-target"
RUST_WATCHDOG_LIMIT_BYTES = 20 * 1024**3  # watchdog limit on the target dir alone

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 used_bytes():
    """Bytes used in the du-monitored dirs. df/statvfs see the host fs, not the
    per-container ephemeral-storage quota, so du is the only honest measure."""
    _, out, _ = run("du -sb /tmp /usr/local/cargo /root/.cache /var/tmp 2>/dev/null "
                    "| awk '{s+=$1} END {print s+0}'", "/tmp", 900)
    for line in reversed(out.splitlines()):
        s = line.strip()
        if s.isdigit():
            return int(s)
    return 0


def log_disk(tag):
    _, out, _ = run("du -sb /tmp/pb-cargo-target /tmp/cache /usr/local/cargo/registry "
                    "2>/dev/null", "/tmp", 120)
    print(f"[disk:{tag}] container_used={used_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 blowing the container's ephemeral-storage quota -- an
    eviction loses all remaining rows."""
    u = used_bytes()
    if u > DU_LIMIT_BYTES:
        print(f"[disk:{tag}] used={u >> 30}G > limit={DU_LIMIT_BYTES >> 30}G, "
              "reclaiming shared target dir", flush=True)
        reclaim_disk()
        u = used_bytes()
    if u > CONTAINER_QUOTA_BYTES - 2 * 1024**3:
        raise RuntimeError(f"disk_pressure: used={u >> 30}G 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}"


DEFAULT_REPORT_FINDS = [r'for f in reports/*; do [ -f "$f" ] && cat "$f"; done']
REPORT_FINDS = {
    "java": DEFAULT_REPORT_FINDS + [
        r'find . \( -path "*surefire-reports*" -o -path "*failsafe-reports*" '
        r'-o -path "*build/test-results*" \) -name "*.xml" -type f '
        r'| sort | head -400 | while read -r f; do cat "$f"; done',
        r'find . -path "*reports/tests*" -name "*.html" -type f '
        r'| sort | head -200 | while read -r f; do cat "$f"; done',
    ],
}


def collect_reports(repo_dir, lang):
    """Cat the report files the test frameworks wrote (per-language find commands)
    into the output stream the log parser sees. Each output capped at 8M chars."""
    outs = []
    for cmd in REPORT_FINDS.get(lang, DEFAULT_REPORT_FINDS):
        _, o, _ = run(cmd, repo_dir, 300)
        if o.strip():
            outs.append(o[:8_000_000])
    return "\n".join(outs)


WATCHDOG_LANGS = {"rust"}


def watchdog_wrap(cmd):
    """Run cmd in its own process group under a du watchdog. setsid is critical:
    without it cargo survives `kill -9 -- -$pid` and keeps writing to the quota.
    Build runs in FOREGROUND; the du monitor polls in BACKGROUND; `wait $pid`
    decides the exit code (avoids the kill -0 zombie-hang on fast commands)."""
    limit = DU_LIMIT_BYTES
    q = shlex.quote(cmd)
    return (
        f"printf %s {q} > /tmp/pb_cmd.sh\n"
        "setsid bash /tmp/pb_cmd.sh & pid=$!\n"
        "( while kill -0 $pid 2>/dev/null; do\n"
        "    used=$(du -sb /tmp/pb-cargo-target 2>/dev/null "
        "| awk '{s+=$1} END {print s+0}')\n"
        f"    if [ \"$used\" -gt {RUST_WATCHDOG_LIMIT_BYTES} ]; then\n"
        "      kill -9 -- -$pid 2>/dev/null\n"
        "      echo \"[DISK_WATCHDOG] killed build: container=${used}B\"\n"
        "      rm -rf /tmp/pb-cargo-target 2>/dev/null\n"
        "      exit 0\n"
        "    fi\n"
        "    sleep 20 >/dev/null 2>&1\n"
        "  done ) & mon=$!\n"
        "wait $pid; rc=$?\n"
        "kill $mon 2>/dev/null\n"
        "exit $rc\n"
    )


def run_tests(row, repo_dir, lang, phase_tag=""):
    """Run rebuild_cmds, test_cmds, print_cmds, then collect the report files the
    test frameworks wrote (surefire/gradle XML, gradle HTML, reports/*) and feed
    them to the log parser. Returns (tests_dict, combined_output_tail)."""
    # v1.3: rows whose cmds reference a nested repo/ layout need a self-symlink,
    # and it must exist AFTER every clean_state (which git-cleans it away).
    _cmds = (row.get("test_cmds") or []) + (row.get("rebuild_cmds") or []) + (row.get("print_cmds") or [])
    if any(("repo/" in c) or c.rstrip().endswith("/repo") for c in _cmds):
        _sl = os.path.join(repo_dir, "repo")
        if not (os.path.islink(_sl) or os.path.exists(_sl)):
            os.symlink(repo_dir, _sl)
            print("repo-layout symlink created", flush=True)
    disk_guard(f"{phase_tag}-pre")
    parser = get_parser(row)
    dep_err = ensure_js_deps(repo_dir)
    wrap = watchdog_wrap if lang in WATCHDOG_LANGS else (lambda c: c)
    for c in (row.get("rebuild_cmds") or []):
        run(wrap(c), repo_dir, CMD_TIMEOUT_S)
    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(wrap(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"
    out += collect_reports(repo_dir, lang) + "\n"
    disk_guard(f"{phase_tag}-post")
    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
        # v1.1: a dev-profile build with debuginfo hit 43G on the 50G container
        # quota. Stripping debuginfo and disabling incremental compilation has
        # no effect on test outcomes, only on build artifacts.
        os.environ["CARGO_PROFILE_DEV_DEBUG"] = "0"
        os.environ["CARGO_PROFILE_TEST_DEBUG"] = "0"
        os.environ["CARGO_INCREMENTAL"] = "0"
    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"] = []
        for _p in sorted(tfiles):
            try:
                rec["test_files"].append({"path": _p, "content": open(os.path.join(repo_dir, _p), errors="replace").read()})
            except OSError:
                pass  # v1.2: missing files are silently skipped
        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)
            if row["language"] == "rust":
                run(f"rm -rf {RUST_SHARED_TARGET}", "/tmp", 600)
            done += 1
            try:
                api.upload_file(path_or_fileobj=out_path, path_in_repo=f"pilot/results/{args.lang}.jsonl",
                                repo_id=REPO_ID, repo_type="dataset", commit_message=f"pilot {args.lang}: incremental {done} rows")
                if os.path.getsize(verified_path) > 0:
                    api.upload_file(path_or_fileobj=verified_path, path_in_repo=f"pilot/verified/{args.lang}.jsonl",
                                    repo_id=REPO_ID, repo_type="dataset", commit_message=f"pilot {args.lang}: verified {done}")
            except Exception as pe:
                print(f"[push] incremental push failed: {pe}", flush=True)

    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()