File size: 10,325 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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))