"""Self-contained certificates for the multi-domain EVI core release. The original PlotQA release keeps using the schema-v1 certificate/replay path. This module covers the two new source-native families: * GQA: native semantic program + scene graph + released photograph + bbox mask; * CLEVR: native functional program + scene + fresh structured renderer. Both paths persist every input required to replay execution, rendering, evidence projection, and missing-information witnesses in a separate process. No model output participates in admission. """ from __future__ import annotations import io import json from collections.abc import Mapping, Sequence from pathlib import Path from typing import Any, Literal from PIL import Image from ..dsl.canonicalize import canonical_program_sha256 from ..executors.base import ExecutionResult from ..hashing import canonical_json_hash, sha256_file from ..renderers import render from ..renderers.base import RenderedAssets, decode_uint32_png from ..renderers.gqa import gqa_evidence_mask_png, raster_diff_mask_png, render_gqa_observation from ..sources.base import World from ..sources.world_ops import world_sha256 from .build import certificate_id, program_from_dict from .replay import ReplayResult CORE_CERTIFICATE_CONTRACT = "evi_core_view_v1" CoreSource = Literal["gqa", "clevr"] CoreState = Literal["FULL", "A_SAME", "A_CHANGED", "U_MISSING"] class CoreCertificateError(ValueError): """A source-native EVI view cannot be certified or replayed.""" def execution_record(result: ExecutionResult) -> dict[str, Any]: """Canonical persisted representation of an executor result.""" return { "status": result.status, "answer_canonical": result.answer_canonical, "dependency_node_ids": list(result.dependency_node_ids), "referent_cardinality": result.referent_cardinality, "trace_sha256": result.trace_sha256, "executor_name": result.executor_name, "executor_version": result.executor_version, } def evidence_mask_from_node_map( node_map_png: bytes, node_table: Sequence[str], dependency_node_ids: Sequence[str], ) -> bytes: """Project dependency IDs through a lossless node-owner map.""" import numpy as np if not node_table or node_table[0] != "__background__": raise CoreCertificateError("node table lacks background sentinel") index = {node_id: position for position, node_id in enumerate(node_table)} selected = [index[node_id] for node_id in dependency_node_ids if node_id in index] if not selected: raise CoreCertificateError("no dependency node has node-map coverage") owners = decode_uint32_png(node_map_png) mask = np.isin(owners, selected).astype("uint8") * 255 if not bool(mask.any()): raise CoreCertificateError("projected evidence mask is empty") output = io.BytesIO() Image.fromarray(mask, mode="L").save( output, format="PNG", optimize=False, compress_level=9, ) return output.getvalue() def build_core_certificate( *, source: CoreSource, base_id: str, view_id: str, state: CoreState, question_sha256: str, choices_sha256: str, program_language: str, program_sha256: str, before_world: World, after_world: World, before_result: ExecutionResult, after_result: ExecutionResult, renderer_name: str, renderer_version: str, renderer_seed: int, render_manifest: Mapping[str, Any], image_filename: str, image_sha256: str, node_map_sha256: str, diff_mask_sha256: str, evidence_mask_sha256: str, masked_node_id: str | None, fresh_structured_render: bool, completion_proof: Mapping[str, Any] | None = None, ) -> dict[str, Any]: """Build and validate a content-addressed multi-domain certificate.""" if len(base_id) != 64 or len(program_sha256) != 64: raise CoreCertificateError("base/program identity must be SHA-256") if not before_result.is_unique: raise CoreCertificateError("FULL execution must be unique") _validate_state( state, before_result=before_result, after_result=after_result, completion_proof=completion_proof, ) dependency_ids = list(before_result.dependency_node_ids) if not dependency_ids: raise CoreCertificateError("certificate requires executor dependency nodes") certificate: dict[str, Any] = { "schema_version": 1, "contract": CORE_CERTIFICATE_CONTRACT, "source": source, "tier": "C1_SOURCE_NATIVE", "base_id": base_id, "view_id": view_id, "question_sha256": question_sha256, "choices_sha256": choices_sha256, "world_before_sha256": world_sha256(before_world), "world_after_sha256": world_sha256(after_world), "program": { "language": program_language, "canonical_ast_sha256": program_sha256, "dependency_node_ids": dependency_ids, }, "executor": { "before": execution_record(before_result), "after": execution_record(after_result), }, "renderer": { "name": renderer_name, "version": renderer_version, "seed": renderer_seed, "render_manifest_sha256": canonical_json_hash(dict(render_manifest)), "image_filename": image_filename, "image_sha256": image_sha256, "node_map_sha256": node_map_sha256, "diff_mask_sha256": diff_mask_sha256, "evidence_mask_sha256": evidence_mask_sha256, "masked_node_id": masked_node_id, "fresh_structured_render": fresh_structured_render, }, "proof": { "state": state, "completion": dict(completion_proof) if completion_proof is not None else None, }, "checks": { "question_choices_unchanged": True, "source_full_answer_reproduced": True, "deterministic_executor_success": True, "render_manifest_validated": True, "semantic_mask_validated": True, "per_example_reasoning_vlm_calls": 0, "per_example_human_decisions": 0, }, } certificate["certificate_id"] = certificate_id(certificate) return certificate def is_core_certificate(value: Mapping[str, Any]) -> bool: return value.get("contract") == CORE_CERTIFICATE_CONTRACT def replay_core_view(view_dir: str | Path) -> ReplayResult: """Replay one GQA/CLEVR EVI view from only persisted bytes.""" root = Path(view_dir) errors: list[str] = [] try: certificate = _load(root / "certificate.json") before_world = _load(root / "world_before.json") after_world = _load(root / "world_after.json") program_record = _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 not is_core_certificate(certificate): return ReplayResult(str(root), False, ("not an EVI core certificate",)) if certificate_id(certificate) != certificate.get("certificate_id"): errors.append("certificate content address mismatch") source = str(certificate.get("source", "")) if source not in {"gqa", "clevr"}: errors.append(f"unsupported core certificate source {source!r}") return ReplayResult(str(root), False, tuple(errors)) try: program, executor = _restore_program_and_executor(source, program_record, before_world) before = executor.execute(program, world=before_world) after = executor.execute(program, world=after_world) except Exception as exc: return ReplayResult(str(root), False, (f"executor replay failed: {exc}",)) program_sha = ( program.canonical_program_sha256 if source == "gqa" else canonical_program_sha256(program, world=before_world) ) if program_sha != certificate.get("program", {}).get("canonical_ast_sha256"): errors.append("canonical program hash mismatch") if world_sha256(before_world) != certificate.get("world_before_sha256"): errors.append("world_before hash mismatch") if world_sha256(after_world) != certificate.get("world_after_sha256"): errors.append("world_after hash mismatch") if execution_record(before) != certificate.get("executor", {}).get("before"): errors.append("before executor result mismatch") if execution_record(after) != certificate.get("executor", {}).get("after"): errors.append("after executor result mismatch") renderer = certificate.get("renderer") if not isinstance(renderer, Mapping): return ReplayResult(str(root), False, (*errors, "renderer record missing")) image_filename = str(renderer.get("image_filename", "")) image_path = root / image_filename required_files = { "image": image_path, "node_map": root / "node_map.uint32.png", "diff_mask": root / "diff_mask.png", "evidence_mask": root / "evidence_mask.png", } for label, path in required_files.items(): if not path.is_file(): errors.append(f"{label} artifact missing") if errors and any("missing" in error for error in errors): return ReplayResult(str(root), False, tuple(errors)) if sha256_file(image_path) != renderer.get("image_sha256"): errors.append("persisted image hash mismatch") if sha256_file(required_files["node_map"]) != renderer.get("node_map_sha256"): errors.append("persisted node-map hash mismatch") if sha256_file(required_files["diff_mask"]) != renderer.get("diff_mask_sha256"): errors.append("persisted diff-mask hash mismatch") if sha256_file(required_files["evidence_mask"]) != renderer.get("evidence_mask_sha256"): errors.append("persisted evidence-mask hash mismatch") if canonical_json_hash(manifest) != renderer.get("render_manifest_sha256"): errors.append("render manifest hash mismatch") try: replay, full_replay = _rerender( source, root=root, before_world=before_world, after_world=after_world, renderer=renderer, ) except Exception as exc: errors.append(f"render replay failed: {exc}") else: if replay[0] != image_path.read_bytes(): errors.append("image replay bytes differ") if replay[1] != required_files["node_map"].read_bytes(): errors.append("node-map replay bytes differ") if replay[2] != manifest: errors.append("render-manifest replay differs") if replay[3] != text_manifest: errors.append("text-manifest replay differs") expected_diff = raster_diff_mask_png(full_replay[0], replay[0]) if expected_diff != required_files["diff_mask"].read_bytes(): errors.append("diff-mask replay bytes differ") dependency_ids = certificate.get("program", {}).get("dependency_node_ids") try: if source == "gqa": expected_evidence = gqa_evidence_mask_png( before_world, dependency_ids if isinstance(dependency_ids, list) else (), ) else: expected_evidence = evidence_mask_from_node_map( full_replay[1], full_replay[2]["node_table"], dependency_ids if isinstance(dependency_ids, list) else (), ) except Exception as exc: errors.append(f"evidence replay failed: {exc}") else: if expected_evidence != required_files["evidence_mask"].read_bytes(): errors.append("evidence-mask replay bytes differ") _verify_state_proof( certificate, before_result=before, after_result=after, errors=errors, ) if certificate.get("proof", {}).get("state") == "U_MISSING": _replay_completions( source, root=root, program=program, executor=executor, renderer=renderer, certificate=certificate, errors=errors, ) return ReplayResult(str(root), not errors, tuple(errors)) def _restore_program_and_executor( source: str, record: Mapping[str, Any], before_world: World, ) -> tuple[Any, Any]: if source == "gqa": from ..executors.gqa import GQASemanticExecutor, compile_gqa_program gqa_program = compile_gqa_program( str(record["question_id"]), { "imageId": record["image_id"], "semantic": record["semantic"], "semanticStr": record.get("semantic_str", ""), }, ) return gqa_program, GQASemanticExecutor() from ..executors.clevr import ClevrExecutor clevr_program = program_from_dict(record) if canonical_program_sha256(clevr_program, world=before_world) != ( record.get("canonical_program_sha256") ): raise CoreCertificateError("persisted CLEVR program identity mismatch") return clevr_program, ClevrExecutor() def _rerender( source: str, *, root: Path, before_world: World, after_world: World, renderer: Mapping[str, Any], ) -> tuple[ tuple[bytes, bytes, dict[str, Any], dict[str, Any]], tuple[bytes, bytes, dict[str, Any], dict[str, Any]], ]: seed = int(renderer["seed"]) if source == "gqa": source_bytes = (root / "source.jpg").read_bytes() masked = renderer.get("masked_node_id") observed = render_gqa_observation( source_bytes, after_world, masked_node_id=str(masked) if masked is not None else None, seed=seed, ) full = render_gqa_observation( source_bytes, before_world, masked_node_id=None, seed=seed, ) return ( ( observed.image_jpeg, observed.node_map_png, observed.render_manifest, observed.text_manifest, ), ( full.image_jpeg, full.node_map_png, full.render_manifest, full.text_manifest, ), ) manifest_width = int(_load(root / "render_manifest.json")["width"]) manifest_height = int(_load(root / "render_manifest.json")["height"]) observed_assets = render( after_world, renderer_id=str(renderer["name"]), seed=seed, width=manifest_width, height=manifest_height, ) full_assets = render( before_world, renderer_id=str(renderer["name"]), seed=seed, width=manifest_width, height=manifest_height, ) return _assets_tuple(observed_assets), _assets_tuple(full_assets) def _assets_tuple( assets: RenderedAssets, ) -> tuple[bytes, bytes, dict[str, Any], dict[str, Any]]: return ( assets.rgba_png, assets.node_map_png, assets.render_manifest, assets.text_manifest, ) def _replay_completions( source: str, *, root: Path, program: Any, executor: Any, renderer: Mapping[str, Any], certificate: Mapping[str, Any], errors: list[str], ) -> None: completion = certificate.get("proof", {}).get("completion") if not isinstance(completion, Mapping): errors.append("missing-information completion proof absent") return observed: list[str] = [] answers: list[Any] = [] for label in ("a", "b"): path = root / f"completion_{label}.json" try: world = _load(path) except (OSError, ValueError) as exc: errors.append(f"completion {label} load failed: {exc}") continue if world_sha256(world) != completion.get(f"world_{label}_sha256"): errors.append(f"completion {label} world hash mismatch") result = executor.execute(program, world=world) answers.append(result.answer_canonical) if result.status != "UNIQUE": errors.append(f"completion {label} is not uniquely answerable") if result.answer_canonical != completion.get(f"answer_{label}"): errors.append(f"completion {label} answer mismatch") try: if source == "gqa": masked = renderer.get("masked_node_id") gqa_assets = render_gqa_observation( (root / "source.jpg").read_bytes(), world, masked_node_id=str(masked) if masked is not None else None, seed=int(renderer["seed"]), ) observed.append(gqa_assets.image_sha256) else: manifest = _load(root / "render_manifest.json") clevr_assets = render( world, renderer_id=str(renderer["name"]), seed=int(renderer["seed"]), width=int(manifest["width"]), height=int(manifest["height"]), ) observed.append(clevr_assets.rgba_sha256) except Exception as exc: errors.append(f"completion {label} render failed: {exc}") if len(answers) == 2 and answers[0] == answers[1]: errors.append("completion answers do not differ") if len(observed) == 2: if observed[0] != observed[1]: errors.append("completion observations differ") expected = completion.get("observed_image_sha256") if observed[0] != expected: errors.append("completion observed-image hash mismatch") def _validate_state( state: CoreState, *, before_result: ExecutionResult, after_result: ExecutionResult, completion_proof: Mapping[str, Any] | None, ) -> None: if state == "FULL": if not after_result.is_unique or after_result.answer_canonical != ( before_result.answer_canonical ): raise CoreCertificateError("FULL requires the original unique answer") elif state == "A_SAME": if not after_result.is_unique or after_result.answer_canonical != ( before_result.answer_canonical ): raise CoreCertificateError("A_SAME requires equal unique answers") elif state == "A_CHANGED": if not after_result.is_unique or after_result.answer_canonical == ( before_result.answer_canonical ): raise CoreCertificateError("A_CHANGED requires a distinct unique answer") elif state == "U_MISSING": if after_result.status != "MISSING_INFORMATION": raise CoreCertificateError("U_MISSING requires MISSING_INFORMATION") if not isinstance(completion_proof, Mapping): raise CoreCertificateError("U_MISSING requires completion witnesses") if completion_proof.get("answer_a") == completion_proof.get("answer_b"): raise CoreCertificateError("completion witness answers must differ") else: raise CoreCertificateError(f"unsupported core state {state!r}") def _verify_state_proof( certificate: Mapping[str, Any], *, before_result: ExecutionResult, after_result: ExecutionResult, errors: list[str], ) -> None: state = certificate.get("proof", {}).get("state") try: _validate_state( state, before_result=before_result, after_result=after_result, completion_proof=certificate.get("proof", {}).get("completion"), ) except (CoreCertificateError, TypeError) as exc: errors.append(f"state proof mismatch: {exc}") def _load(path: Path) -> dict[str, Any]: value = json.loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError(f"{path} must contain an object") return value __all__ = [ "CORE_CERTIFICATE_CONTRACT", "CoreCertificateError", "build_core_certificate", "evidence_mask_from_node_map", "execution_record", "is_core_certificate", "replay_core_view", ]