# Copyright (c) 2026 CLSA contributors # SPDX-License-Identifier: MIT """Load, validate and audit PreAct-Bench without trusting the builder.""" from __future__ import annotations import json import random from collections import Counter, defaultdict import jsonschema from clsa.envs.sandbox import SandboxEnv from clsa.envs.tasks import make_tasks from clsa.util import DATA, ROOT, load_config, read_jsonl BENCH_DIR = DATA / "preact_bench" SCHEMA_PATH = ROOT / "schemas" / "decision_point.schema.json" SPLITS = ("train", "calib", "test", "heldout") N_PER_FAMILY = int(load_config("bench").get("n_per_family", 20)) def schema() -> dict: with open(SCHEMA_PATH, "r", encoding="utf-8") as fh: return json.load(fh) _VALIDATOR = None def validator(): """A cached validator: rebuilding jsonschema state per item is ~50x slower.""" global _VALIDATOR if _VALIDATOR is None: sch = schema() cls = jsonschema.validators.validator_for(sch) cls.check_schema(sch) _VALIDATOR = cls(sch) return _VALIDATOR def load_preact_bench(split: str | None = None) -> list[dict]: """One-line load. split in {train, calib, test, heldout} or None for all.""" if split is None: return read_jsonl(BENCH_DIR / "all.jsonl") return read_jsonl(BENCH_DIR / "data" / f"{split}.jsonl") def validate_items(items: list[dict]) -> list[str]: v = validator() errors: list[str] = [] for it in items: for exc in v.iter_errors(it): errors.append(f"{it.get('item_id', '?')}: {exc.message}") break return errors _TASK_CACHE: dict[int, dict] = {} def task_index(seed: int) -> dict: if seed not in _TASK_CACHE: _TASK_CACHE[seed] = {t["task_id"]: t for t in make_tasks(seed=seed, n_per_family=N_PER_FAMILY)} return _TASK_CACHE[seed] def verify_fork(item: dict, tasks: dict | None = None) -> bool: """Rebuild the state from the replay prefix and reproduce the stored label.""" tasks = tasks or task_index(int(item["replay"]["task_seed"])) task = tasks[item["task_id"]] env = SandboxEnv(task, seed=item["replay"]["task_seed"], max_steps=int(task["max_steps"])) for act in item["replay"]["prefix"]: env.step(act) out = env.fork(item["act"]) stored = item["fork"]["do_a"] return ( out["state_digest"] == stored["state_digest"] and abs(out["harm"] - stored["harm"]) < 1e-9 and bool(out["irreversible_harm"]) == bool(stored["irreversible_harm"]) and bool(out["success"]) == bool(stored["success"]) ) def stratification_report(items: list[dict]) -> dict: strat: dict[str, Counter] = defaultdict(Counter) for it in items: lab = it["labels"] exposure = "exposed" if lab["exposed"] else "unexposed" if lab["committed"]: commitment = "commit_unsafe" elif lab["executed"]: commitment = "exec_safe" else: commitment = "candidate_not_executed" strat[it["split"]][f"{exposure}|{commitment}"] += 1 return {k: dict(v) for k, v in strat.items()} def main() -> None: # pragma: no cover - audit CLI items = load_preact_bench() print(f"items: {len(items)}") print("split counts:", dict(Counter(it["split"] for it in items))) print("family counts:", dict(Counter(it["family"] for it in items))) print("risk classes:", dict(Counter(it["risk_class"] for it in items))) errors = validate_items(items) print(f"schema errors: {len(errors)}") for e in errors[:10]: print(" ", e) strat = stratification_report(items) for split, counts in strat.items(): print(split, dict(sorted(counts.items()))) rng = random.Random(0) sample = rng.sample(items, min(40, len(items))) ok = sum(verify_fork(it) for it in sample) print(f"fork replay reproduced {ok}/{len(sample)} sampled labels") if errors or ok != len(sample): raise SystemExit(1) if __name__ == "__main__": # pragma: no cover main()