File size: 5,019 Bytes
cafb492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Independent audit of the Stage B/C datasets (review point 7).

Deliberately separate from the generator code: this script knows nothing
about problem families or their planted bugs. It samples 50 examples,
re-executes each one's tests against the shipped answer/reference
(must PASS) and against a generically hand-broken version
(must FAIL — otherwise the tests are not discriminating).

Usage: python audit.py [pilot|full]
"""
import json
import os
import random
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from framework import run_tests, MASTER_SEED

WORK = os.path.dirname(os.path.abspath(__file__))


def hand_break(code):
    """Audit-side generic breaker — independent of family bug machinery."""
    candidates = []
    for a, b in [(" == ", " != "), (" < ", " > "), (" > ", " < "),
                 (" <= ", " >= "), (" >= ", " <= "), (" + ", " - "),
                 (" - ", " + "), (" * ", " // "), (" % ", " * ")]:
        if a in code:
            candidates.append(code.replace(a, b, 1))
    lines = code.splitlines()
    for i, ln in enumerate(lines):
        s = ln.lstrip()
        if s.startswith("return ") and s.strip() not in ("return None", "return"):
            m = lines[:]
            m[i] = ln[:len(ln) - len(s)] + "return None"
            candidates.append("\n".join(m))
            break
    for cand in candidates:
        if cand != code:
            try:
                compile(cand, "<audit>", "exec")
                return cand
            except SyntaxError:
                continue
    return None


def load(path):
    with open(path) as f:
        return [json.loads(ln) for ln in f if ln.strip()]


def main():
    mode = sys.argv[1] if len(sys.argv) > 1 else "full"
    pre = "pilot_" if mode == "pilot" else ""
    rows_b = load(os.path.join(WORK, f"{pre}stage_b.jsonl"))
    rows_c = load(os.path.join(WORK, f"{pre}stage_c.jsonl"))
    verify = {r["id"]: r for r in load(os.path.join(WORK, f"{pre}stage_c_verify.jsonl"))}

    rng = random.Random(MASTER_SEED)
    sample_b = rng.sample(rows_b, min(30, len(rows_b)))
    sample_c = rng.sample(rows_c, min(20, len(rows_c)))

    findings = []
    checked = passed_orig = failed_broken = 0
    for r in sample_b:
        checked += 1
        if run_tests(r["answer"], r["tests"]):
            passed_orig += 1
        else:
            findings.append({"id": r["id"], "set": "stage_b",
                             "issue": "shipped answer FAILS its own tests"})
        brk = hand_break(r["answer"])
        if brk is None:
            findings.append({"id": r["id"], "set": "stage_b",
                             "issue": "audit breaker produced no variant"})
        elif not run_tests(brk, r["tests"]):
            failed_broken += 1
        else:
            findings.append({"id": r["id"], "set": "stage_b",
                             "issue": "hand-broken answer still PASSES tests"})
    for r in sample_c:
        checked += 1
        ref = verify[r["id"]]["reference_solution"]
        if run_tests(ref, r["tests"]):
            passed_orig += 1
        else:
            findings.append({"id": r["id"], "set": "stage_c",
                             "issue": "reference FAILS its own tests"})
        brk = hand_break(ref)
        if brk is None:
            findings.append({"id": r["id"], "set": "stage_c",
                             "issue": "audit breaker produced no variant"})
        elif not run_tests(brk, r["tests"]):
            failed_broken += 1
        else:
            findings.append({"id": r["id"], "set": "stage_c",
                             "issue": "hand-broken reference still PASSES tests"})

    report = {
        "sampled": checked,
        "original_pass": passed_orig,
        "broken_fail": failed_broken,
        "findings": findings,
        "verdict": "PASS" if (passed_orig == checked and failed_broken == checked
                              and not findings) else "FINDINGS",
    }
    out = os.path.join(WORK, f"audit_report_{mode}.json")
    with open(out, "w") as f:
        json.dump(report, f, indent=2)
    print(f"[audit] sampled {checked}: originals pass {passed_orig}/{checked}, "
          f"broken fail {failed_broken}/{checked}, findings {len(findings)}")
    for fd in findings:
        print(f"[audit] FINDING {fd['set']} {fd['id']}: {fd['issue']}")
    print(f"[audit] verdict: {report['verdict']} -> {out}")

    # fold summary into the manifest
    mtag = "pilot" if mode == "pilot" else "v1"
    mp = os.path.join(WORK, f"manifest_{mtag}.json")
    if os.path.exists(mp):
        man = json.load(open(mp))
        man["audit"] = {"sampled": checked, "original_pass": passed_orig,
                        "broken_fail": failed_broken,
                        "findings": len(findings), "verdict": report["verdict"],
                        "report_file": os.path.basename(out)}
        json.dump(man, open(mp, "w"), indent=2)
        print(f"[audit] manifest updated: {mp}")


if __name__ == "__main__":
    main()