servicesToptal's picture
Update dataset (part 3)
fe4e0a1 verified
Raw History Blame Contribute Delete
11.2 kB
#!/usr/bin/env python3
"""Mutation probe runner — grades a tree with the SHIPPED grader.
Deliberately a sibling of calibrate.py rather than a flag on it: an in-flight
calibration owns .calib/calibration.json, and a mutation matrix must not write
into the file a verdict cites. Same weights (read out of tasks.py), same flat
blocker cap, same run_grading.sh, own state dirs, own logs, own JSON.
python3 mutprobe.py mut-arity [mut-...]
python3 mutprobe.py mut-lua --criteria B3_no_fabricated_record_on_status_change
"""
from __future__ import annotations
import argparse
import ast
import json
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
GRADER = Path(os.environ.get("CALIB_GRADER_DIR") or (HERE / "grader"))
CALIB = HERE / ".calib"
BASE_TREE = CALIB / "base"
OUT = CALIB / "mutation-probe.json"
# Nothing in this repository is regenerated in place by its own suite, so
# there is nothing to snapshot and put back after a grading.
MUTABLE: tuple[str, ...] = ()
def load_table():
tree = ast.parse((HERE / "tasks.py").read_text())
graders = cap = None
for node in tree.body:
if not isinstance(node, ast.Assign):
continue
for target in node.targets:
if not isinstance(target, ast.Name):
continue
if target.id == "GRADERS":
graders = [(t[0], t[1], t[2]) for t in ast.literal_eval(node.value)]
elif target.id == "BLOCKER_CAP":
cap = ast.literal_eval(node.value)
assert graders and cap is not None
total = sum(w for _n, w, _b in graders)
if abs(total - 1.0) > 1e-9:
raise SystemExit(f"weights sum to {total}, not 1.0")
return graders, cap
def _cargo_env() -> dict[str, str]:
"""The host's cargo directories, for a calibration that runs outside the image.
run_grading.sh defaults to the image's paths (/cargo, /hud/repotarget);
on a developer machine those do not exist and every criterion would come
back a GRADER FAULT — correctly, but uselessly. Asking the toolchain where
its registry is is the one place this differs from the image, and it changes
nothing about what is graded.
"""
out = {}
if not os.environ.get("CARGO_HOME"):
home = Path.home() / ".cargo"
if home.is_dir():
out["GRADER_CARGO_HOME"] = str(home)
return out
CARGO_ENV = _cargo_env()
def reward(results, graders, cap, faults=()):
"""The same arithmetic tasks.py does, faults included.
A criterion the grader could not judge is STRUCK FROM THE BLOCKER SET — the
grader broke, so it cannot cap the run; scoring a fault as a failed
criterion is what turned mut-timer's 0.860 into a 0.600 with a blocker
failure it never had. It does not earn its weight either: paying for an
unjudged criterion is a channel, and it paid run 8d578573 a free 0.12 (see
faultprobe.py for the arithmetic over this whole matrix).
"""
# G-5-prime: та же арифметика, что в tasks.py. results НЕ переписывается
# (гейт на base измерен зелёным и остаётся зелёным в отчёте) — он просто
# не зарабатывает, когда ни одна другая клетка не зелёная.
# G-5" (11.09): the rule of the ticket (law W-1) is green on an untouched
# checkout for the same reason the gate is, so it is paid on the same
# terms — only next to a green cell of the core.
_G5P_CONDITIONAL = tuple(n for n, _w, _b in graders
if n.startswith(("gate_", "rule_")))
_g5p_cells = [n for n, _w, _b in graders if n not in _G5P_CONDITIONAL and n in results]
if _g5p_cells and not any(results.get(n) for n in _g5p_cells):
results = dict(results, **{g: False for g in _G5P_CONDITIONAL})
faults = set(faults)
uncapped = sum(w for n, w, _b in graders if n not in faults and results.get(n))
failed = [n for n, _w, b in graders
if b and n not in faults and not results.get(n)]
# A blocker that was not measured is not a blocker that was passed. It is
# not reported as failed — that would be a phantom failure — but the ceiling
# stays on, because lifting it is worth up to the whole gap between the cap
# and 1.00 to a tree that would have failed the gate. Measured over every
# possible outcome vector in faultprobe.py: without this, breaking a gate
# fixture is worth +0.40.
unproven = [n for n, _w, b in graders if b and n in faults]
if not failed and not unproven:
return uncapped, uncapped, []
return max(0.0, min(uncapped, cap)), uncapped, failed
def measured_scale(results, graders, cap, faults=()):
"""(weight measured, reward over that weight) — reported, never the reward.
§5.3 of SOLVER-FORENSICS asks for this number, and it is the right number to
show a human re-reading a faulted trace. It is not the reward, because
renormalising pays for a broken fixture exactly when the unmeasured
criterion would have scored below the run's average — which is the criterion
an agent would pick. faultprobe.py measures how much, on every tree in the
matrix.
"""
faults = set(faults)
measured = sum(w for n, w, _b in graders if n not in faults)
if measured <= 0:
return 0.0, 0.0
final, _uncapped, _failed = reward(results, graders, cap, faults)
return measured, final / measured
def load_timeouts():
"""Per-criterion timeout from the same GRADERS table, handed to the grader.
The ladder is fitted to this budget, so grading locally against a different
one is grading a different ladder.
"""
tree = ast.parse((HERE / "tasks.py").read_text())
for node in tree.body:
if isinstance(node, ast.Assign) and any(
getattr(t, "id", None) == "GRADERS" for t in node.targets):
return {t[0]: t[4] for t in ast.literal_eval(node.value)}
raise SystemExit("could not read GRADERS out of tasks.py")
TIMEOUTS = load_timeouts()
def run_criterion(tree: Path, name: str, state: Path, log_dir: Path):
env = dict(os.environ)
env.update({
"REPO_DIR": str(tree),
"HARNESS_DIR": str(GRADER),
"GRADER_STATE_DIR": str(state),
"BASE_SRC": os.environ.get("BASE_SRC") or str(BASE_TREE),
"PYTHON_BIN": sys.executable,
**CARGO_ENV,
})
budget = TIMEOUTS.get(name, GATE_TIMEOUT)
started = time.time()
proc = subprocess.run(["bash", str(GRADER / "run_grading.sh"), name, str(budget)],
env=env, capture_output=True, text=True, timeout=budget + 300)
elapsed = time.time() - started
(log_dir / f"{name}.log").write_text(proc.stdout + "\n--- stderr ---\n" + proc.stderr)
if proc.returncode == 3:
return None, elapsed, proc.stdout # grader fault
return proc.returncode == 0, elapsed, proc.stdout
def load_gate() -> tuple[str, int]:
tree = ast.parse((HERE / "tasks.py").read_text())
name = budget = None
for node in tree.body:
if isinstance(node, ast.Assign):
for t in node.targets:
if getattr(t, "id", None) == "GATE":
name = ast.literal_eval(node.value)
elif getattr(t, "id", None) == "GATE_TIMEOUT":
budget = ast.literal_eval(node.value)
if not name or not budget:
raise SystemExit("could not read GATE/GATE_TIMEOUT out of tasks.py")
return name, budget
GATE, GATE_TIMEOUT = load_gate()
def grade(which: str, graders, cap, criteria, keep):
tree = CALIB / which
if not (tree / "Cargo.toml").exists():
raise SystemExit(f"no tree at {tree}")
state = CALIB / f"state-{which}"
if not keep:
shutil.rmtree(state, ignore_errors=True)
state.mkdir(parents=True, exist_ok=True)
log_dir = CALIB / f"logs-{which}"
log_dir.mkdir(parents=True, exist_ok=True)
snap = {r: (tree / r).read_bytes() for r in MUTABLE if (tree / r).exists()}
print(f"\n=== {which} ===", flush=True)
results, timings, faults = {}, {}, []
for name, weight, blocker in graders:
if criteria and name not in criteria:
continue
ok, elapsed, out = run_criterion(tree, name, state, log_dir)
verdict = "PASS" if ok else "FAIL"
if ok is None:
faults.append(name)
ok, verdict = False, "FAULT"
results[name] = ok
timings[name] = elapsed
print(f" {verdict:<5} {name:<46} w={weight:.2f} "
f"{'blocker' if blocker else ' '} {elapsed:6.1f}s", flush=True)
for line in out.splitlines():
stripped = line.strip()
if stripped.startswith(("PASS:", "FAIL:", "GRADER FAULT")):
print(f" {stripped[:200]}", flush=True)
# Law G-5: the gate is the last row of GRADERS and was graded in the loop
# above with everything else; there is no separate, weightless gate run.
gate_ok = results.get(GATE, True) if not criteria else True
for rel, data in snap.items():
f = tree / rel
if f.exists() and f.read_bytes() != data:
f.write_bytes(data)
final, uncapped, failed = reward(results, graders, cap, faults)
if not gate_ok:
print(" -> A GATE FAILED: the repository's own tests were rewritten or "
"left red; the total is capped and the gate's own weight is not earned",
flush=True)
print(f" -> uncapped {uncapped:.3f}, failed blockers {failed or 'none'}, "
f"gate {'PASS' if gate_ok else 'FAIL'}, "
f"reward {final:.3f}"
+ (f" ⚠ NOT A MEASUREMENT — grader faults: {faults} "
f"(counted as met, struck from the blockers)" if faults else ""), flush=True)
return {"tree": which, "results": results, "timings": timings, "uncapped": uncapped,
"reward": final, "failed_blockers": failed, "grader_faults": faults,
"gate": gate_ok, "partial": bool(criteria)}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("trees", nargs="+")
ap.add_argument("--criteria", default="")
ap.add_argument("--keep-state", action="store_true")
args = ap.parse_args()
graders, cap = load_table()
criteria = [c for c in args.criteria.split(",") if c]
report = [grade(t, graders, cap, criteria, args.keep_state) for t in args.trees]
previous = []
if OUT.exists():
try:
previous = json.loads(OUT.read_text())
except (ValueError, OSError):
previous = []
merged = {e["tree"]: e for e in previous if isinstance(e, dict) and "tree" in e}
for e in report:
if e["partial"] and e["tree"] in merged and not merged[e["tree"]]["partial"]:
merged[e["tree"]]["results"].update(e["results"])
continue
merged[e["tree"]] = e
OUT.write_text(json.dumps(sorted(merged.values(), key=lambda e: e["tree"]), indent=2) + "\n")
print(f"\nwritten to {OUT}")
if __name__ == "__main__":
main()