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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
"""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",
]