File size: 3,985 Bytes
4882451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Grader tamper check: gold replies must fail when the answer key is deliberately mutated."""
import copy
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "environment" / "src"))
from binary_reasoning_v1.grading import _answer_symbol, grade_item, needs_judge, norm_symbol  # noqa: E402


def resolve_path():
    if len(sys.argv) > 1:
        return Path(sys.argv[1])
    for p in (ROOT / "sample_free.jsonl", ROOT / "environment/src/binary_reasoning_v1/items.jsonl"):
        if p.exists():
            return p
    raise SystemExit("no sample JSONL found; pass one as argv[1]")


def load_rows(path):
    rows = []
    for line in path.read_text(encoding="utf-8").splitlines():
        if line.strip():
            rows.append(json.loads(line))
    return rows


def parse_json_answer(ans):
    if isinstance(ans, dict):
        return ans
    if isinstance(ans, str):
        try:
            obj = json.loads(ans)
            if isinstance(obj, dict):
                return obj
        except Exception:
            pass
    return {}


def mutate_token(s):
    s = str(s)
    if not s:
        return "RELAB_TAMPER"
    mid = len(s) // 2
    return f"{s[:mid]}_RELAB_TAMPER_{s[mid:]}"


def gold_reply(row):
    fam = row.get("family", "")
    ans = row.get("answer")
    if fam == "func_id_mc" and isinstance(ans, dict):
        opts = ans.get("options", [])
        correct = norm_symbol(ans.get("correct", ""))
        for i, opt in enumerate(opts[:4]):
            if norm_symbol(opt) == correct:
                return "ABCD"[i]
        return str(ans.get("correct", ""))
    if fam == "toolchain_fp" and isinstance(ans, dict):
        return "\n".join(str(s) for s in ans.get("toolchain_strings", []))
    if fam == "crossarch_equivalence":
        obj = parse_json_answer(ans)
        if bool(obj.get("same")):
            return f"Same function: {obj.get('symbol', '')}"
        return "Not the same."
    sym = _answer_symbol(ans)
    return str(sym or ans or "")


def tamper_answer(row):
    fam = row.get("family", "")
    ans = copy.deepcopy(row.get("answer"))
    if fam == "func_id_mc" and isinstance(ans, dict):
        opts = ans.get("options", [])
        correct = norm_symbol(ans.get("correct", ""))
        for opt in opts:
            if norm_symbol(opt) != correct:
                ans["correct"] = opt
                return ans
        ans["correct"] = f"{ans.get('correct', '')}_RELAB_TAMPER"
        return ans
    if fam == "toolchain_fp" and isinstance(ans, dict):
        ans["toolchain_strings"] = [mutate_token(s) for s in ans.get("toolchain_strings", [])]
        return ans
    if fam == "library_ident":
        return f"{ans}_RELAB_TAMPER"
    if fam == "crossarch_equivalence":
        obj = parse_json_answer(ans)
        obj["same"] = not bool(obj.get("same"))
        if isinstance(ans, str):
            return json.dumps(obj)
        return obj
    if isinstance(ans, dict):
        ans["symbol"] = f"{ans.get('symbol', '')}_RELAB_TAMPER"
        ans["aliases"] = [f"{a}_RELAB_TAMPER" for a in ans.get("aliases", [])]
        return ans
    return f"{ans}_RELAB_TAMPER"


def main():
    path = resolve_path()
    rows = load_rows(path)
    passed = failed = skipped = 0
    fails = []
    for row in rows:
        fam = row.get("family", "")
        ans = row.get("answer")
        if needs_judge(fam, ans):
            skipped += 1
            continue
        score = grade_item(fam, gold_reply(row), tamper_answer(row))
        if score < 1.0:
            passed += 1
        else:
            failed += 1
            fails.append((row.get("id"), fam, score))
    print(f"file={path}")
    print(f"summary: grader_tamper pass={passed}/{passed + failed} fail={failed} skipped_judge={skipped}")
    for f in fails[:10]:
        print("FAIL", *f)
    return 0 if failed == 0 else 1


if __name__ == "__main__":
    raise SystemExit(main())