| |
| """D-cut CPU validation: arms A (brute-ref), B (ref-diverse), C (out-validators), |
| D (trace-repair) — stubbed-LLM integration through handle_problem + harness tests. |
| No GPU, no network. 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_SPJ = os.path.join(HERE, "minipatch", "scripts", "lcb_public_probe_harness_spj.py") |
| HARNESS_ORIG = os.path.join(HERE, "..", "round5_sv_cut", "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 "")) |
|
|
| |
| P1 = ("Read two integers a and b from stdin and print their sum.\n\n" |
| "Example\nInput\n1 2\nOutput\n3\n") |
| P2 = ("Given n, print any pair of positive integers a b with a+b = n. " |
| "If there are multiple valid answers, print any of them.\n\n" |
| "Example\nInput\n4\nOutput\n1 3\n") |
| SUM_CODE = "a,b=map(int,input().split());print(a+b)" |
| BAD_EFF = "a,b=map(int,input().split());print(a-b)" |
| DEVIANT = "a,b=map(int,input().split());print(a*b if a==b else a+b)" |
| PAIR_OK = "n=int(input());print(1, n-1)" |
| VALID_OVAL = ("import sys\n" |
| "inp=open(sys.argv[1]).read().split();out=open(sys.argv[2]).read().split()\n" |
| "n=int(inp[0])\n" |
| "sys.exit(0 if len(out)==2 and all(t.lstrip('-').isdigit() for t in out)\n" |
| " and int(out[0])>0 and int(out[1])>0 and int(out[0])+int(out[1])==n else 1)\n") |
| BROKEN_OVAL = "import sys\nsys.exit(0)\n" |
|
|
| class FakeMsg: pass |
| class FakeClient: |
| def __init__(self, sums=SUM_CODE, eff_b=SUM_CODE, oval=VALID_OVAL): |
| self.n_reread = 0 |
| self.sums, self.eff_b, self.oval = sums, eff_b, oval |
| c = self |
| class Completions: |
| async def create(self, **kw): |
| prompt = kw["messages"][0]["content"] |
| txt = c.route(prompt) |
| r = FakeMsg(); r.usage = FakeMsg() |
| r.usage.prompt_tokens = 10; r.usage.completion_tokens = 10 |
| ch = FakeMsg(); ch.message = FakeMsg(); ch.message.content = txt |
| r.choices = [ch] |
| return r |
| self.chat = FakeMsg(); self.chat.completions = Completions() |
| def route(self, p): |
| py = lambda c: f"```python\n{c}\n```" |
| if "Extract every SAMPLE" in p or "worked EXAMPLES" in p: |
| smp = ({"input": "4\n", "output": "1 3\n"} if "pair" in p |
| else {"input": "1 2\n", "output": "3\n"}) |
| return f"```json\n{json.dumps({'samples': [smp]})}\n```" |
| if "stress-input design" in p: |
| probes = ["6\n"] if "pair" in p else ["0 0\n"] |
| return (f"```json\n{json.dumps({'probe_inputs': [{'input': x} for x in probes]})}\n```" |
| f"\n```python\nimport sys\nsys.exit(0)\n```") |
| if "OUTPUT VALIDATOR program" in p: |
| return py(self.oval) |
| if "BRUTE-FORCE Python reference" in p: |
| return py(self.sums) |
| if "independent reading attempt" in p: |
| self.n_reread += 1 |
| return py(SUM_CODE if self.n_reread % 2 else DEVIANT) |
| if "EFFICIENT, production-quality" in p: |
| return py(PAIR_OK if "pair" in p else self.sums) |
| if "name the algorithm" in p: |
| return py(PAIR_OK if "pair" in p else self.eff_b) |
| if "break_inputs" in p: |
| return f"```json\n{json.dumps({'break_inputs': [{'input': '5 5\n'}, {'input': '9 1\n'}]})}\n```" |
| |
| return py(PAIR_OK if "pair" in p else SUM_CODE) |
|
|
| 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, "seeds.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, "audit.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, pid, question, cands, client): |
| 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") |
| prob = {"question": question, "cands": cands} |
| await mod.handle_problem(pid, prob, {"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 = {} |
| for l in open(args.out): |
| if l.strip() and not args.out.endswith("summary.jsonl"): |
| r = json.loads(l) |
| if "public_tests" in r: |
| tests[r["id"]] = json.loads(r["public_tests"]) |
| return audit, tests.get(pid) |
|
|
| def run_harness(harness, code, tests): |
| 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) |
| return json.loads(r.stdout.strip().splitlines()[-1]) |
|
|
| |
| check("T0a oval accepts valid", mod.run_out_validator(VALID_OVAL, "4\n", "2 2\n", 4.0) is True) |
| check("T0b oval rejects invalid", mod.run_out_validator(VALID_OVAL, "4\n", "9 9\n", 4.0) is False) |
| check("T0c oval crash = None", mod.run_out_validator("raise RuntimeError()", "4\n", "1 3\n", 4.0) in (False, None)) |
|
|
| |
| tests_prop = {"inputs": ["4\n", "6\n"], "outputs": [None, None], |
| "out_validators": [VALID_OVAL, VALID_OVAL], "time_limit": 4} |
| v = run_harness(HARNESS_SPJ, "n=int(input());print(2, n-2)", tests_prop) |
| check("T1 harness: alternate valid answer passes", v["category"] == "all_pass", str(v)[:120]) |
| v = run_harness(HARNESS_SPJ, "n=int(input());print(9, 9)", tests_prop) |
| check("T2 harness: invalid answer -> wrong_answer w/ property text", |
| v["category"] == "wrong_answer" and "certified checker" in str(v.get("first_fail", {}).get("expected")), |
| str(v)[:160]) |
| tests_plain = {"inputs": ["1 2\n"], "outputs": ["3\n"], "time_limit": 4} |
| v1 = run_harness(HARNESS_SPJ, SUM_CODE, tests_plain) |
| v2 = run_harness(HARNESS_ORIG, SUM_CODE, tests_plain) |
| check("T3 harness: bit-identical without field", v1 == v2, f"{v1} vs {v2}") |
|
|
| |
| with tempfile.TemporaryDirectory() as tmp: |
| a = make_args([], tmp) |
| audit, t = drive(a, "p1", P1, [f"```python\n{SUM_CODE}\n```"], FakeClient(eff_b=BAD_EFF)) |
| wb_out_ctrl = [o for i, o in zip(t["inputs"], t["outputs"]) if i.startswith("5 5")] |
| ctrl_keys = set(audit["funnel"]) |
| with tempfile.TemporaryDirectory() as tmp: |
| a = make_args(["--brute-ref"], tmp) |
| audit, t = drive(a, "p1", P1, [f"```python\n{SUM_CODE}\n```"], FakeClient(eff_b=BAD_EFF)) |
| f = audit["funnel"] |
| wb_out = [o for i, o in zip(t["inputs"], t["outputs"]) if i.startswith("5 5")] |
| check("T4a brute validated", f.get("n_brute_valid") == 1, str(f)) |
| check("T4b brute certifies wb label (1 eff + brute)", |
| f.get("n_wb_cert_brute", 0) >= 1 and wb_out and wb_out[0] == "10", |
| f"cert={f.get('n_wb_cert_brute')} out={wb_out}") |
| check("T4c control stripped the same label", wb_out_ctrl and wb_out_ctrl[0] is None, str(wb_out_ctrl)) |
| check("T4d control funnel has no D-cut keys", |
| not (ctrl_keys & {"n_brute_valid", "n_wb_cert_brute", "oval_certified", |
| "n_disputes", "trace_streak"}), str(ctrl_keys)) |
|
|
| |
| with tempfile.TemporaryDirectory() as tmp: |
| a = make_args(["--ref-diverse", "2"], tmp) |
| audit, t = drive(a, "p1", P1, [f"```python\n{SUM_CODE}\n```"], FakeClient()) |
| f = audit["funnel"] |
| srows = [json.loads(l) for l in open(a.out + ".summary.jsonl")] \ |
| if os.path.exists(a.out + ".summary.jsonl") else [] |
| check("T5a diverse refs sample-gated", f.get("n_diverse_valid", 0) >= 1, str(f)) |
| check("T5b dispute detected + surfaced", |
| f.get("n_disputes", 0) >= 1 and any("READING CHECK" in r["summary"] for r in srows), |
| f"disputes={f.get('n_disputes')} rows={len(srows)}") |
|
|
| |
| with tempfile.TemporaryDirectory() as tmp: |
| a = make_args(["--out-validators"], tmp) |
| audit, t = drive(a, "p2", P2, [f"```python\n{PAIR_OK}\n```"], FakeClient()) |
| f = audit["funnel"] |
| check("T6a validator certified", f.get("oval_certified") is True, str(f)) |
| check("T6b emission property-only", |
| t and t.get("out_validators") and all(o is None for o in t["outputs"]), |
| str(t)[:150]) |
| with tempfile.TemporaryDirectory() as tmp: |
| a = make_args(["--out-validators"], tmp) |
| audit, t = drive(a, "p2", P2, [f"```python\n{PAIR_OK}\n```"], FakeClient(oval=BROKEN_OVAL)) |
| check("T7 broken validator -> conservative skip", |
| audit["funnel"].get("oval_certified") is False and audit.get("skip_prop") |
| and not t, f"{audit.get('skip_prop')} t={bool(t)}") |
|
|
| |
| with tempfile.TemporaryDirectory() as tmp: |
| a1 = make_args(["--trace-repair"], tmp, loop_n=1) |
| bad = f"```python\n{BAD_EFF}\n```" |
| audit1, _ = drive(a1, "p1", P1, [bad, bad], FakeClient()) |
| s1 = os.path.exists(a1.out + ".summary.jsonl") |
| a2 = make_args(["--trace-repair"], tmp, loop_n=2) |
| audit2, _ = drive(a2, "p1", P1, [bad, bad], FakeClient()) |
| srows = [json.loads(l) for l in open(a2.out + ".summary.jsonl")] \ |
| if os.path.exists(a2.out + ".summary.jsonl") else [] |
| check("T8a loop1: streak=1, no repair row yet", |
| audit1["funnel"].get("trace_streak") == 1 and not s1, |
| str(audit1["funnel"])) |
| check("T8b loop2: streak=2 fires REPAIR MODE", |
| audit2["funnel"].get("trace_streak") == 2 |
| and any("REPAIR MODE" in r["summary"] for r in srows), |
| f"{audit2['funnel'].get('trace_streak')} rows={len(srows)}") |
|
|
| print(f"\n{PASS} passed, {FAIL} failed") |
| sys.exit(1 if FAIL else 0) |
|
|