"""Build kreatix-code-debug: buggy Python code, a real failure, and a fix that is verified by execution. Every row starts from a verified kreatix-code-hard problem (reference == brute-force oracle). One realistic bug is injected into the reference by editing the exact source span (codegen/mutate.py). A row is kept only if the buggy code gives a wrong result (or crashes) on at least one test input; the fix restores the reference, which passes all of them. The failing input, expected and actual output, and any traceback shown in a row come from running the buggy code. Three request styles: a reported failure, no hint ("find the bug"), and a pasted traceback. Splits: problems from the families in codegen.base.HELDOUT appear only in test. Each buggy program appears at most --cap-program times and each family at most --cap-family times per split. python generator/build_debug.py --candidates 16000 --workers 8 """ from __future__ import annotations import argparse import json import os import random import re import sys from collections import Counter import hashlib HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) sys.path.insert(0, os.path.join(os.path.dirname(ROOT), "kreatix-code-hard", "generator")) from codegen import FAMILIES, problem_id, split_of, verify # noqa: E402 from codegen.select import generate, select, write # noqa: E402 from codegen.base import fmt_call # noqa: E402 from codegen.mutate import apply, line_text, pick_mutations # noqa: E402 from codegen.runner import RunError, run_calls, run_script # noqa: E402 GEN, VERSION = "kreatix-code-debug", "0.1.0" T = { "en": { "ask_fail": ["This is supposed to solve the task below, but `{call}` returns `{got}` instead of `{exp}`. Find " "and fix the bug.", "My solution gives the wrong answer: `{call}` should be `{exp}`, I get `{got}`. " "What's wrong?"], "ask_nohint": ["Here is my solution. Something is wrong but I can't see it. Can you find the bug?", "Please review this solution: there is a bug somewhere. Find it, show an input that fails, and " "fix it."], "ask_tb": ["Running `{call}` crashes with this traceback. What's going on and how do I fix it?", "I get an exception for `{call}`:"], "task": "Task:", "bug": "**Bug:** line {ln}", "fix": "**Fix:**", "full": "**Corrected code:**", "after": "With the fix, `{call}` returns `{exp}` (before: `{got}`), and the code gives the expected result on " "all {n} test inputs, including the edge cases.", "counter": "A failing input: `{call}` should return `{exp}`, but this code returns `{got}`.", "ask_crash": ["This is supposed to solve the task below, but `{call}` raises `{got}` instead of returning " "`{exp}`. Find and fix the bug.", "My solution crashes: `{call}` should return `{exp}`, but it raises `{got}`. What is wrong?"], "ask_crash_seq": ["This is supposed to solve the task below, but running `{call}` raises `{got}`. Find and fix " "the bug."], "counter_crash": "A failing input: `{call}` should return `{exp}`, but this code raises `{got}`.", "counter_crash_seq": "A failing input: running `{call}` raises `{got}`.", "after_crash": "With the fix, `{call}` returns `{exp}` instead of raising an error, and the code gives the " "expected result on all {n} test inputs, including the edge cases.", "after_crash_seq": "With the fix, `{call}` runs without errors, and the code gives the expected result on all " "{n} test inputs, including the edge cases.", "think_crash": "Reproduce: `{call}` raises `{got}`" + "{exp_part}.", "exp_part": ", expected `{exp}`", "crash": "The crash comes from line {ln}: on this input the bug drives the code into an invalid operation " "(`{err}`).", "think": ["Reproduce: `{call}` gives `{got}`, expected `{exp}`.", "Look for the line whose behaviour differs on " "this input: line {ln}, `{line}`.", "Cause: {cause}", "Fix that line and re-check every test input."], "why": { "cmp_flip": "The comparison uses `{new}` but needs `{old}`. They only differ when both sides are equal, and " "that boundary case is exactly what the failing input hits.", "arith_flip": "It uses `{new}` where it needs `{old}`, so the value moves in the wrong direction.", "bool_flip": "The two conditions are joined with `{new_s}`, but the logic needs `{old_s}` ({why_bool}).", "minmax_swap": "It calls `{new}()` where it needs `{old}()`, so it keeps the wrong extreme.", "bisect_swap": "It uses `{new}` instead of `{old}`. The two only differ for equal values, and here that " "decides how ties are handled.", "off_by_one": "It is off by one: `{new}` should be `{old}`, so the loop {miss} one position.", "index_swap": "It reads index `{new}` but needs `{old}` ({which} element).", "init_change": "The value starts at `{new}` instead of `{old}`, so every later step builds on the wrong base.", "drop_stmt": "A statement is missing from the loop: `{stmt}`. Without it, the state it updates never changes " "while the loop runs.", "neg_drop": "The minus sign in `{old}` is gone, which reverses the order (or direction) the code relies on.", }, "arith_crash": "It uses `{new}` where it needs `{old}`; with these operand types `{new}` is not even defined, " "so Python raises an error instead of computing a value.", "both": "both conditions must hold", "either": "either condition is enough", "misses": "skips", "visits": "visits an extra", "last": "the last", "first": "the first", "missing_at": "**Bug:** a missing line in the loop (it belongs after line {ln})", }, "fi": { "ask_fail": ["Tämän pitäisi ratkaista alla oleva tehtävä, mutta `{call}` palauttaa `{got}` eikä `{exp}`. Etsi ja " "korjaa virhe.", "Ratkaisuni antaa väärän vastauksen: `{call}` pitäisi olla `{exp}`, saan `{got}`. " "Mikä on vialla?"], "ask_nohint": ["Tässä ratkaisuni. Jokin on vialla, mutta en näe mikä. Löydätkö virheen?", "Tarkista tämä ratkaisu: siinä on virhe jossain. Etsi se, näytä syöte, joka epäonnistuu, ja " "korjaa se."], "ask_tb": ["Kun ajan `{call}`, ohjelma kaatuu tällä virheilmoituksella. Mistä on kyse ja miten korjaan sen?", "Saan poikkeuksen kutsulla `{call}`:"], "task": "Tehtävä:", "bug": "**Virhe:** rivi {ln}", "fix": "**Korjaus:**", "full": "**Korjattu koodi:**", "after": "Korjauksen jälkeen `{call}` palauttaa `{exp}` (ennen: `{got}`), ja koodi antaa odotetun tuloksen kaikilla " "{n} testisyötteellä, myös reunatapauksissa.", "counter": "Epäonnistuva syöte: `{call}` pitäisi palauttaa `{exp}`, mutta tämä koodi palauttaa `{got}`.", "ask_crash": ["Tämän pitäisi ratkaista alla oleva tehtävä, mutta `{call}` nostaa poikkeuksen `{got}` eikä " "palauta `{exp}`. Etsi ja korjaa virhe.", "Ratkaisuni kaatuu: `{call}` pitäisi palauttaa `{exp}`, mutta se nostaa poikkeuksen `{got}`. Mikä " "on vialla?"], "ask_crash_seq": ["Tämän pitäisi ratkaista alla oleva tehtävä, mutta `{call}` nostaa poikkeuksen `{got}`. Etsi " "ja korjaa virhe."], "counter_crash": "Epäonnistuva syöte: `{call}` pitäisi palauttaa `{exp}`, mutta tämä koodi nostaa poikkeuksen " "`{got}`.", "counter_crash_seq": "Epäonnistuva syöte: `{call}` nostaa poikkeuksen `{got}`.", "after_crash": "Korjauksen jälkeen `{call}` palauttaa `{exp}` eikä nosta virhettä, ja koodi antaa odotetun " "tuloksen kaikilla {n} testisyötteellä, myös reunatapauksissa.", "after_crash_seq": "Korjauksen jälkeen `{call}` toimii ilman virheitä, ja koodi antaa odotetun tuloksen kaikilla " "{n} testisyötteellä, myös reunatapauksissa.", "think_crash": "Toista: `{call}` nostaa poikkeuksen `{got}`" + "{exp_part}.", "exp_part": ", odotettu `{exp}`", "crash": "Kaatuminen tulee riviltä {ln}: tällä syötteellä virhe vie koodin virheelliseen operaatioon (`{err}`).", "think": ["Toista: `{call}` antaa `{got}`, odotettu `{exp}`.", "Etsi rivi, jonka toiminta poikkeaa tällä " "syötteellä: rivi {ln}, `{line}`.", "Syy: {cause}", "Korjaa rivi ja tarkista kaikki testisyötteet."], "why": { "cmp_flip": "Vertailu käyttää operaattoria `{new}`, mutta tarvitaan `{old}`. Ne eroavat vain, kun molemmat " "puolet ovat yhtä suuret, ja juuri tähän rajatapaukseen epäonnistuva syöte osuu.", "arith_flip": "Siinä on `{new}`, vaikka tarvitaan `{old}`, joten arvo muuttuu väärään suuntaan.", "bool_flip": "Ehdot on yhdistetty sanalla `{new_s}`, mutta logiikka vaatii `{old_s}` ({why_bool}).", "minmax_swap": "Siinä kutsutaan `{new}()`, vaikka tarvitaan `{old}()`, joten se pitää väärän ääriarvon.", "bisect_swap": "Siinä on `{new}` eikä `{old}`. Ne eroavat vain yhtä suurilla arvoilla, ja tässä se ratkaisee " "tasatilanteiden käsittelyn.", "off_by_one": "Siinä on yhden virhe: `{new}` pitäisi olla `{old}`, joten silmukka {miss} yhden kohdan.", "index_swap": "Siinä luetaan indeksi `{new}`, mutta tarvitaan `{old}` ({which} alkio).", "init_change": "Arvo alustetaan arvoon `{new}` eikä `{old}`, joten jokainen myöhempi askel rakentuu väärälle " "pohjalle.", "drop_stmt": "Silmukasta puuttuu lause: `{stmt}`. Ilman sitä tila, jota se päivittää, ei muutu silmukan " "aikana.", "neg_drop": "Lausekkeesta `{old}` puuttuu miinusmerkki, mikä kääntää järjestyksen (tai suunnan), johon koodi " "luottaa.", }, "arith_crash": "Siinä on `{new}`, vaikka tarvitaan `{old}`; näillä operandityypeillä `{new}` ei ole edes " "määritelty, joten Python nostaa virheen eikä laske arvoa.", "both": "molempien ehtojen on oltava tosia", "either": "kumpi tahansa ehto riittää", "misses": "ohittaa", "visits": "käy ylimääräisessä", "last": "viimeinen", "first": "ensimmäinen", "missing_at": "**Virhe:** silmukasta puuttuu rivi (se kuuluu rivin {ln} jälkeen)", }, } def show(v): return repr(v) def describe_failure(p, call, got): """Readable call text and the observed result for function or class problems.""" exp = p.results[json.dumps(call)] if p.kind == "function": return fmt_call(p.entry, call), exp, got ops, outs = call["ops"], (got if isinstance(got, list) else None) idx = len(ops) - 1 if outs is not None: for i, (a, b) in enumerate(zip(exp, outs)): if a != b: idx = i break seq = [f"obj = {p.entry}(" + ", ".join(repr(a) for a in call["init"]) + ")"] seq += [f"obj.{op[0]}(" + ", ".join(repr(a) for a in op[1:]) + ")" for op in ops[:idx + 1]] shown = "; ".join(seq) g = outs[idx] if outs is not None else got return shown, exp[idx], g def traceback_for(p, bug, call): if p.kind == "function": script = bug + f"\n\n{fmt_call(p.entry, call)}\n" else: lines = [f"obj = {p.entry}(" + ", ".join(repr(a) for a in call["init"]) + ")"] lines += [f"obj.{op[0]}(" + ", ".join(repr(a) for a in op[1:]) + ")" for op in call["ops"]] script = bug + "\n\n" + "\n".join(lines) + "\n" code, out = run_script(script, timeout=15) if code == 0 or "Traceback" not in out: return None tb = out[out.index("Traceback"):].strip() return re.sub(r'File "[^"]*main\.py"', 'File "solution.py"', tb) # line numbers match the code shown def make_rows(args): seed, n, langs = args rng = random.Random(seed) names, weights = zip(*[(k, w) for k, (f, w) in FAMILIES.items()]) rows, drops = [], Counter() while len(rows) < n: fam = rng.choices(names, weights)[0] lang = rng.choices(list(langs), list(langs.values()))[0] p = FAMILIES[fam][0](rng, lang) ok, _ = verify(p) if not ok: drops["unverified problem"] += 1 continue calls = p.small + p.edge made = False for m in pick_mutations(p.solution, rng, 6): bug = apply(p.solution, m) try: compile(bug, "solution.py", "exec") res, _ = run_calls(bug, p.entry, calls, p.kind, timeout=10) except (SyntaxError, RunError): drops["mutant does not run"] += 1 continue fails = [(c, r) for c, r in zip(calls, res) if r.get("ok", None) != p.results[json.dumps(c)] or "err" in r] if not fails: drops["mutant passes every test"] += 1 continue fails.sort(key=lambda cr: len(json.dumps(cr[0]))) call, r = fails[0] crashed = "err" in r got_raw = r.get("ok") if not crashed else r["err"] mode = "traceback" if crashed and rng.random() < 0.7 else rng.choices(["fail", "nohint"], [0.65, 0.35])[0] tb = traceback_for(p, bug, call) if mode == "traceback" else None if mode == "traceback" and not tb: mode = "fail" row = render(p, m, bug, call, got_raw, crashed, mode, tb, len(calls), lang, rng) norm = bug.replace(p.entry, "ENTRY") row["meta"].update({"problem_id": problem_id(p), "split": split_of(p), "program_id": hashlib.md5(norm.encode()).hexdigest()[:12]}) rows.append(row) made = True break if not made: drops[f"{fam}: no failing mutant"] += 1 return rows, drops def render(p, m, bug, call, got_raw, crashed, mode, tb, n_tests, lang, rng): t = T[lang] call_s, exp, got = describe_failure(p, call, got_raw) got_s = got if crashed else show(got) exp_s = show(exp) task = p.statement.split("\n\n", 1)[-1] code_block = f"```python\n{bug.rstrip()}\n```" seq_crash = crashed and p.kind == "class" if mode == "fail" and crashed: ask = rng.choice(t["ask_crash_seq"] if seq_crash else t["ask_crash"]) user = ask.format(call=call_s, got=got_s, exp=exp_s) + f"\n\n{t['task']} {task}\n\n{code_block}" elif mode == "fail": user = rng.choice(t["ask_fail"]).format(call=call_s, got=got_s, exp=exp_s) + f"\n\n{t['task']} {task}\n\n{code_block}" elif mode == "nohint": user = rng.choice(t["ask_nohint"]) + f"\n\n{t['task']} {task}\n\n{code_block}" else: user = rng.choice(t["ask_tb"]).format(call=call_s) + f"\n\n```\n{tb}\n```\n\n{code_block}" ln = m.line old_line = line_text(p.solution, ln) if m.kind == "drop_stmt": shown_line, fixed_block = None, "\n".join(p.solution.splitlines()[max(0, ln - 2):ln]) else: shown_line = line_text(bug, ln) fixed_block = old_line fill = {"old": m.old.strip(), "new": m.new.strip(), "old_s": m.old.strip(), "new_s": m.new.strip(), "stmt": m.detail.get("stmt", ""), "why_bool": t["both"] if m.old.strip() == "and" else t["either"], "miss": t["misses"] if m.kind == "off_by_one" and _shrinks(m) else t["visits"], "which": t["last"] if m.old.strip() == "-1" else t["first"]} cause = t["why"][m.kind].format(**fill) if crashed and m.kind == "arith_flip" and str(got_raw).startswith("TypeError"): cause = t["arith_crash"].format(**fill) out = [] if rng.random() < 0.6: th = [s.format(call=call_s, got=got_s, exp=exp_s, ln=ln, line=(shown_line or old_line).strip(), cause=cause) for s in t["think"]] if crashed: th[0] = t["think_crash"].format(call=call_s, got=got_s, exp_part="" if seq_crash else t["exp_part"].format(exp=exp_s)) out.append("\n" + "\n".join(f"- {s}" for s in th) + "\n") if mode == "nohint": key = ("counter_crash_seq" if seq_crash else "counter_crash") if crashed else "counter" out.append(t[key].format(call=call_s, got=got_s, exp=exp_s)) if mode == "traceback": out.append(t["crash"].format(ln=ln, err=got_raw.split(":")[0])) if shown_line is not None: out.append(t["bug"].format(ln=ln) + f"\n```python\n{shown_line.rstrip()}\n```\n{cause}") else: out.append(t["missing_at"].format(ln=ln - 1) + f"\n{cause}") out.append(t["fix"] + f"\n```python\n{fixed_block.rstrip()}\n```") out.append(t["full"] + f"\n```python\n{p.solution.rstrip()}\n```") key = ("after_crash_seq" if seq_crash else "after_crash") if crashed else "after" out.append(t[key].format(call=call_s, exp=exp_s, got=got_s, n=n_tests)) return {"messages": [{"role": "user", "content": user}, {"role": "assistant", "content": "\n\n".join(out)}], "meta": {"kind": f"code.debug.{m.kind}.{p.family}", "lang": lang, "generator": GEN, "version": VERSION, "mode": mode, "bug_line": ln, "entry": p.entry, "checked_by": f"buggy code fails on {json.dumps(call)[:60]}...; fix == verified reference " f"(oracle-checked on {n_tests} inputs)"}} def _shrinks(m): try: return int(m.new) < int(m.old) except ValueError: return len(m.new) < len(m.old) def main(): try: sys.stdout.reconfigure(encoding="utf-8") except AttributeError: pass ap = argparse.ArgumentParser() ap.add_argument("--candidates", type=int, default=16000) ap.add_argument("--cap-program", type=int, default=2) ap.add_argument("--cap-family", type=int, default=80) ap.add_argument("--test-cap-family", type=int, default=100) ap.add_argument("--workers", type=int, default=4) ap.add_argument("--langs", default="en=0.7,fi=0.3") ap.add_argument("--out", default=os.path.join(ROOT, "data")) a = ap.parse_args() langs = {k: float(v) for k, v in (p.split("=") for p in a.langs.split(","))} rows, drops = generate(make_rows, a.candidates, a.workers, langs, 3_000_000) out, sel = select(rows, lambda r: r["meta"]["program_id"], lambda r: r["meta"]["kind"].split(".")[3], {"train": (a.cap_program, a.cap_family, 10**9), "test": (a.cap_program, a.test_cap_family, 10**9)}) for split in ("test", "train"): rs = out[split] write(a.out, "codedebug", split, rs) print(f"{split}: {len(rs):,} rows, {len({r['meta']['program_id'] for r in rs}):,} distinct buggy programs from " f"{len({r['meta']['problem_id'] for r in rs})} solutions; langs {dict(Counter(r['meta']['lang'] for r in rs))}", flush=True) print(f" bug kinds {dict(Counter(r['meta']['kind'].split('.')[2] for r in rs).most_common())}", flush=True) print(f" modes {dict(Counter(r['meta']['mode'] for r in rs))}", flush=True) print(f" families {dict(Counter(r['meta']['kind'].split('.')[3] for r in rs).most_common())}", flush=True) print(f"candidates {len(rows):,}; generation drops {dict(drops.most_common(6))}; selection {dict(sel)}", flush=True) if __name__ == "__main__": main()