practice / tools /selftest.py
birgermoell's picture
Add Practice generators, indices, verification and documentation
2983a9c verified
Raw History Blame Contribute Delete
4.67 kB
#!/usr/bin/env python3
"""Self-test an environment: python3 tools/selftest.py <env_dir_name> [seeds]
For every seed and difficulty:
1. generation is deterministic
2. the standalone oracle, run on the task files alone, scores exactly 1.0
3. no answer, an empty object and a non-object all score 0
4. changing any single checked value makes that check fail (so every check has teeth)
5. the hidden checks are not in the task files, and every top-level answer key is named in the instruction
"""
import copy, importlib, json, os, subprocess, sys, tempfile
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from practice import verify
def load_validators(env_dir):
p = os.path.join(ROOT, "envs", env_dir, "validators.py")
if not os.path.exists(p): return None
import importlib.util
spec = importlib.util.spec_from_file_location("validators_" + env_dir, p)
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m); return m
def set_path(obj, path, value):
parts = path.split("."); cur = obj
for p in parts[:-1]: cur = cur[int(p)] if isinstance(cur, list) else cur[p]
last = parts[-1]
if isinstance(cur, list): cur[int(last)] = value
else: cur[last] = value
def mutate(chk, got):
t = chk["type"]
if t == "int": return [got + 1, got - 1, str(got), None]
if t == "number": return [got + 3 * chk["abs_tol"] + 1e-6, got - 3 * chk["abs_tol"] - 1e-6, str(got), None, True]
if t == "str": return [got + "x", "", None, 0]
if t == "bool": return [not got, None, int(got), str(got).lower()]
if t == "list": return [got[:-1], got + got[-1:], list(reversed(got)) if len(set(map(str, got))) > 1 else got + ["zz"], None, "x"]
if t == "set": return [got[:-1] if got else ["zz"], got + ["zz"], got + got[:1] if got else ["zz", "zy"], None]
return []
def run(env_dir, seeds):
gen = importlib.import_module("envs.%s.gen" % env_dir)
validators = load_validators(env_dir)
oracle = os.path.join(ROOT, "envs", env_dir, "oracle.py")
n = fails = 0
def fail(task, msg):
print("FAIL %s: %s" % (task.id, msg)); return 1
for d in (1, 2, 3):
for seed in seeds:
t = gen.generate(seed, d); t2 = gen.generate(seed, d); n += 1
if (t.files, t.checks, t.instruction) != (t2.files, t2.checks, t2.instruction): fails += fail(t, "not deterministic")
blob = "\n".join(t.files.values())
if "checks" in t.files or any(k.endswith("checks.json") for k in t.files): fails += fail(t, "checks leaked into files")
for c in t.checks:
top = c["path"].split(".")[0] if "path" in c else None
if top and ("`%s`" % top) not in t.instruction: fails += fail(t, "answer key `%s` is not named in the instruction" % top)
if not t.checks: fails += fail(t, "no checks")
with tempfile.TemporaryDirectory() as tmp:
for rel, text in t.files.items():
p = os.path.join(tmp, rel); os.makedirs(os.path.dirname(p), exist_ok=True)
open(p, "w").write(text)
r = subprocess.run([sys.executable, "-I", oracle], cwd=tmp, capture_output=True, text=True, timeout=120)
if r.returncode != 0 or not os.path.exists(os.path.join(tmp, "answer.json")):
fails += fail(t, "oracle crashed: " + r.stderr[-400:]); continue
ans = json.load(open(os.path.join(tmp, "answer.json")))
score, details = verify.grade(ans, t.checks, validators)
if score != 1.0:
bad = [x["check"] for x in details if x["score"] != 1.0][:4]
fails += fail(t, "oracle scored %s; failing checks %s" % (score, bad)); continue
for junk in (None, {}, [], "x", 3):
if verify.grade(junk, t.checks, validators)[0] != 0.0: fails += fail(t, "junk answer %r scored above 0" % (junk,))
for i, c in enumerate(t.checks):
if c["type"] == "custom": continue
got = verify.lookup(ans, c["path"])
for m in mutate(c, c["value"] if c["type"] in ("list", "set") else got):
a2 = copy.deepcopy(ans); set_path(a2, c["path"], m)
if verify.run_check(a2, c, validators) != 0.0:
fails += fail(t, "check %s still passes with %r" % (c["path"], m)); break
print("%s: %d tasks tested, %d failures" % (env_dir, n, fails))
return fails
if __name__ == "__main__":
seeds = range(int(sys.argv[2])) if len(sys.argv) > 2 else range(40)
sys.exit(1 if run(sys.argv[1], seeds) else 0)