SACB / source /tools /build_corpus.py
ilintar's picture
Add corpus source: base repos, task overlays, hidden tests, and the authoring tools
9368cc4 verified
Raw
History Blame Contribute Delete
7.88 kB
#!/usr/bin/env python3
"""Build and validate the agentic corpus from on-disk task sources.
Layout -- one substantial base repository carries many tasks:
<lang>/<repo>/repo/ the base tree, in its CORRECT state
<lang>/<repo>/tasks/<id>/task.json metadata + instruction
<lang>/<repo>/tasks/<id>/break/ overlay that injects the defect
<lang>/<repo>/tasks/<id>/tests/ hidden tests, never in the agent's tree
<lang>/<repo>/tasks/<id>/gold/ optional; defaults to the base tree
The agent starts from base+break. The reference fix is the base itself, so a
task cannot ship with a "solution" that does not work. For add-a-feature tasks
the break overlay simply removes the implementation.
fail_to_pass / pass_to_pass are derived by running the tests twice, never
hand-written. That catches both ways a task can be quietly worthless: a defect
no test exercises, and a reference fix that does not itself pass.
"""
import argparse, json, shutil, sys, tempfile
from pathlib import Path
EVAL = Path(__file__).resolve().parents[2] / "examples" / "llama-eval"
sys.path.insert(0, str(EVAL))
from eval_sandbox import Sandbox # noqa: E402
from agentic_eval import LANGS, Runner, AgenticTask, materialise # 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() and "__pycache__" not in p.parts}
def load_tasks(corpus: Path):
"""Yield one record per task directory found under the corpus root."""
for repo_dir in sorted(p.parent for p in corpus.rglob("repo/.")):
base = read_tree(repo_dir / "repo")
if not base:
continue
for task_dir in sorted((repo_dir / "tasks").glob("*")):
if not (task_dir / "task.json").is_file():
continue
meta = json.loads((task_dir / "task.json").read_text())
break_overlay = read_tree(task_dir / "break")
gold_overlay = read_tree(task_dir / "gold")
# The task's tests/ directory *is* the tests root, so it keeps that
# prefix in the graded tree. Without it the files land beside the
# source and discovery has no start directory to look in. The
# package marker is added here rather than committed, so authoring
# a task never means remembering an empty file.
tests = {f"tests/{rel}": body
for rel, body in read_tree(task_dir / "tests").items()}
if tests:
tests.setdefault("tests/__init__.py", "")
problems = []
if not break_overlay:
problems.append("break/ is empty -- nothing is defective")
if not tests:
problems.append("tests/ is empty")
for rel in break_overlay:
if rel not in base and not meta.get("allow_new_files"):
problems.append(f"break/ adds {rel!r}, which is not in the base repo")
yield {
"task_id": meta.get("task_id", f"{repo_dir.name}-{task_dir.name}"),
"repo": repo_dir.name,
"lang": meta["lang"],
"category": meta["category"],
"difficulty": int(meta.get("difficulty", 3)),
"instruction": meta["instruction"].strip(),
"files": {**base, **break_overlay},
"gold": {**base, **gold_overlay},
"tests": tests,
}, problems
def sandbox_for(lang_name: str) -> Sandbox:
lang = LANGS[lang_name]
sbx = Sandbox(name=f"agentic-{lang_name}", packages=list(lang.packages),
provision=list(lang.provision),
address_space_limit=lang.address_space_limit)
sbx.ensure(quiet=True)
return sbx
def validate(rec: dict, runner: Runner, workroot: Path):
task = AgenticTask.from_record({**rec, "fail_to_pass": [], "pass_to_pass": []})
problems = []
def run(files, label):
dest = workroot / f"{task.task_id}-{label}"
shutil.rmtree(dest, ignore_errors=True)
materialise(files, dest)
materialise(task.tests, dest)
return runner.test(dest).get("tests", {})
base = run(task.files, "base")
gold = run(rec["gold"], "gold")
if not gold:
return ({**rec, "fail_to_pass": [], "pass_to_pass": [], "n_tests": 0},
["reference tree produced no test results at all"])
gold_fail = sorted(t for t, v in gold.items() if v != "pass")
if gold_fail:
problems.append(f"reference fix fails {len(gold_fail)} test(s): {gold_fail[:4]}")
f2p = sorted(t for t, v in gold.items() if v == "pass" and base.get(t) != "pass")
p2p = sorted(t for t, v in gold.items() if v == "pass" and base.get(t) == "pass")
if not f2p:
problems.append("no test separates the broken tree from the fix -- "
"the defect is not exercised")
# Regression guards matter because without them, deleting the offending code
# scores the same as repairing it. The exception is a defect that stops the
# package importing at all: then nothing passes beforehand, so there is
# genuinely nothing to preserve, and the fail_to_pass tests carry the whole
# behavioural check themselves.
baseline_passes = sum(1 for v in base.values() if v == "pass")
if not p2p and baseline_passes:
problems.append("no pass_to_pass tests -- deleting the feature would score "
"the same as fixing it")
elif not p2p:
print(" note: nothing passes at baseline (total breakage), so this "
"task has no regression guards")
rec = {**rec, "fail_to_pass": f2p, "pass_to_pass": p2p, "n_tests": len(gold)}
return rec, problems
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--corpus", default=str(Path(__file__).parent / "corpus"))
ap.add_argument("--out", default=str(Path(__file__).parent / "agentic-corpus.jsonl"))
ap.add_argument("--only", default=None)
args = ap.parse_args()
runners, records, failed = {}, [], []
workroot = Path(tempfile.mkdtemp(prefix="corpus-build-"))
try:
for rec, load_problems in load_tasks(Path(args.corpus)):
if args.only and args.only not in rec["task_id"]:
continue
if load_problems:
failed.append((rec["task_id"], "; ".join(load_problems)))
print(f" BAD {rec['task_id']}")
for p in load_problems:
print(f" ! {p}")
continue
lang = rec["lang"]
if lang not in runners:
runners[lang] = Runner(sandbox_for(lang), LANGS[lang])
rec, problems = validate(rec, runners[lang], workroot)
print(f" {'OK ' if not problems else 'BAD'} {rec['task_id']:<30} "
f"{rec['lang']:<11}{rec['category']:<8}d{rec['difficulty']} "
f"f2p={len(rec['fail_to_pass']):<3} p2p={len(rec['pass_to_pass']):<3} "
f"({rec.get('n_tests', 0)} tests)")
for p in problems:
print(f" ! {p}")
if problems:
failed.append((rec["task_id"], "; ".join(problems)))
else:
records.append(rec)
finally:
shutil.rmtree(workroot, ignore_errors=True)
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
with out.open("w") as fh:
for rec in records:
fh.write(json.dumps(rec) + "\n")
print(f"\n{len(records)} valid task(s) -> {out}")
if failed:
print(f"{len(failed)} rejected")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())