"""Protocol locking and resume fingerprints for P4 (Volve), separate from the frozen P3 lock. Paths in the stamp are relative to their root (repo, outputs or Volve data directory), so a lock is portable between checkouts; it is still bound to one environment, as in P3. Before the lock exists, `current_stamp` gives the same stamp without writing it (smoke runs only). """ from __future__ import annotations import json from datetime import datetime, timezone from pathlib import Path import yaml from ml_porosity.f3.protocol import digest, environment, fingerprint from ml_porosity.paths import REPO_ROOT, outputs_dir, volve_root __all__ = ["CONFIG", "LOCK", "current_stamp", "fingerprint", "freeze", "load_protocol", "source_config"] CONFIG = REPO_ROOT / "configs/protocol_volve.yaml" LOCK = REPO_ROOT / "configs/protocol_volve.lock.json" SCRIPTS = ("scripts/23_build_volve_wells.py", "scripts/24_run_volve.py", "scripts/run_p4.ps1", "scripts/run_p4.sh") PROTECTED = ("wavelets.npz", "p2/warp_prior_f3.json") RESULTS = ("registration", "train", "summary") def load_protocol() -> dict: return yaml.safe_load(CONFIG.read_text(encoding="utf-8")) def source_config(p: dict) -> dict: """configs/d3_volve.yaml, which built the dataset; its p4 section holds the slot groups of the blind folds.""" cfg = yaml.safe_load((REPO_ROOT / p["data"]["source_config"]).read_text(encoding="utf-8")) if list(cfg["p4"]["wells"]) != list(p["data"]["wells"]) or cfg["p4"]["label"] != p["data"]["label"]: raise RuntimeError("protocol_volve and its source configuration disagree on wells or label") if not set(p["split"]["schemes"]) <= set(cfg["p4"]["blind_schemes"]): raise RuntimeError("Unknown blind scheme in protocol_volve") return cfg 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: import hashlib 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 input_files(p: dict) -> list[Path]: """Derived dataset, its configuration and every raw file the build reads, except the cube (checked against the data manifest at the first lock).""" cfg = source_config(p) root, p4 = volve_root(), cfg["p4"] files = [outputs_dir() / "volve/volve_wells.npz", outputs_dir() / "volve/volve_wells_summary.json", root / cfg["picks"], root / cfg["horizons_twt"] / cfg["grid_horizon"]] for spec in p4["wells"].values(): files.append(root / p4["survey_dir"] / spec["survey"]) logs = root / cfg["well_logs_dir"] / spec["logs"] / p4["log_subdir"] files += [logs / p4["las_input"], logs / p4["las_output"]] files += [root / cfg["well_logs_dir"] / cfg["checkshots"][spec["picks"]][kind] for kind in spec.get("checkshots", [])] return files def portable_name(path: Path) -> str: """Portable name: 'repo:', 'outputs:' or 'volve:' plus the POSIX path relative to that root.""" path = path.resolve() for prefix, base in (("volve", volve_root()), ("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, outputs and Volve roots: {path}") def current_stamp(p: dict | None = None) -> dict: p = load_protocol() if p is None else p missing = [f for f in input_files(p) + [outputs_dir() / a for a in PROTECTED] if not f.exists()] if missing: raise FileNotFoundError(f"P4 inputs missing (sync data/ and outputs/ first): {[str(f) for f in missing]}") config = REPO_ROOT / p["data"]["source_config"] return {"protocol_sha256": digest(CONFIG, True), "code_sha256": source_hash(), "environment": environment(), "protected_artifacts": {portable_name(outputs_dir() / a): digest(outputs_dir() / a) for a in PROTECTED}, "inputs": {portable_name(f): digest(f, f == config) for f in [config] + input_files(p)}} 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"P4 lock mismatch: {k}. Preserve results and create a new protocol version.") return old if check: raise RuntimeError("P4 is not locked. Run the lock stage before registration/training.") if any((outputs_dir() / "p4" / d).exists() for d in RESULTS): raise RuntimeError("Refusing a first lock after P4 results already exist.") cfg = source_config(p) manifest = json.loads((REPO_ROOT / "data_manifest/volve.json").read_text(encoding="utf-8")) expected = manifest["files"][cfg["cube"]]["sha256"] cube = volve_root() / cfg["cube"] if not cube.exists() or digest(cube) != expected: raise RuntimeError(f"Volve cube missing or different from the audited source: {cube}") stamp |= {"locked_utc": datetime.now(timezone.utc).isoformat(), "segy_sha256": expected, "canonical_text": "UTF-8, CRLF normalized to LF for code, protocol and source configuration; " "binary inputs exact", "wells": p["data"]["wells"]} LOCK.write_text(json.dumps(stamp, indent=2), encoding="utf-8") CONFIG.with_suffix(".sha256").write_text(stamp["protocol_sha256"] + " configs/protocol_volve.yaml\n", encoding="utf-8") return stamp