"""Portable protocol locking and resume fingerprints for P3.""" from __future__ import annotations import hashlib import importlib.metadata import itertools import json import platform from datetime import datetime, timezone from pathlib import Path import yaml from ml_porosity.paths import REPO_ROOT, f3_root, f3_segy, outputs_dir CONFIG = REPO_ROOT / 'configs/protocol_f3.yaml' LOCK = REPO_ROOT / 'configs/protocol_f3.lock.json' def digest(path: Path, text: bool = False) -> str: h = hashlib.sha256() if text: h.update(path.read_bytes().replace(b'\r\n', b'\n')) else: with path.open('rb') as f: for chunk in iter(lambda: f.read(8 * 1024 * 1024), b''): h.update(chunk) return h.hexdigest() def source_hash() -> str: h = hashlib.sha256() paths = sorted((REPO_ROOT / 'ml_porosity').rglob('*.py')) paths += sorted((REPO_ROOT / 'scripts').glob('*.py')) paths += [REPO_ROOT/'scripts/run_p3.ps1'] paths += [REPO_ROOT / 'pyproject.toml'] for p in paths: h.update(p.relative_to(REPO_ROOT).as_posix().encode() + b'\0') h.update(p.read_bytes().replace(b'\r\n', b'\n') + b'\0') return h.hexdigest() def environment() -> dict: packages = ('torch', 'numpy', 'scipy', 'pandas', 'matplotlib', 'segyio', 'lasio', 'pylops', 'numba', 'scikit-learn', 'PyYAML', 'tabulate', 'psutil') return {'python': platform.python_version(), 'platform': platform.system(), 'packages': {name: importlib.metadata.version(name) for name in packages}} def load_protocol() -> dict: return yaml.safe_load(CONFIG.read_text(encoding='utf-8')) def training_sets(wells: list[str], size: int = 2) -> list[tuple[str, ...]]: return list(itertools.combinations(sorted(wells), size)) def inner_folds(wells: list[str], outer: str) -> list[tuple[str, tuple[str, ...]]]: if outer not in wells: raise ValueError(outer) train = [w for w in wells if w != outer] return [(v, tuple(sorted(w for w in train if w != v))) for v in train] def freeze(check: bool = False) -> dict: p = load_protocol() data = outputs_dir() / 'f3_wells.npz' files = [data, REPO_ROOT/'configs/d1_f3.yaml', REPO_ROOT/'configs/protocol.yaml', f3_root()/'.survey'] files += sorted(f3_root().glob('WellInfo/*.wlt')) files += sorted((f3_root() / 'Rawdata/Well_data').rglob('*.las')) files += sorted((f3_root() / 'Rawdata/Well_data').rglob('*_TD.txt')) protected = [outputs_dir()/'wavelets.npz', outputs_dir()/'p2/warp_prior_f3.json'] stamp = {'protocol_sha256': digest(CONFIG, True), 'code_sha256': source_hash(), 'environment': environment(), 'protected_artifacts': {str(f.relative_to(REPO_ROOT)): digest(f) for f in protected}, 'inputs': {str(f.relative_to(REPO_ROOT)): digest(f) for f in files}} 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'P3 lock mismatch: {k}. Preserve results and create a new protocol version.') return old if check: raise RuntimeError('P3 is not locked. Run the lock stage before registration/training.') if any((outputs_dir() / 'p3' / d).exists() for d in ('registration', 'train', 'summary')): raise RuntimeError('Refusing a first lock after P3 results already exist.') manifest = json.loads((REPO_ROOT / 'data_manifest/f3_demo_2023.json').read_text(encoding='utf-8')) expected = manifest['files']['Rawdata/F3_entire.segy']['sha256'] if digest(f3_segy()) != expected: raise RuntimeError('F3 cube differs from the audited source.') stamp |= {'locked_utc': datetime.now(timezone.utc).isoformat(), 'segy_sha256': expected, 'canonical_text': 'UTF-8, CRLF normalized to LF for code and protocol; 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_f3.yaml\n', encoding='utf-8') return stamp def fingerprint(stamp: dict, **settings) -> str: return hashlib.sha256(json.dumps({'lock': stamp, **settings}, sort_keys=True).encode()).hexdigest()