"""Independent replay of persisted certificate artifacts.""" from __future__ import annotations import json from concurrent.futures import ProcessPoolExecutor from dataclasses import dataclass from pathlib import Path from typing import Any from ..dsl.canonicalize import canonical_program_sha256 from ..executors import get_executor from ..executors.reference_plot import ReferencePlotExecutor from ..hashing import canonical_json_hash, sha256_file from ..paths import repo_root from ..renderers import render from ..schema_io import load_schema, parse_json, validate from ..sources.world_ops import world_sha256 from .build import certificate_id, program_from_dict @dataclass(frozen=True) class ReplayResult: view_dir: str ok: bool errors: tuple[str, ...] def _load(path: Path) -> dict[str, Any]: value = parse_json(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError(f"{path} must contain an object") return value def replay_view(view_dir: str | Path) -> ReplayResult: """Replay one persisted view without using builder in-memory objects.""" root = Path(view_dir) errors: list[str] = [] try: cert = _load(root / "certificate.json") before_world = _load(root / "world_before.json") after_world = _load(root / "world_after.json") program = program_from_dict(_load(root / "program.json")) manifest = _load(root / "render_manifest.json") text_manifest = _load(root / "text_manifest.json") except (OSError, ValueError, KeyError, TypeError) as exc: return ReplayResult(str(root), False, (f"load failed: {exc}",)) if certificate_id(cert) != cert.get("certificate_id"): errors.append("certificate content address mismatch") schema_errors = validate( cert, load_schema(repo_root() / "schemas" / "intervention_certificate.schema.json") ) if schema_errors: errors.append("certificate schema mismatch: " + "; ".join(schema_errors[:3])) if program.base_id != cert.get("base_id"): errors.append("program base-id mismatch") if program.question_sha256 != cert.get("question_sha256"): errors.append("program question hash mismatch") if program.choices_sha256 != cert.get("choices_sha256"): errors.append("program choices hash mismatch") if canonical_program_sha256(program, world=before_world) != cert.get("program", {}).get( "canonical_ast_sha256" ): errors.append("canonical program hash mismatch") if world_sha256(before_world) != cert.get("world_before_sha256"): errors.append("world_before hash mismatch") if world_sha256(after_world) != cert.get("world_after_sha256"): errors.append("world_after hash mismatch") if canonical_json_hash(manifest) != cert.get("renderer", {}).get("render_manifest_sha256"): errors.append("render manifest hash mismatch") image_path = root / "image.png" node_map_path = root / "node_map.uint32.png" diff_mask_path = root / "diff_mask.png" if not image_path.exists(): errors.append("image.png missing") elif sha256_file(image_path) != cert.get("renderer", {}).get("first_render_sha256"): errors.append("persisted image hash mismatch") if not node_map_path.exists(): errors.append("node_map.uint32.png missing") elif sha256_file(node_map_path) != manifest.get("node_map_sha256"): errors.append("persisted node-map hash mismatch") if not diff_mask_path.exists(): errors.append("diff_mask.png missing") elif sha256_file(diff_mask_path) != cert.get("renderer", {}).get("diff_mask_sha256"): errors.append("persisted diff-mask hash mismatch") executor = get_executor(program.dsl) before = executor.execute(program, world=before_world) after = executor.execute(program, world=after_world) ex = cert.get("executor", {}) if before.trace_sha256 != ex.get("before_trace_sha256"): errors.append("before executor trace mismatch") if after.trace_sha256 != ex.get("after_trace_sha256"): errors.append("after executor trace mismatch") if before.answer_canonical != ex.get("before_answer_canonical"): errors.append("before executor answer mismatch") if after.answer_canonical != ex.get("after_answer_canonical"): errors.append("after executor answer mismatch") expected_status = { "UNIQUE": "unique_answer", "MISSING_INFORMATION": "missing_information", "INVALID_REFERENT": "invalid_referent", }.get(after.status) if expected_status != ex.get("after_status"): errors.append("after executor status mismatch") try: assets = render( after_world, renderer_id=str(cert["renderer"]["name"]), seed=int(cert["renderer"]["seed"]), width=int(manifest["width"]), height=int(manifest["height"]), ) except Exception as exc: # renderer failures must become a replay failure errors.append(f"render replay failed: {exc}") else: if assets.rgba_sha256 != cert.get("renderer", {}).get("replay_render_sha256"): errors.append("RGBA replay hash mismatch") if assets.node_map_sha256 != manifest.get("node_map_sha256"): errors.append("node-map replay hash mismatch") if assets.render_manifest != manifest: errors.append("render replay manifest mismatch") if assets.text_manifest != text_manifest: errors.append("text-manifest replay mismatch") proof = cert.get("proof", {}) state = proof.get("state") if state == "FULL" and ( not before.is_unique or not after.is_unique or before.answer_canonical != after.answer_canonical or proof.get("answer") != after.answer_canonical ): errors.append("FULL proof mismatch") if state == "A_SAME" and ( not before.is_unique or not after.is_unique or before.answer_canonical != after.answer_canonical ): errors.append("A_SAME proof mismatch") if state == "A_CHANGED" and ( not before.is_unique or not after.is_unique or before.answer_canonical == after.answer_canonical ): errors.append("A_CHANGED proof mismatch") if state == "U_INVALID" and ( before.referent_cardinality != 1 or after.status != "INVALID_REFERENT" or after.referent_cardinality == 1 ): errors.append("U_INVALID proof mismatch") if proof.get("state") == "U_MISSING": if after.status != "MISSING_INFORMATION": errors.append("U_MISSING executor status mismatch") for label in ("a", "b"): path = root / f"completion_{label}.json" if not path.exists(): errors.append(f"{path.name} missing") continue completion = _load(path) if world_sha256(completion) != proof.get(f"completion_{label}_world_sha256"): errors.append(f"completion {label} world hash mismatch") result = executor.execute(program, world=completion) expected = proof.get(f"completion_{label}_answer") if result.answer_canonical != expected: errors.append(f"completion {label} answer mismatch") try: observed = render( completion, renderer_id=str(cert["renderer"]["name"]), seed=int(cert["renderer"]["seed"]), width=int(manifest["width"]), height=int(manifest["height"]), ) except Exception as exc: errors.append(f"completion {label} render failed: {exc}") else: if observed.rgba_sha256 != proof.get(f"observed_render_{label}_sha256"): errors.append(f"completion {label} observed hash mismatch") if proof.get("observed_render_a_sha256") != proof.get("observed_render_b_sha256"): errors.append("completion observations differ") reference = cert.get("reference_executor") if isinstance(reference, dict): ref_result = ReferencePlotExecutor().execute(program, world=after_world) ref_status = { "UNIQUE": "unique_answer", "MISSING_INFORMATION": "missing_information", "INVALID_REFERENT": "invalid_referent", }.get(ref_result.status) if ref_status != reference.get("after_status"): errors.append("reference executor status mismatch") if ref_result.answer_canonical != reference.get("after_answer_canonical"): errors.append("reference executor answer mismatch") if ref_result.trace_sha256 != reference.get("trace_sha256"): errors.append("reference executor trace mismatch") if ( ref_result.status != after.status or ref_result.answer_canonical != after.answer_canonical ): errors.append("reference executor disagrees with primary") return ReplayResult(str(root), not errors, tuple(errors)) def replay_dataset(dataset_dir: str | Path, *, workers: int = 1) -> list[ReplayResult]: """Replay every referenced view, preserving manifest order across workers.""" if workers < 1: raise ValueError("workers must be at least 1") root = Path(dataset_dir) view_dirs: list[Path] = [] with (root / "groups.jsonl").open("r", encoding="utf-8") as handle: for line in handle: if not line.strip(): continue group = json.loads(line) for view in group.get("views", []): rel = view.get("artifact_dir") if rel is None: # Released schema v2 stores the image path; its parent is the # canonical view artifact directory. images = view.get("images") or [] rel = str(Path(images[0]["path"]).parent) if images else "" view_dirs.append(root / str(rel)) if workers == 1: return [replay_view(view_dir) for view_dir in view_dirs] with ProcessPoolExecutor(max_workers=workers) as pool: return list(pool.map(replay_view, view_dirs, chunksize=8))