File size: 11,462 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
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
"""Build content-addressed state certificates.

The certificate is deliberately derived only from immutable inputs: the source
and transformed worlds, typed program, deterministic executor results, and two
byte-identical renderer passes.  A model response is never accepted as a label.
"""

from __future__ import annotations

from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from functools import lru_cache
from typing import Any, Literal

from ..dsl.ast import Program, ast_node_from_dict
from ..executors.base import ExecutionResult
from ..hashing import canonical_json_hash
from ..paths import repo_root
from ..renderers.base import RenderedAssets
from ..schema_io import load_schema, validate
from ..sources.base import World
from ..sources.world_ops import world_sha256

State = Literal["FULL", "A_SAME", "A_CHANGED", "U_MISSING", "U_INVALID"]


class CertificateError(ValueError):
    """A certificate cannot be proven from the supplied artifacts."""


@dataclass(frozen=True)
class MissingProofInputs:
    completion_a_world_sha256: str
    completion_b_world_sha256: str
    completion_a_answer: str | int | bool
    completion_b_answer: str | int | bool
    observed_render_a_sha256: str
    observed_render_b_sha256: str


def certificate_id(certificate: Mapping[str, Any]) -> str:
    """Recompute the content address, excluding the address field itself."""
    payload = dict(certificate)
    payload.pop("certificate_id", None)
    return canonical_json_hash(payload)


@lru_cache(maxsize=1)
def _certificate_schema() -> dict[str, Any]:
    return load_schema(repo_root() / "schemas" / "intervention_certificate.schema.json")


def program_from_dict(data: Mapping[str, Any]) -> Program:
    """Rebuild a :class:`Program` from its P2 envelope."""
    selector = data.get("referent_selector")
    return Program(
        dsl=str(data["dsl"]),  # type: ignore[arg-type]
        program=ast_node_from_dict(data["program"]),
        base_id=str(data["base_id"]),
        question_sha256=str(data["question_sha256"]),
        choices_sha256=str(data["choices_sha256"]),
        compile_status=str(data["compile_status"]),  # type: ignore[arg-type]
        referent_selector=ast_node_from_dict(selector) if isinstance(selector, Mapping) else None,
        required_referent_cardinality=data.get("required_referent_cardinality"),
        referenced_node_ids=tuple(str(v) for v in data.get("referenced_node_ids", [])),
        canonical_program_sha256=str(data.get("canonical_program_sha256") or ""),
        reason_code=str(data["reason_code"]) if data.get("reason_code") is not None else None,
        constraint_channels=tuple((str(k), str(v)) for k, v in data.get("constraint_channels", [])),
    )


def _status(value: str) -> str:
    mapping = {
        "UNIQUE": "unique_answer",
        "MISSING_INFORMATION": "missing_information",
        "INVALID_REFERENT": "invalid_referent",
    }
    try:
        return mapping[value]
    except KeyError:
        raise CertificateError(f"executor status {value!r} cannot certify a label") from None


def _assert_render_replay(first: RenderedAssets, replay: RenderedAssets) -> None:
    if first.rgba_png != replay.rgba_png:
        raise CertificateError("RGBA render replay differs")
    if first.node_map_png != replay.node_map_png:
        raise CertificateError("node-map render replay differs")
    if first.render_manifest != replay.render_manifest:
        raise CertificateError("render manifest replay differs")
    if first.text_manifest != replay.text_manifest:
        raise CertificateError("text manifest replay differs")


def _proof(
    state: State,
    before: ExecutionResult,
    after: ExecutionResult,
    *,
    missing: MissingProofInputs | None,
) -> dict[str, Any]:
    if state == "FULL":
        if not before.is_unique or after.answer_canonical != before.answer_canonical:
            raise CertificateError("FULL requires the same unique before/after answer")
        return {"state": state, "answer": before.answer_canonical}
    if state == "A_SAME":
        if not before.is_unique or not after.is_unique:
            raise CertificateError("A_SAME requires two unique answers")
        if after.answer_canonical != before.answer_canonical:
            raise CertificateError("A_SAME answers differ")
        return {
            "state": state,
            "before_answer": before.answer_canonical,
            "after_answer": after.answer_canonical,
            "equality_asserted": True,
        }
    if state == "A_CHANGED":
        if not before.is_unique or not after.is_unique:
            raise CertificateError("A_CHANGED requires two unique answers")
        if after.answer_canonical == before.answer_canonical:
            raise CertificateError("A_CHANGED answers are equal")
        return {
            "state": state,
            "before_answer": before.answer_canonical,
            "after_answer": after.answer_canonical,
            "inequality_asserted": True,
        }
    if state == "U_MISSING":
        if after.status != "MISSING_INFORMATION":
            raise CertificateError("U_MISSING requires MISSING_INFORMATION after execution")
        if missing is None:
            raise CertificateError("U_MISSING requires two completion witnesses")
        if missing.completion_a_answer == missing.completion_b_answer:
            raise CertificateError("U_MISSING completion answers must differ")
        if missing.observed_render_a_sha256 != missing.observed_render_b_sha256:
            raise CertificateError("U_MISSING completion observations must be identical")
        return {
            "state": state,
            "completion_a_world_sha256": missing.completion_a_world_sha256,
            "completion_b_world_sha256": missing.completion_b_world_sha256,
            "completion_a_answer": missing.completion_a_answer,
            "completion_b_answer": missing.completion_b_answer,
            "answers_differ": True,
            "observed_render_a_sha256": missing.observed_render_a_sha256,
            "observed_render_b_sha256": missing.observed_render_b_sha256,
            "observed_renders_identical": True,
        }
    if state == "U_INVALID":
        if after.status != "INVALID_REFERENT":
            raise CertificateError("U_INVALID requires INVALID_REFERENT after execution")
        if before.referent_cardinality != 1 or after.referent_cardinality == 1:
            raise CertificateError("U_INVALID selector cardinalities do not prove failure")
        return {
            "state": state,
            "selector_cardinality_before": 1,
            "selector_cardinality_after": int(after.referent_cardinality or 0),
            "required_cardinality": 1,
            "precondition_failed": True,
        }
    raise CertificateError(f"unknown state {state!r}")


def build_certificate(
    *,
    tier: Literal["C1_SOURCE_NATIVE", "C2_DUAL_COMPILED"],
    base_id: str,
    view_id: str,
    question_sha256: str,
    choices_sha256: str,
    world_before: World,
    world_after: World,
    program: Program,
    before_result: ExecutionResult,
    after_result: ExecutionResult,
    renderer_id: str,
    renderer_version: str,
    renderer_seed: int,
    first_render: RenderedAssets,
    replay_render: RenderedAssets,
    changed_node_ids: Sequence[str],
    diff_mask_sha256: str,
    state: State,
    missing_proof: MissingProofInputs | None = None,
    reference_result: ExecutionResult | None = None,
    c2_compilation: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
    """Build and schema-validate one content-addressed certificate."""
    if program.compile_status != "compiled":
        raise CertificateError("an unsupported program cannot be certified")
    if program.base_id != base_id:
        raise CertificateError("program/base ID mismatch")
    if program.question_sha256 != question_sha256 or program.choices_sha256 != choices_sha256:
        raise CertificateError("program question/choices hash mismatch")
    if not before_result.is_unique:
        raise CertificateError("FULL execution is not unique")
    _assert_render_replay(first_render, replay_render)

    selector_sha = (
        canonical_json_hash(program.referent_selector.to_ast_node_dict())
        if program.referent_selector is not None
        else None
    )
    proof = _proof(state, before_result, after_result, missing=missing_proof)
    certificate: dict[str, Any] = {
        "schema_version": 1,
        "tier": tier,
        "base_id": base_id,
        "view_id": view_id,
        "question_sha256": question_sha256,
        "choices_sha256": choices_sha256,
        "world_before_sha256": world_sha256(world_before),
        "world_after_sha256": world_sha256(world_after),
        "program": {
            "language": program.dsl,
            "canonical_ast_sha256": program.canonical_program_sha256,
            "dependency_node_ids": list(before_result.dependency_node_ids),
            "referent_selector_sha256": selector_sha,
        },
        "executor": {
            "name": before_result.executor_name,
            "version": before_result.executor_version,
            "deterministic": True,
            "before_trace_sha256": before_result.trace_sha256,
            "after_trace_sha256": after_result.trace_sha256,
            "before_answer_canonical": before_result.answer_canonical,
            "after_answer_canonical": after_result.answer_canonical,
            "after_status": _status(after_result.status),
        },
        "reference_executor": None,
        "renderer": {
            "name": renderer_id,
            "version": renderer_version,
            "seed": renderer_seed,
            "render_manifest_sha256": canonical_json_hash(first_render.render_manifest),
            "first_render_sha256": first_render.rgba_sha256,
            "replay_render_sha256": replay_render.rgba_sha256,
            "replay_exact_match": True,
            "changed_node_ids": sorted(set(changed_node_ids)),
            "diff_mask_sha256": diff_mask_sha256,
        },
        "proof": proof,
        "c2_compilation": dict(c2_compilation) if c2_compilation is not None else None,
        "checks": {
            "question_choices_unchanged": True,
            "source_full_answer_reproduced": True,
            "fresh_structured_render": True,
            "pixel_scope_audit_passed": True,
            "choice_uniqueness_passed": True,
            "certificate_replayed": True,
        },
    }
    if reference_result is not None:
        agrees = (
            reference_result.status == after_result.status
            and reference_result.answer_canonical == after_result.answer_canonical
        )
        if not agrees:
            raise CertificateError("reference executor disagrees with primary")
        certificate["reference_executor"] = {
            "name": reference_result.executor_name,
            "version": reference_result.executor_version,
            "after_status": _status(reference_result.status),
            "after_answer_canonical": reference_result.answer_canonical,
            "trace_sha256": reference_result.trace_sha256,
            "agrees_with_primary": True,
        }
    certificate["certificate_id"] = certificate_id(certificate)
    errors = validate(certificate, _certificate_schema())
    if errors:
        raise CertificateError("certificate schema validation failed: " + "; ".join(errors))
    return certificate