"""Protocol loading, locking and realization guards for protocol_bench. The lock (configs/protocol_bench.lock.json + .sha256) records the protocol text, the code (ml_porosity/**/*.py, the bench scripts, pyproject.toml), the environment, every hash-listed input, the protocol_p2r artifacts that S2/S4 read, and the nominal generator fingerprints of two realizations. Main realizations 8–15 are refused unless the lock exists and matches; dev realizations 900–905 never need the lock; the protocol_p2 realizations 0–7 are always refused. """ from __future__ import annotations import hashlib import json from datetime import datetime, timezone from pathlib import Path import yaml from ml_porosity.f3.protocol import digest, environment from ml_porosity.paths import REPO_ROOT, outputs_dir __all__ = ["CONFIG", "LOCK", "check_rids", "current_stamp", "dev_stamp", "fingerprint", "freeze", "load_protocol", "protocol_p2", "protocol_p2r", "generator_config"] CONFIG = REPO_ROOT / "configs/protocol_bench.yaml" LOCK = REPO_ROOT / "configs/protocol_bench.lock.json" SCRIPTS = ("scripts/34_run_bench.py", "scripts/run_bench.sh") RESULT_DIRS = ("s1", "s2", "s3", "s4", "s8", "summary") def load_protocol(check_inputs: bool = True) -> dict: p = yaml.safe_load(CONFIG.read_text(encoding="utf-8")) if check_inputs: for k, v in p["inputs"].items(): f = REPO_ROOT / v["path"] if not f.exists(): raise FileNotFoundError(f"protocol_bench input {k} missing: {v['path']} (sync outputs/ first)") h = digest(f, text=f.suffix in (".yaml", ".json")) if v.get("sha256") not in (None, "TBD") and h != v["sha256"]: raise RuntimeError(f"{v['path']} differs from the hash recorded in protocol_bench ({h[:12]} ≠ {v['sha256'][:12]})") from ml_porosity.data.synth_d2 import normalize_misspec, preset_misspec cfg = generator_config(p) for name, spec in (p.get("calibration", {}).get("chosen") or {}).items(): if normalize_misspec(spec) != normalize_misspec(preset_misspec(cfg, name)): raise RuntimeError(f"preset {name} in {p['inputs']['d2_config']['path']} differs from calibration.chosen of protocol_bench") return p def generator_config(p: dict) -> dict: return yaml.safe_load((REPO_ROOT / p["inputs"]["d2_config"]["path"]).read_text(encoding="utf-8")) def protocol_p2(p: dict) -> dict: """protocol_p2: source of the registration, training and metric blocks (as scripts 14/15 use it).""" return yaml.safe_load((REPO_ROOT / p["inputs"]["protocol_p2"]["path"]).read_text(encoding="utf-8")) def protocol_p2r(p: dict) -> dict: return yaml.safe_load((REPO_ROOT / p["inputs"]["protocol_p2r"]["path"]).read_text(encoding="utf-8")) def code_files() -> list[Path]: paths = sorted((REPO_ROOT / "ml_porosity").rglob("*.py")) paths += [REPO_ROOT / s for s in SCRIPTS if (REPO_ROOT / s).exists()] return paths + [REPO_ROOT / "pyproject.toml"] def source_hash() -> str: h = hashlib.sha256() for f in code_files(): h.update(f.relative_to(REPO_ROOT).as_posix().encode() + b"\0") h.update(f.read_bytes().replace(b"\r\n", b"\n") + b"\0") return h.hexdigest() def p2r_reference_files(p: dict) -> list[Path]: """protocol_p2r artifacts the benchmark reads: SMC particles and phase of the S4 cells, the per-regime runs.csv (S1 grid, S2 nominal reference, S3 join) and sigma_post.csv.""" root = outputs_dir() / "p2r" ref = p["reference"]["p2r"] files = [root / "summary" / "sigma_post.csv"] files += [root / "train" / reg / "runs.csv" for reg in ref["regimes"]] for cell in p["studies"]["S4"]["cells"]: for N in p["studies"]["S4"]["n_train"]: for rid in p["grid"]["realizations"]: tag = f"r{rid}_c{cell['c']:g}_n{N}_s{p['registration']['reg_seed']}" files += [root / "posterior" / cell["regime"] / f"{tag}_particles.npz", root / "posterior" / cell["regime"] / f"{tag}_phase.json"] return files def portable(path: Path) -> str: path = path.resolve() for prefix, base in (("outputs", outputs_dir()), ("repo", REPO_ROOT)): try: return f"{prefix}:{path.relative_to(base.resolve()).as_posix()}" except ValueError: continue raise ValueError(f"input outside the repository and outputs roots: {path}") def nominal_fingerprints(p: dict) -> dict: """Recompute the nominal generator fingerprints of the realizations listed in the protocol and compare them with tests/data/d2_fingerprints.json (recorded before the misspecification parameters were added).""" from ml_porosity.benchmark.data import fingerprint_realization, load_inputs inp = load_inputs(p) stored = json.loads((REPO_ROOT / p["inputs"]["fingerprints"]["path"]).read_text(encoding="utf-8")) out = {} for rid in p["reference"]["fingerprint_rids"]: fp = fingerprint_realization(inp.realization(rid, None)) ref = stored["realizations"][str(rid)] ok = all(ref[block].get(k) == v for block, d in fp.items() for k, v in d.items() if k in ref[block]) out[str(rid)] = {"match": bool(ok), "sha256_of_fingerprint": hashlib.sha256(json.dumps(fp, sort_keys=True).encode()).hexdigest()} if not ok: raise RuntimeError(f"nominal generator fingerprint of realization {rid} differs from tests/data/d2_fingerprints.json") return out def current_stamp(p: dict | None = None, with_fingerprints: bool = True) -> dict: p = load_protocol() if p is None else p inputs = {k: REPO_ROOT / v["path"] for k, v in p["inputs"].items()} refs = p2r_reference_files(p) missing = [f for f in list(inputs.values()) + refs if not f.exists()] if missing: raise FileNotFoundError(f"protocol_bench inputs missing (sync outputs/ first): {[str(f) for f in missing[:5]]}" f"{' ...' if len(missing) > 5 else ''}") stamp = {"protocol_sha256": digest(CONFIG, True), "code_sha256": source_hash(), "environment": environment(), "inputs": {portable(f): digest(f, f.suffix in (".yaml", ".json")) for f in inputs.values()}, "p2r_reference": {portable(f): digest(f, f.suffix == ".json") for f in refs}} if with_fingerprints: stamp["nominal_fingerprints"] = nominal_fingerprints(p) return stamp def freeze(check: bool = False) -> dict: """Return the lock; create it if absent and check is False. Any difference from an existing lock is an error.""" p = load_protocol() stamp = current_stamp(p) if LOCK.exists(): old = json.loads(LOCK.read_text(encoding="utf-8")) for k, v in stamp.items(): if old[k] != v: raise RuntimeError(f"protocol_bench lock mismatch: {k}. Preserve results and create a new protocol version.") return old if check: raise RuntimeError("protocol_bench is not locked. Run the lock stage before any main-grid run.") if any((outputs_dir() / "bench" / d).exists() for d in RESULT_DIRS): raise RuntimeError("Refusing a first lock after protocol_bench results already exist.") if any(v.get("sha256") in (None, "TBD") for v in p["inputs"].values()): raise RuntimeError("protocol_bench.yaml has an input without a recorded sha256 (TBD): fill it before locking.") if p.get("status", "").upper().startswith("DRAFT"): raise RuntimeError("protocol_bench.yaml still says DRAFT: set status to LOCKED (with the date) before locking.") stamp |= {"locked_utc": datetime.now(timezone.utc).isoformat(), "canonical_text": "UTF-8, CRLF normalized to LF for code, protocol and text inputs; binary inputs exact", "studies": sorted(p["studies"]), "realizations": p["grid"]["realizations"]} LOCK.write_text(json.dumps(stamp, indent=2), encoding="utf-8") CONFIG.with_suffix(".sha256").write_text(stamp["protocol_sha256"] + " configs/protocol_bench.yaml\n", encoding="utf-8") return stamp def dev_stamp(p: dict) -> dict: """Resume key for dev and repro runs: the nominal generator (configuration without the preset block) and the registration block only; the misspecification preset enters the job settings as its normalised dict. Code and protocol edits during dev therefore do not invalidate the cache (dev outputs are never results).""" cfg = {k: v for k, v in generator_config(p).items() if k != "misspec_presets"} return {"dev": True, "generator_nominal_sha256": hashlib.sha256(json.dumps(cfg, sort_keys=True, default=str).encode()).hexdigest(), "registration": p["registration"]} def fingerprint(stamp: dict, **settings) -> str: return hashlib.sha256(json.dumps({"lock": stamp, **settings}, sort_keys=True).encode()).hexdigest() def check_rids(rids, p: dict, dev: bool, repro: bool = False) -> None: """Main realizations only under the lock; dev realizations only with dev=True; protocol_p2 realizations never; no mixing. repro: the single reproduction cell (reproduction.rid) is allowed without the lock.""" rids = sorted(set(int(r) for r in rids)) p2 = protocol_p2(p)["grid"] if bad := sorted(set(rids) & set(p2["realizations"])): raise SystemExit(f"realizations {bad} belong to the protocol_p2 main grid and are never used by protocol_bench") main, devs = set(p["grid"]["realizations"]), set(p["grid"]["dev_realizations"]) if set(rids) & main and set(rids) & devs: raise SystemExit("do not mix main-grid and dev realizations in one run") if unknown := sorted(set(rids) - main - devs): raise SystemExit(f"realizations {unknown} are neither main-grid nor dev realizations of protocol_bench") if dev: if set(rids) & main: raise SystemExit("--dev runs use dev realizations 900–905 only") return if repro: if rids != [int(p["reproduction"]["rid"])]: raise SystemExit("the reproduction stage runs the single cell of protocol_bench reproduction:") return if set(rids) & devs: raise SystemExit("dev realizations require --dev (outputs go to outputs/bench/dev)") freeze(check=True)