File size: 8,573 Bytes
39d54f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate the round-5 feedback-case-selection (diversity) mechanism.

Covers the two layers:
  1. Probe harness (plain + SPJ): LCB_PROBE_ORDER unset/'canonical' emits output with NO new
     keys and identical semantics; 'shuffle'/'rotate' are deterministic per seed, keep the
     ORIGINAL suite idx on failing cases, respect LCB_PROBE_MAX_FAILS, and different seeds
     reach different failing cases (the staleness fix).
  2. Feedback operator (se_patches/benchmarks/livecodebench/_feedback_aggregate.py):
     LCB_FB_CASE_SELECT unset -> prompts unchanged; 'shuffle' -> a STUCK (byte-identical)
     candidate is shown DIFFERENT failing cases on consecutive recombination calls (the
     per-epoch seed also keys the exec cache); fb_audit gains probe_epoch / shown_cases
     (+ case_select / case_seeds in diversity mode); leaving diversity mode reproduces the
     legacy prompt exactly (cache not poisoned).

Optionally, set R4_SPJ_REF (path to the round-4 shipped lcb_public_probe_harness_spj.py) to
also assert byte-identity of legacy-env outputs against the round-4 reference.

Usage: python3 scripts/validate_case_select.py   (exit 0 = all checks pass)
"""
import importlib.util
import json
import os
import re
import subprocess
import sys
import tempfile

REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PLAIN = os.path.join(REPO, "scripts/lcb_public_probe_harness.py")
SPJ = os.path.join(REPO, "scripts/lcb_public_probe_harness_spj.py")
AGG = os.path.join(REPO, "se_patches/benchmarks/livecodebench/_feedback_aggregate.py")
R4_REF = os.environ.get("R4_SPJ_REF")

N = 30
TESTS = {"inputs": [f"{i+1}\n" for i in range(N)], "outputs": [f"{2*(i+1)}\n" for i in range(N)],
         "testtype": "stdin", "time_limit": 4}
FAIL_IDX = {i for i in range(N) if (i + 1) % 3 == 0}
C_OK = "n=int(input())\nprint(2*n)\n"
C_F3 = "n=int(input())\nprint(2*n if n%3 else -1)\n"

passed = failed = 0


def check(name, cond, detail=""):
    global passed, failed
    passed, failed = passed + cond, failed + (not cond)
    print(f"  {'PASS' if cond else 'FAIL'} {name}" + ("" if cond else f"  {detail}"))


def run(harness, code, tests, env_extra):
    env = {k: v for k, v in os.environ.items() if not k.startswith("LCB_")}
    env.update(env_extra)
    with tempfile.TemporaryDirectory() as td:
        cp, tp = os.path.join(td, "c.py"), os.path.join(td, "t.json")
        open(cp, "w").write(code)
        open(tp, "w").write(json.dumps(tests))
        p = subprocess.run([sys.executable, harness, cp, tp],
                           capture_output=True, text=True, timeout=120, env=env)
    return p.stdout.strip().splitlines()[-1]


print("== harness: canonical mode is legacy-shaped ==")
for tag, h in (("plain", PLAIN), ("spj", SPJ)):
    legacy = run(h, C_F3, TESTS, {"LCB_PROBE_MAX_FAILS": "3"})
    explicit = run(h, C_F3, TESTS, {"LCB_PROBE_MAX_FAILS": "3", "LCB_PROBE_ORDER": "canonical"})
    v = json.loads(legacy)
    check(f"{tag}: explicit canonical == unset", legacy == explicit)
    check(f"{tag}: no probe_order/probe_seed keys", "probe_order" not in v and "probe_seed" not in v)
    check(f"{tag}: canonical fails are first-3", [f["idx"] for f in v["fails"]] == [2, 5, 8],
          str([f["idx"] for f in v["fails"]]))
    if R4_REF and tag == "spj":
        check("spj: byte-identical to round-4 reference", legacy == run(R4_REF, C_F3, TESTS, {"LCB_PROBE_MAX_FAILS": "3"}))

print("== harness: shuffle/rotate ==")
E = {"LCB_PROBE_MAX_FAILS": "3", "LCB_PROBE_ORDER": "shuffle", "LCB_PROBE_ORDER_SEED": "p|1|c|"}
r1 = run(SPJ, C_F3, TESTS, E)
check("shuffle deterministic per seed", r1 == run(SPJ, C_F3, TESTS, E))
v = json.loads(r1)
idx1 = [f["idx"] for f in v["fails"]]
check("shuffle: 3 fails, ORIGINAL suite idx", len(idx1) == 3 and set(idx1) <= FAIL_IDX, str(idx1))
check("shuffle: n_pass + 3 == n_ran", v["n_pass"] + 3 == v["n_ran"])
check("shuffle: probe_order/probe_seed recorded", v.get("probe_order") == "shuffle")
union = set()
for s in range(6):
    union |= {f["idx"] for f in json.loads(run(SPJ, C_F3, TESTS, {**E, "LCB_PROBE_ORDER_SEED": f"p|{s}|c|"}))["fails"]}
check("shuffle: 6 seeds reach past the first-3 window", len(union) > 3 and bool(union - {2, 5, 8}), str(sorted(union)))
vr = json.loads(run(SPJ, C_F3, TESTS, {"LCB_PROBE_MAX_FAILS": "3", "LCB_PROBE_ORDER": "rotate",
                                       "LCB_PROBE_ORDER_SEED": "r|7|"}))
check("rotate: 3 original-idx fails", len(vr["fails"]) == 3 and all(f["idx"] in FAIL_IDX for f in vr["fails"]))
vs = json.loads(run(SPJ, C_F3, {**TESTS, "checker": "print(1)\n"}, E))
check("spj checker consulted under shuffle (accept-all -> all_pass)", vs["category"] == "all_pass" and vs["n_pass"] == N)

print("== operator: legacy vs diversity ==")
QUESTION = "TOY problem: read n, print 2*n. (case-select validation fixture)"
TD = tempfile.mkdtemp(prefix="csval_")
seedp, pubp, logp = (os.path.join(TD, x) for x in ("seed.jsonl", "pub.jsonl", "fb_audit.jsonl"))
open(seedp, "w").write(json.dumps({"id": "toy-1", "question": QUESTION}) + "\n")
open(pubp, "w").write(json.dumps({"id": "toy-1", "public_tests": json.dumps(TESTS)}) + "\n")
os.environ.update({"LCB_FB_SEED": seedp, "LCB_FB_PUBLIC": pubp, "LCB_FB_HARNESS": SPJ,
                   "LCB_FB_LOG": logp, "LCB_FB_MAX_SHOWN": "3", "LCB_PROBE_MAX_FAILS": "3",
                   "LCB_FB_FULLTESTS": "1"})
os.environ.pop("LCB_FB_CASE_SELECT", None)
spec = importlib.util.spec_from_file_location("csval_agg", AGG)
agg = importlib.util.module_from_spec(spec)
spec.loader.exec_module(agg)
FENCE = "reasoning...\n```python\n{}\n```\n"
cf, co = FENCE.format(C_F3), FENCE.format(C_OK)
recs = lambda: [json.loads(l) for l in open(logp)]
shown = lambda p: [int(m) for m in re.findall(r"\[test (\d+)\]", p)]

p_legacy = agg.feedback_aggregate(QUESTION, [cf, co])
check("legacy prompt shows canonical first-3", shown(p_legacy) == [2, 5, 8], str(shown(p_legacy)))
r = recs()[-1]
check("legacy log: probe_epoch + shown_cases", r.get("probe_epoch") == 1 and r.get("shown_cases") == [[2, 5, 8], None], str(r))
check("legacy log: no case_select", "case_select" not in r)

os.environ["LCB_FB_CASE_SELECT"] = "shuffle"
s1, s2 = shown(agg.feedback_aggregate(QUESTION, [cf, co])), shown(agg.feedback_aggregate(QUESTION, [cf, co]))
check("diversity: 3 real failing cases per call", len(s1) == 3 and len(s2) == 3 and set(s1) <= FAIL_IDX and set(s2) <= FAIL_IDX,
      f"{s1} / {s2}")
check("diversity: consecutive epochs differ (stuck candidate un-stalled)", s1 != s2, f"{s1} vs {s2}")
r1_, r2_ = recs()[-2], recs()[-1]
check("diversity log: epochs increment", (r1_.get("probe_epoch"), r2_.get("probe_epoch")) == (2, 3))
check("diversity log: case_select/seeds/shown_cases", r1_.get("case_select") == "shuffle"
      and r1_.get("case_seeds") and r1_["case_seeds"][0].startswith("toy-1|2|")
      and r1_.get("shown_cases") == [s1, None], str(r1_))

os.environ.pop("LCB_FB_CASE_SELECT", None)
check("legacy prompt reproduced after diversity calls (cache clean)",
      agg.feedback_aggregate(QUESTION, [cf, co]) == p_legacy)

print("== canonical operator (the one the r4/r5 oracle-fb runs use) ==")
CAN = os.path.join(REPO, "se_patches/benchmarks/livecodebench/_feedback_canonical.py")
spec_c = importlib.util.spec_from_file_location("csval_canonical", CAN)
can = importlib.util.module_from_spec(spec_c)
spec_c.loader.exec_module(can)
pc = can.feedback_canonical(QUESTION, [cf, co])
check("canonical legacy shows first-3", shown(pc) == [2, 5, 8], str(shown(pc)))
check("canonical prompt is the balanced (non-stay-close) top", "Combine the best ideas" in pc)
rc_ = recs()[-1]
check("canonical log: operator + probe_epoch + shown_cases", rc_.get("operator") == "canonical_fb"
      and rc_.get("probe_epoch") == 1 and rc_.get("shown_cases") == [[2, 5, 8], None], str(rc_))
os.environ["LCB_FB_CASE_SELECT"] = "shuffle"
c1, c2 = shown(can.feedback_canonical(QUESTION, [cf, co])), shown(can.feedback_canonical(QUESTION, [cf, co]))
check("canonical diversity: consecutive epochs differ", len(c1) == 3 and len(c2) == 3
      and set(c1) <= FAIL_IDX and set(c2) <= FAIL_IDX and c1 != c2, f"{c1} vs {c2}")
check("canonical diversity log: case_select/seeds", recs()[-1].get("case_select") == "shuffle"
      and recs()[-1].get("case_seeds") and recs()[-1]["case_seeds"][0].startswith("toy-1|3|"))
os.environ.pop("LCB_FB_CASE_SELECT", None)
check("canonical legacy prompt reproduced (cache clean)", can.feedback_canonical(QUESTION, [cf, co]) == pc)

print(f"\n{passed} passed, {failed} failed")
sys.exit(1 if failed else 0)