"""Frozen evaluator contract (mirrors Kea's define_evaluator semantics). The contract pins everything that changes evaluation semantics: the problems source, the scoring rule, the solver registry behavior, tolerance mapping and budget. A content hash over the relevant source files + canonical params guards against silent drift: if any of it changes, load() fails closed and a new version must be frozen, after which the baseline is rebuilt (Kea rule: never compare scores across contract versions). """ import hashlib, json, os SRC_DIR = os.path.dirname(os.path.abspath(__file__)) CONTRACT_FILE = os.path.join(os.path.dirname(SRC_DIR), "benchmarks", "contract.json") # Only files that change EVALUATION SEMANTICS (scoring rule + baseline methods). # Candidate-method files (detectors.py, switcher.py) get a separate methods hash # recorded in candidates.json, so detector-threshold calibration does not # invalidate the baseline contract. FILES = ["problems.py", "score.py", "dopri5.py"] # contract.py self-reference excluded; PARAMS below is hashed METHOD_FILES = ["detectors.py", "switcher.py"] # Canonical semantic parameters (changing any = new version) PARAMS = { "metric": {"name": "work_log", "direction": "minimize"}, "seeds": [0, 1, 2], "tols": {"0": 1e-4, "1": 1e-6, "2": 1e-8}, "budget_nfe": 1_000_000, # failed/over-budget runs count as budget "jacobian_weight": 25, # gamma: njev -> nfev equivalents "error_slack": 10.0, # success iff err <= slack * tol } def _hash_files(files): h = hashlib.sha256() for f in files: p = os.path.join(SRC_DIR, f) with open(p, "rb") as fh: h.update(fh.read()) return h def _read_json(path): with open(path) as fh: return json.load(fh) def _digest16(path): with open(path, "rb") as fh: return hashlib.sha256(fh.read()).hexdigest()[:16] def content_hash(): h = _hash_files(FILES) h.update(json.dumps(PARAMS, sort_keys=True).encode()) return h.hexdigest()[:16] def methods_hash(): return _hash_files(METHOD_FILES).hexdigest()[:16] def freeze(version=None): """Write/update contract.json. Returns (version, hash).""" data = {} if os.path.exists(CONTRACT_FILE): try: data = _read_json(CONTRACT_FILE) except Exception: data = {} h = content_hash() if data.get("contentHash") == h: return data["version"], h version = (data.get("version", 0) + 1) if version is None else version # archive previous version if data.get("contentHash"): prev = os.path.join(os.path.dirname(CONTRACT_FILE), f"contract.v{data['version']}.json") with open(prev, "w") as f: json.dump(data, f, indent=2) with open(CONTRACT_FILE, "w") as f: json.dump({"name": "ode_stiff_switch", "version": version, "contentHash": h, "params": PARAMS, "frozenAt": __import__("time").time(), "files": {fn: _digest16(os.path.join(SRC_DIR, fn)) for fn in FILES}}, f, indent=2) return version, h def load(): """Fail-closed: tampered contract raises.""" if not os.path.exists(CONTRACT_FILE): raise RuntimeError("no contract frozen - run freeze() first") data = _read_json(CONTRACT_FILE) if data.get("contentHash") != content_hash(): raise RuntimeError("contract tampered: contentHash mismatch (re-freeze and rebuild baseline)") return data if __name__ == "__main__": v, h = freeze() print(f"contract v{v} hash={h}")