#!/usr/bin/env python3 """RT-cut CPU validation: trace-exec (harness+renderer), blocked-restart (prepare+renderer), emit-top-k, and the rt7 routed combo. Exit 0 = all pass.""" import asyncio, importlib.util, json, os, subprocess, sys, tempfile from concurrent.futures import ThreadPoolExecutor HERE = os.path.dirname(os.path.abspath(__file__)) SELF = os.path.join(HERE, "minipatch", "selffb") sys.path.insert(0, SELF) spec = importlib.util.spec_from_file_location("svp", os.path.join(SELF, "selffb_v2_prepare.py")) mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod) HARNESS = os.path.join(HERE, "minipatch", "scripts", "lcb_public_probe_harness_spj.py") RUN_INPUTS = os.path.join(SELF, "run_inputs_harness.py") PASS = FAIL = 0 def check(name, ok, detail=""): global PASS, FAIL ok = bool(ok); PASS += ok; FAIL += (not ok) print(f"{'PASS' if ok else 'FAIL'} {name}" + (f" [{detail}]" if detail and not ok else "")) def run_harness(code, tests, env=None): e = dict(os.environ); e.update(env or {}) with tempfile.TemporaryDirectory() as td: cp = os.path.join(td, "c.py"); open(cp, "w").write(code) tp = os.path.join(td, "t.json"); json.dump(tests, open(tp, "w")) r = subprocess.run([sys.executable, HARNESS, cp, tp], capture_output=True, text=True, timeout=120, env=e) return json.loads(r.stdout.strip().splitlines()[-1]) # ── T1-T2: harness trace ───────────────────────────────────────────────── WA = "a,b=map(int,input().split())\ns=a-b\nprint(s)" tests = {"inputs": ["3 4\n"], "outputs": ["7\n"], "time_limit": 4} v_on = run_harness(WA, tests, {"LCB_TRACE_EXEC": "1"}) v_off = run_harness(WA, tests) tr = (v_on.get("first_fail") or {}).get("trace", "") check("T1a trace present w/ env", "L2:" in tr and "s=" in tr, tr[:120]) check("T1b bit-identical w/o env", "trace" not in (v_off.get("first_fail") or {}), str(v_off)[:100]) TLE = "a,b=map(int,input().split())\nwhile True:\n a+=1" v = run_harness(TLE, {"inputs": ["1 2\n"], "outputs": ["3\n"], "time_limit": 3}, {"LCB_TRACE_EXEC": "1"}) tr = (v.get("first_fail") or {}).get("trace", "") check("T2 TLE trace shows hot loop", "TIME LIMIT" in tr and "a+=1" in tr, tr[-150:]) # ── T3: aggregate renderer shows trace ─────────────────────────────────── aspec = importlib.util.spec_from_file_location( "fa", os.path.join(HERE, "minipatch", "benchmarks", "livecodebench", "_feedback_aggregate.py")) fa = importlib.util.module_from_spec(aspec); aspec.loader.exec_module(fa) os.environ["LCB_FB_MAX_SHOWN"] = "3" pub = {"category": "wrong_answer", "n_pass": 0, "n_ran": 1, "n_total": 1, "first_fail": {"idx": 0, "input": "3 4", "expected": "7", "actual": "-1", "kind": "wrong_answer", "trace": "L2: s=a-b || s=-1"}, "fails": [{"idx": 0, "input": "3 4", "expected": "7", "actual": "-1", "kind": "wrong_answer", "trace": "L2: s=a-b || s=-1"}]} blk = fa._rich_block(pub, 3) check("T3 renderer includes RUNTIME TRACE", "RUNTIME TRACE" in blk and "s=a-b" in blk, blk[:150]) # ── T4: canonical restart mode ─────────────────────────────────────────── with tempfile.TemporaryDirectory() as td: seedf = os.path.join(td, "seeds.jsonl") open(seedf, "w").write(json.dumps({"id": "p1", "question": "QSTATEMENT", "problem": "QSTATEMENT"}) + "\n") pubf = os.path.join(td, "pub.jsonl") open(pubf, "w").write(json.dumps({"id": "p1", "public_tests": json.dumps( {"inputs": ["1 2\n"], "outputs": ["3\n"], "time_limit": 4})}) + "\n") logf = os.path.join(td, "fb.jsonl") rst = os.path.join(td, "r.jsonl") open(rst, "w").write(json.dumps({"id": "p1", "loop": 3, "keep": 2}) + "\n") env = {"LCB_FB_SEED": seedf, "LCB_FB_PUBLIC": pubf, "LCB_FB_LOG": logf, "LCB_FB_HARNESS": HARNESS, "LCB_FB_MAX_SHOWN": "3"} for k, v in env.items(): os.environ[k] = v cspec = importlib.util.spec_from_file_location( "fc", os.path.join(HERE, "minipatch", "benchmarks", "livecodebench", "_feedback_canonical.py")) fc = importlib.util.module_from_spec(cspec); cspec.loader.exec_module(fc) fn = getattr(fc, "feedback_canonical", None) or getattr(fc, "canonical_fb", None) if fn is None: fn = next(v for k, v in vars(fc).items() if callable(v) and "feedback" in k or k == "operator") cands = [f"```python\nprint({i})\n```" for i in range(5)] os.environ["LCB_FB_RESTART"] = rst out_on = fn("QSTATEMENT", cands) del os.environ["LCB_FB_RESTART"] out_off = fn("QSTATEMENT", cands) check("T4a restart: directive + only 2 parents", "RESTART DIRECTIVE" in out_on and "Solution 3" not in out_on and "Solution 2" in out_on, out_on[-200:]) check("T4b no env: all 5 parents, no directive", "RESTART DIRECTIVE" not in out_off and "Solution 5" in out_off, out_off[:100]) # ── T5-T8: prepare end-to-end (stub client from D-cut suite) ───────────── sys.path.insert(0, os.path.join(HERE, "..", "round5_abcd_cut")) P1 = ("Read two integers a and b from stdin and print their sum.\n\n" "Example\nInput\n1 2\nOutput\n3\n") SUM_CODE = "a,b=map(int,input().split());print(a+b)" BAD = "a,b=map(int,input().split());print(a-b)" class FM: pass class Client: def __init__(self): c = self class Comp: async def create(self, **kw): p = kw["messages"][0]["content"] py = lambda cd: f"```python\n{cd}\n```" if "Extract every SAMPLE" in p or "worked EXAMPLES" in p: t = f"```json\n{json.dumps({'samples': [{'input': '1 2\n', 'output': '3\n'}]})}\n```" elif "stress-input design" in p: t = (f"```json\n{json.dumps({'probe_inputs': [{'input': '0 0\n'}]})}\n```" "\n```python\nimport sys\nsys.exit(0)\n```") elif "break_inputs" in p: t = f"```json\n{json.dumps({'break_inputs': [{'input': '5 5\n'}]})}\n```" else: t = py(SUM_CODE) r = FM(); r.usage = FM(); r.usage.prompt_tokens = 5; r.usage.completion_tokens = 5 ch = FM(); ch.message = FM(); ch.message.content = t; r.choices = [ch] return r self.chat = FM(); self.chat.completions = Comp() def make_args(extra, tmp, loop_n=1): cap = {}; orig_run, orig_ma = mod.asyncio.run, mod.main_async mod.main_async = lambda a: cap.update(a=a); mod.asyncio.run = lambda c: c ck = os.path.join(tmp, "ck.json"); json.dump({"problems": []}, open(ck, "w")) sd = os.path.join(tmp, "s.jsonl"); open(sd, "w").write("") argv = ["p", "--checkpoint", ck, "--seeds", sd, "--loop", str(loop_n), "--out", os.path.join(tmp, "fb_tests.jsonl"), "--audit", os.path.join(tmp, "a.jsonl"), "--bank", os.path.join(tmp, "bank.jsonl"), "--harness", RUN_INPUTS, "--agree", "all", "--samples", "anchor", "--gen-tests", "off", "--probes", "valid", "--wb-cands", "8", "--wb-certify", "--eff-anchor-tol", "0.7", "--exec-workers", "4", "--time-limit", "4.0"] + extra old = sys.argv; sys.argv = argv try: mod.main() finally: sys.argv = old; mod.asyncio.run = orig_run; mod.main_async = orig_ma a = cap["a"] a._trstreak_path = a.bank + ".trstreak.json" try: a._trstreak = json.load(open(a._trstreak_path)) except Exception: a._trstreak = {} return a def drive(args, cands): async def go(): sem = asyncio.Semaphore(8); pool = ThreadPoolExecutor(max_workers=4) bank = mod.Bank(args.bank); lock = asyncio.Lock() outf = open(args.out, "a"); auditf = open(args.audit, "a") await mod.handle_problem("p1", {"question": P1, "cands": cands}, {"format": "stdin_stdout"}, Client(), args, sem, pool, bank, outf, auditf, lock) outf.close(); auditf.close(); pool.shutdown() asyncio.run(go()) audit = [json.loads(l) for l in open(args.audit)][-1] tests = None for l in open(args.out): r = json.loads(l) if r.get("id") == "p1" and "public_tests" in r: tests = json.loads(r["public_tests"]) return audit, tests bad = f"```python\n{BAD}\n```" with tempfile.TemporaryDirectory() as tmp: a1 = make_args(["--blocked-restart"], tmp, 1); drive(a1, [bad, bad]) a2 = make_args(["--blocked-restart"], tmp, 2) audit, _ = drive(a2, [bad, bad]) rows = [json.loads(l) for l in open(a2.out + ".restart.jsonl")] \ if os.path.exists(a2.out + ".restart.jsonl") else [] check("T5 blocked-restart fires at streak 2", audit["funnel"].get("restart_fired") and rows and rows[-1]["keep"] == 4, f"{audit['funnel'].get('restart_fired')} rows={rows}") with tempfile.TemporaryDirectory() as tmp: a = make_args(["--emit-order", "failcount", "--emit-top-k", "2", "--fb-summary"], tmp) audit, t = drive(a, [bad, bad]) bank_n = len(json.loads(next(iter(open(a.bank))))["tests"]) check("T6 emit-top-k: emission 2, bank larger", t and len(t["inputs"]) == 2 and bank_n > 2, f"emitted={len(t['inputs']) if t else 0} bank={bank_n}") with tempfile.TemporaryDirectory() as tmp: a = make_args(["--wb-pair", "--emit-order", "failcount", "--emit-top-k", "20", "--out-validators", "--blocked-restart"], tmp) audit, t = drive(a, [bad, bad]) check("T7 rt7 combo runs clean, tests emitted", t and audit["funnel"].get("n_bank", 0) > 0, str(audit["funnel"])[:120]) with tempfile.TemporaryDirectory() as tmp: a = make_args([], tmp) audit, t = drive(a, [f"```python\n{SUM_CODE}\n```"]) check("T8 sv7 control: no RT funnel keys", not (set(audit["funnel"]) & {"restart_fired"}) and t, str(audit["funnel"])[:100]) print(f"\n{PASS} passed, {FAIL} failed") sys.exit(1 if FAIL else 0)