SACB / source /tools /gen_compounds.py
ilintar's picture
Add corpus source: base repos, task overlays, hidden tests, and the authoring tools
9368cc4 verified
Raw
History Blame Contribute Delete
5.64 kB
#!/usr/bin/env python3
"""Generate compound tasks by combining already-validated single defects.
Every single-defect task in the corpus has been through the builder, so its
fault is known findable and its tests known correct against the reference. A
compound is the union of several such tasks whose broken files are disjoint --
that disjointness is what guarantees no single edit repairs more than one, which
is the property the difficulty dial depends on.
Nothing is invented here: the break overlays and the tests are the ones already
validated, and only the instruction is composed.
"""
import argparse, itertools, json, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from make_tasks import CORPUS # noqa: E402
def read_tree(root: Path) -> dict:
if not root.is_dir():
return {}
return {str(p.relative_to(root)): p.read_text()
for p in sorted(root.rglob("*")) if p.is_file()}
def load_singles(repo: str):
"""Every task in `repo` that breaks exactly one file and is not compound."""
out = []
tasks_dir = CORPUS / repo / "tasks"
for task_dir in sorted(tasks_dir.glob("*")):
meta_path = task_dir / "task.json"
if not meta_path.is_file():
continue
meta = json.loads(meta_path.read_text())
if meta.get("compound"):
continue
broken = read_tree(task_dir / "break")
tests = read_tree(task_dir / "tests")
if len(broken) != 1 or not tests:
continue # compounds and malformed tasks are not ingredients
out.append({
"id": task_dir.name,
"files": broken,
"tests": tests,
"instruction": meta["instruction"],
"difficulty": meta.get("difficulty", 3),
})
return out
def compose_instruction(parts) -> str:
"""One triage ticket listing each symptom, renumbered."""
head = (f"{len(parts)} findings from this week's triage. They have separate "
f"causes and are not related to one another; all {len(parts)} need "
f"fixing.\n")
body = []
for n, part in enumerate(parts, 1):
# keep only the symptom prose, dropping each source task's own numbering
text = part["instruction"].strip()
text = "\n ".join(line.strip() for line in text.splitlines() if line.strip())
body.append(f"\n{n}. {text}")
return head + "\n".join(body)
def build(repo: str, lang: str, size: int, limit: int, prefix: str):
singles = load_singles(repo)
made, used_pairs = 0, set()
# Cap how often one defect is reused. Without this the generator anchors
# nearly every compound on whichever ingredient sorts first, which
# correlates the outcomes: one defect a model cannot fix would sink most of
# the corpus at once, and the resolved rate would measure that single bug
# rather than the breadth it is meant to.
max_uses = max(2, (limit * size) // max(len(singles), 1) + 1)
uses: dict = {}
for combo in itertools.combinations(singles, size):
if made >= limit:
break
touched = [set(c["files"]) for c in combo]
# disjoint files: no single edit can repair two of them
if any(a & b for a, b in itertools.combinations(touched, 2)):
continue
ids = tuple(sorted(c["id"] for c in combo))
if any(uses.get(i, 0) >= max_uses for i in ids):
continue
# avoid re-using the same pair of ingredients across many compounds
pairs = set(itertools.combinations(ids, 2))
if pairs & used_pairs:
continue
used_pairs |= pairs
for i in ids:
uses[i] = uses.get(i, 0) + 1
merged_files, merged_tests = {}, {}
for part in combo:
merged_files.update(part["files"])
for name, body in part["tests"].items():
key = name
if key in merged_tests and merged_tests[key] != body:
stem, dot, ext = name.partition(".")
key = f"{stem}_{part['id'].replace('-', '_')}{dot}{ext}"
merged_tests[key] = body
task_id = f"{prefix}-{made + 1:02d}"
tdir = CORPUS / repo / "tasks" / task_id
(tdir / "tests").mkdir(parents=True, exist_ok=True)
for rel, content in merged_files.items():
out = tdir / "break" / rel
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(content)
for name, body in merged_tests.items():
(tdir / "tests" / name).write_text(body)
(tdir / "task.json").write_text(json.dumps({
"lang": lang,
"category": "logic",
"difficulty": 5,
"compound": True,
"ingredients": list(ids),
"instruction": compose_instruction(combo),
}, indent=2) + "\n")
print(f" {task_id}: {' + '.join(ids)}")
made += 1
print(f"{made} compound task(s) for {repo}")
return made
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--size", type=int, default=3, help="defects per compound")
ap.add_argument("--limit", type=int, default=8, help="max compounds per repo")
args = ap.parse_args()
total = 0
for repo, lang, prefix in (("python/scheduler", "python", "triage"),
("typescript/router", "typescript", "review"),
("python/ledger", "python", "audit")):
total += build(repo, lang, args.size, args.limit, f"{prefix}{args.size}")
print(f"\n{total} total")