"""AGA-Code Stage B / Stage C dataset builder (v2 — with Guy's review folded in). Review compliance built into this file: 1. ~10 families HELD OUT of Stage B entirely (transfer test set). 2. ~20% of Stage B examples are already-correct drafts ("clean"): the critique explicitly says no bug was found and revise is a no-op. Bug kinds mirror real small-model errors (off_by_one, wrong_operator, missing_return, wrong_variable, wrong_edge, swapped_branch, missing_case). 3. Stage C is tiered: a LARGE easy tier + standard + held-out tier, and every Stage C instruction states the exact function signature. 4. Stage C problems are mutation-scored: >=5 mutants per problem, problems with mutation score < 0.6 are DROPPED. 5. Stage B / Stage C instructions are disjoint (normalized-hash check). 6. No model generation/decoding anywhere in this build (pure subprocess execution harness) — tokenizer-independent; aga_code.py is v0.1.7. Usage: python build.py selftest | pilot | full """ import hashlib import json import os import random import sys import time from concurrent.futures import ProcessPoolExecutor from datetime import date sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from framework import (REGISTRY, THINK_SKELETONS, CRITIQUE_TEMPLATES, CRITIQUE_CLEAN, MASTER_SEED, run_tests, exec_run, trivial_wrong_solutions, sha256_hex, norm_instruction) import families_a, families_b, families_c # noqa: F401 — registers families WORK = os.path.dirname(os.path.abspath(__file__)) MAX_CHARS = 12000 FAM_CAP = 0.10 PHRASE_CAP = 0.05 CLEAN_FRACTION = 0.20 MUTATION_MIN = 0.6 MUTATION_COUNT_MIN = 5 HELD_OUT = { "caesar_cipher", "run_length_encode", "merge_sorted", "prime_factors", "collatz_steps", "quicksort", "csv_parse_line", "eval_expr", "bank_account", "matrix_multiply", } CLEAN_CHECKS = [ "bounds, operators, and return values", "control flow and edge cases", "loop bounds, comparisons, and the return statement", "the specification, point by point", ] OP_FLIPS = [(" == ", " != "), (" != ", " == "), (" <= ", " >= "), (" >= ", " <= "), (" < ", " > "), (" > ", " < "), (" + ", " - "), (" - ", " + "), (" * ", " + "), (" % ", " * ")] # -------------------------------------------------------------------------- # Mutants for Stage C mutation scoring (generic, generator-independent) # -------------------------------------------------------------------------- def _shells(ref): lines = ref.splitlines() first = lines[0] shells = [] if first.startswith("def "): for body in ["return None", "return 0", "return []", "return ''", "raise RuntimeError('mutant')"]: shells.append(first + "\n " + body) elif first.startswith("class "): name = first[6:].rstrip(":").strip() shells.append(f"class {name}:\n def __init__(self, *a, **k):\n" " raise RuntimeError('mutant')") methods = [ln.strip()[4:-1] for ln in lines[1:] if ln.strip().startswith("def ") and "__init__" not in ln] if methods: body = [f"class {name}:", " def __init__(self, *a, **k):", " pass"] for m in methods: body.append(f" def {m}:") body.append(" return None") shells.append("\n".join(body)) return shells def generic_mutants(g): """Mutants in priority order: family bugs, operator flips, return-None mutants, trivial shells. Caller caps the count.""" ref = g.reference muts = [b.code for b in g.bugs] for a, b in OP_FLIPS: if a in ref: muts.append(ref.replace(a, b, 1)) lines = ref.splitlines() for i, ln in enumerate(lines): if ln.lstrip().startswith("return ") and "None" not in ln: m = lines[:] indent = ln[:len(ln) - len(ln.lstrip())] m[i] = indent + "return None" muts.append("\n".join(m)) muts.extend(_shells(ref)) seen, out = set(), [] for m in muts: if m == ref: continue h = sha256_hex(m) if h in seen: continue try: compile(m, "", "exec") except SyntaxError: continue seen.add(h) out.append(m) return out def example_block(tests): """A concrete worked example (setup + first assert) embedded in the instruction — makes instructions instance-specific (combinatorial diversity) instead of bare templates.""" lines = tests.splitlines() setup = [ln for ln in lines if ln.strip() and not ln.strip().startswith("assert")] asserts = [ln for ln in lines if ln.strip().startswith("assert")] block = setup + asserts[:1] return "\n\nExample:\n" + "\n".join(block) def first_failing_assert_fast(code, tests, timeout=1.5): setup = [ln for ln in tests.splitlines() if ln.strip() and not ln.strip().startswith("assert")] asserts = [ln for ln in tests.splitlines() if ln.strip().startswith("assert")] ctx = "\n".join(setup) for ln in asserts[:4]: if not exec_run(code, (ctx + "\n" + ln) if ctx else ln, timeout=timeout): return ln.strip() return None def signature_block(ref): lines = ref.splitlines() first = lines[0].strip() if first.startswith("class "): name = first[6:].rstrip(":").strip() methods = [ln.strip()[4:-1] for ln in lines[1:] if ln.strip().startswith("def ") and "__init__" not in ln] return f"class {name} with methods: {', '.join(methods)}" return first.rstrip(":") # -------------------------------------------------------------------------- # Instance assembly (worker processes) # -------------------------------------------------------------------------- def assemble_stage_b(job): fam_idx, seed = job rng = random.Random(seed) fam = REGISTRY[fam_idx] if fam.name in HELD_OUT: return None, {"family": fam.name, "reason": "held_out"} g = fam.gen(rng, hard=(rng.random() < 0.4)) if not exec_run(g.reference, g.tests): return None, {"family": fam.name, "reason": "ref_fail"} instruction = g.instruction + example_block(g.tests) think = rng.choice(THINK_SKELETONS).format(**g.think_slots) kind = "clean" if rng.random() < CLEAN_FRACTION: critique = rng.choice(CRITIQUE_CLEAN).format( ref=g.reference, check=rng.choice(CLEAN_CHECKS)) clean = True else: clean = False bugs = list(g.bugs) rng.shuffle(bugs) chosen, failing = None, None for b in bugs: if not exec_run(b.code, g.tests): chosen = b failing = first_failing_assert_fast(b.code, g.tests) break if chosen is None: return None, {"family": fam.name, "reason": "no_bug"} critique = rng.choice(CRITIQUE_TEMPLATES[chosen.kind]).format( buggy=chosen.code, note=chosen.note, failing=failing or "(a test case)") kind = chosen.kind row = { "instruction": instruction, "think": think, "critique": critique, "revise": g.reference, "answer": g.reference, "tests": g.tests, "family": fam.name, "difficulty": g.difficulty, "seed": seed, "clean": clean, "_phrasing": g.phrasing, "_kind": kind, } return row, None def assemble_stage_c(job): fam_idx, seed, tier = job rng = random.Random(seed) fam = REGISTRY[fam_idx] hard = (tier == "standard" and rng.random() < 0.8) or \ (tier == "held_out" and rng.random() < 0.5) g = fam.gen(rng, hard=hard) if not exec_run(g.reference, g.tests): return None, {"family": fam.name, "reason": "ref_fail", "tier": tier} wrongs = trivial_wrong_solutions(g) if not any(not exec_run(w, g.tests) for w in wrongs): return None, {"family": fam.name, "reason": "vacuous", "tier": tier} muts = generic_mutants(g)[:10] if len(muts) < MUTATION_COUNT_MIN: return None, {"family": fam.name, "reason": "few_mutants", "tier": tier} killed = sum(1 for m in muts if not exec_run(m, g.tests, timeout=1.0)) score = killed / len(muts) if score < MUTATION_MIN: return None, {"family": fam.name, "reason": "low_mutation", "tier": tier} sig = signature_block(g.reference) base_instruction = g.instruction + example_block(g.tests) instruction = (base_instruction + f"\n\nImplement exactly this signature: `{sig}`. " "The tests call it directly.") row = { "instruction": instruction, "_base_instruction": base_instruction, "tests": g.tests, "family": fam.name, "difficulty": g.difficulty, "seed": seed, "tier": tier, "mutation_score": round(score, 3), "_phrasing": g.phrasing, "_reference": g.reference, } return row, None # -------------------------------------------------------------------------- # Driver helpers # -------------------------------------------------------------------------- def run_jobs(assembler, jobs): rows, discards = [], {} workers = min(8, os.cpu_count() or 4) with ProcessPoolExecutor(max_workers=workers) as ex: for row, disc in ex.map(assembler, jobs, chunksize=16): if row is None: k = f"{disc['family']}/{disc['reason']}" discards[k] = discards.get(k, 0) + 1 else: rows.append(row) return rows, discards def dedupe_cap(rows, key_fn, total_target, stats): seen, out = set(), [] for r in rows: h = sha256_hex(key_fn(r)) if h in seen: stats["dups"] += 1 continue seen.add(h) out.append(r) cap_f = int(total_target * FAM_CAP) cap_p = int(total_target * PHRASE_CAP) kept, fc, pc = [], {}, {} for r in out: if fc.get(r["family"], 0) >= cap_f or pc.get(r["_phrasing"], 0) >= cap_p: stats["cap_drops"] += 1 continue fc[r["family"]] = fc.get(r["family"], 0) + 1 pc[r["_phrasing"]] = pc.get(r["_phrasing"], 0) + 1 kept.append(r) return kept[:total_target] def famdist(rows, key="family"): d = {} for r in rows: d[r[key]] = d.get(r[key], 0) + 1 return d def sha256_file(path): h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(1 << 20), b""): h.update(chunk) return h.hexdigest() # -------------------------------------------------------------------------- # Build stages # -------------------------------------------------------------------------- def build_stage_b(target, log): t0 = time.time() pool = [i for i, f in enumerate(REGISTRY) if f.name not in HELD_OUT] rng = random.Random(MASTER_SEED + 11) n = int(target * 1.35) + 50 jobs = [(pool[rng.randrange(len(pool))], MASTER_SEED * 1000003 + 11 * 7919 + i) for i in range(n)] rows, discards = run_jobs(assemble_stage_b, jobs) rows = [r for r in rows if len(r["instruction"] + r["think"] + r["critique"] + r["revise"] + r["answer"]) <= MAX_CHARS] stats = {"dups": 0, "cap_drops": 0} kept = dedupe_cap(rows, lambda r: r["instruction"] + "\x00" + r["answer"], target, stats) log["stage_b"] = {"generated": len(jobs), "assembled": len(rows), "kept": len(kept), "discards": discards, "dedup": stats, "seconds": round(time.time() - t0, 1)} print(f"[stage_b] generated {len(jobs)} -> assembled {len(rows)} -> kept " f"{len(kept)} (discards={sum(discards.values())}) " f"in {log['stage_b']['seconds']}s") for k, c in sorted(discards.items(), key=lambda x: -x[1])[:12]: print(f"[stage_b] discard {k}: {c}") return kept TIER_POOLS = { "easy": lambda f: f.name not in HELD_OUT and f.difficulty in ("easy", "medium"), "standard": lambda f: f.name not in HELD_OUT and f.difficulty in ("medium", "hard"), "held_out": lambda f: f.name in HELD_OUT, } def build_stage_c(tier_targets, log): kept_all = [] log["stage_c"] = {} for tier, target in tier_targets.items(): t0 = time.time() pool = [i for i, f in enumerate(REGISTRY) if TIER_POOLS[tier](f)] # NB: str hash() is process-salted (PYTHONHASHSEED); use a fixed map so # tier job selection is reproducible row-for-row. rng = random.Random(MASTER_SEED + {"easy": 11, "standard": 22, "held_out": 33}[tier]) over = {"easy": 1.5, "standard": 1.6, "held_out": 2.3}[tier] n = int(target * over) + 30 base = {"easy": 101, "standard": 202, "held_out": 303}[tier] jobs = [(pool[rng.randrange(len(pool))], MASTER_SEED * 1000003 + base * 7919 + i, tier) for i in range(n)] rows, discards = run_jobs(assemble_stage_c, jobs) stats = {"dups": 0, "cap_drops": 0} kept = dedupe_cap(rows, lambda r: r["_base_instruction"] + "\x00" + r["tests"], target, stats) scores = [r["mutation_score"] for r in kept] log["stage_c"][tier] = { "generated": len(jobs), "assembled": len(rows), "kept": len(kept), "assembly_rate": round(len(rows) / max(1, len(jobs)), 3), "acceptance": round(len(kept) / max(1, len(rows)), 3), "discards": discards, "dedup": stats, "mutation_mean": round(sum(scores) / max(1, len(scores)), 3), "mutation_min": min(scores) if scores else None, "seconds": round(time.time() - t0, 1), } print(f"[stage_c:{tier}] generated {len(jobs)} -> kept {len(kept)} " f"(acceptance {log['stage_c'][tier]['acceptance']}, " f"mutation mean {log['stage_c'][tier]['mutation_mean']}) " f"in {log['stage_c'][tier]['seconds']}s") for k, c in sorted(discards.items(), key=lambda x: -x[1])[:8]: print(f"[stage_c:{tier}] discard {k}: {c}") kept_all.extend(kept) return kept_all def main(): mode = sys.argv[1] if len(sys.argv) > 1 else "pilot" assert mode in ("pilot", "full", "selftest"), mode if mode == "selftest": bad = [] for i, fam in enumerate(REGISTRY): row, disc = assemble_stage_c((i, MASTER_SEED + i, "held_out")) if row is None: bad.append((fam.name, disc["reason"])) print(f"[selftest] FAIL(stageC) {fam.name}: {disc['reason']}") if fam.name not in HELD_OUT: row, disc = assemble_stage_b((i, MASTER_SEED + i)) if row is None: bad.append((fam.name, disc["reason"])) print(f"[selftest] FAIL(stageB) {fam.name}: {disc['reason']}") print(f"[selftest] {len(REGISTRY) * 2 - len(HELD_OUT) * 1 - len(bad)} checks, " f"{len(bad)} failures") if bad: sys.exit(1) return if mode == "pilot": n_b, tiers = 500, {"easy": 150, "standard": 100, "held_out": 50} tag = "pilot" else: n_b, tiers = 25000, {"easy": 5000, "standard": 3500, "held_out": 1500} tag = "v1" log = {} rows_b = build_stage_b(n_b, log) rows_c = build_stage_c(tiers, log) # cross-set disjointness on BASE instructions (point 5) b_hashes = {sha256_hex(norm_instruction(r["instruction"])) for r in rows_b} before = len(rows_c) rows_c = [r for r in rows_c if sha256_hex(norm_instruction(r["_base_instruction"])) not in b_hashes] overlap = before - len(rows_c) print(f"[overlap] dropped {overlap} stage_c rows sharing an instruction with stage_b") # top up tiers back to target after the overlap filter (fresh seeds, # checked against both B and the rows already kept for C) def c_jobs(tier, n, base_tag): pool = [i for i, f in enumerate(REGISTRY) if TIER_POOLS[tier](f)] rng = random.Random(MASTER_SEED + {"easy": 11, "standard": 22, "held_out": 33}[tier] + base_tag) return [(pool[rng.randrange(len(pool))], MASTER_SEED * 1000003 + (base_tag + 500) * 7919 + i, tier) for i in range(n)] topup_added = 0 for tier, target in tiers.items(): short = target - sum(1 for r in rows_c if r["tier"] == tier) rounds = 0 while short > 0 and rounds < 8: rounds += 1 seen_c = {sha256_hex(r["_base_instruction"] + "\x00" + r["tests"]) for r in rows_c} n = int(short * 1.9) + 25 extra_rows, _ = run_jobs(assemble_stage_c, c_jobs(tier, n, 900 + rounds * 100)) fresh = [] for r in extra_rows: h_b = sha256_hex(norm_instruction(r["_base_instruction"])) h_c = sha256_hex(r["_base_instruction"] + "\x00" + r["tests"]) if h_b in b_hashes or h_c in seen_c: continue seen_c.add(h_c) fresh.append(r) added = fresh[:short] rows_c.extend(added) topup_added += len(added) short = target - sum(1 for r in rows_c if r["tier"] == tier) print(f"[topup] tier={tier} round={rounds} added={len(added)} short_now={short}") print(f"[topup] total added={topup_added}") rng = random.Random(MASTER_SEED) rng.shuffle(rows_b) rng.shuffle(rows_c) for i, r in enumerate(rows_b, 1): r["id"] = f"stageb_{i:06d}" for i, r in enumerate(rows_c, 1): r["id"] = f"stagec_{i:06d}" # Re-verify a random sample with the TRUE subprocess harness # (aga_code.run_tests semantics) — the build gates use the fast # in-process runner; this sample proves they agree. vrng = random.Random(MASTER_SEED + 7) vs_b = vrng.sample(rows_b, min(200, len(rows_b))) vs_c = vrng.sample(rows_c, min(100, len(rows_c))) vb_ok = sum(1 for r in vs_b if run_tests(r["answer"], r["tests"])) vc_ok = sum(1 for r in vs_c if run_tests(r["_reference"], r["tests"])) reverify = {"stage_b": f"{vb_ok}/{len(vs_b)}", "stage_c": f"{vc_ok}/{len(vs_c)}"} print(f"[reverify] subprocess sample: B {reverify['stage_b']} C {reverify['stage_c']}") pre = "pilot_" if mode == "pilot" else "" pb = os.path.join(WORK, f"{pre}stage_b.jsonl") pc = os.path.join(WORK, f"{pre}stage_c.jsonl") pcv = os.path.join(WORK, f"{pre}stage_c_verify.jsonl") def write_jsonl(path, rows, fields): with open(path, "w") as f: for r in rows: f.write(json.dumps({k: r[k] for k in fields}) + "\n") write_jsonl(pb, rows_b, ["id", "instruction", "think", "critique", "revise", "answer", "tests", "family", "difficulty", "seed", "clean"]) write_jsonl(pc, rows_c, ["id", "instruction", "tests", "family", "difficulty", "tier", "mutation_score"]) write_jsonl(pcv, rows_c, ["id", "instruction", "tests", "family", "difficulty", "tier", "mutation_score", "_reference"]) # rename _reference -> reference_solution in verify file vrows = [] with open(pcv) as f: for line in f: r = json.loads(line) r["reference_solution"] = r.pop("_reference") vrows.append(r) with open(pcv, "w") as f: for r in vrows: f.write(json.dumps(r) + "\n") kinds = famdist(rows_b, "_kind") clean_n = sum(1 for r in rows_b if r["clean"]) manifest = { "name": "AGA-Code Stage B/C datasets", "version": "1.0.0" if mode == "full" else "0.2.0-pilot", "date": str(date.today()), "seed": MASTER_SEED, "held_out_families": sorted(HELD_OUT), "all_families": sorted(f.name for f in REGISTRY), "generator_sha256": { os.path.basename(p): sha256_file(os.path.join(WORK, p)) for p in ["framework.py", "families_a.py", "families_b.py", "families_c.py", "build.py"] if os.path.exists(os.path.join(WORK, p)) }, "stage_b": {"file": os.path.basename(pb), "rows": len(rows_b), "per_family": famdist(rows_b), "difficulty": famdist(rows_b, "difficulty"), "clean_examples": clean_n, "clean_fraction": round(clean_n / max(1, len(rows_b)), 3), "bug_kind_distribution": kinds, "sha256": sha256_file(pb), "build": log["stage_b"]}, "stage_c": {"file": os.path.basename(pc), "rows": len(rows_c), "shipped_per_tier": famdist(rows_c, "tier"), "per_family": famdist(rows_c), "difficulty": famdist(rows_c, "difficulty"), "per_tier": {t: log["stage_c"][t] for t in tiers}, "sha256": sha256_file(pc), "verify_file": os.path.basename(pcv), "verify_sha256": sha256_file(pcv)}, "gates": { "stage_b_answers_pass_tests": "100% (execution-verified at build)", "stage_b_buggy_drafts_fail": "100% of non-clean (failing assert observed)", "stage_c_tests_pass_reference": "100% (execution-verified)", "stage_c_mutation": f">= {MUTATION_COUNT_MIN} mutants/problem, score >= {MUTATION_MIN}", "cross_set_overlap_dropped": overlap, "cross_set_overlap_topped_up": topup_added, "subprocess_reverify_sample": reverify, }, "notes": [ "Tokenizer: build performs no model generation/decoding (pure " "subprocess execution harness); aga_code.py is v0.1.7 with the " "TokWrapper decoder fix — required for any future generation use.", "Stage C reference solutions are HELD OUT in the verify file only.", ], } mp = os.path.join(WORK, f"manifest_{tag}.json") with open(mp, "w") as f: json.dump(manifest, f, indent=2) print(f"[done] {pb}: {len(rows_b)} rows | {pc}: {len(rows_c)} rows") print(f"[done] B clean fraction: {manifest['stage_b']['clean_fraction']} " f"kinds: {kinds}") print(f"[done] B difficulty: {manifest['stage_b']['difficulty']}") print(f"[done] C difficulty: {manifest['stage_c']['difficulty']}") print(f"[done] manifest: {mp}") if __name__ == "__main__": main()