File size: 7,402 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
"""C2 compile request construction (``docs/02`` §7.1).

A C2 compile request is sent *independently* to each model. §7.1 fixes what it
carries and — just as importantly — what it hides:

  * **sends** — the *untransformed* image (by content hash; bytes travel
    out-of-band to the model client), the raw question + choices, the source
    structured table / recognized formal candidates when present, the DSL
    grammar, and the ``astNode`` JSON schema the response must match.
  * **hides** — the other model's output, the intended intervention / state, and
    any candidate *transformed* image. The two models must compile from the same
    untouched evidence; neither sees what the other produced or what the
    intervention layer plans to do.

``request_sha256`` is the canonical-JSON hash of the payload, the idempotency key
for response caching and the field recorded on the ``compiled_program`` record.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from ..dsl.ast import Dsl
from ..dsl.typecheck import signatures
from ..hashing import canonical_json_hash
from ..sources.base import World

# Fields the request payload is *forbidden* to carry (§7.1 hiding rule). The
# builder asserts none are present so a future caller cannot leak the
# intervention or a sibling model's output into an independent request.
_FORBIDDEN_PAYLOAD_KEYS = frozenset(
    {
        "intended_state",
        "intended_intervention",
        "operator_name",
        "proposer_output",
        "verifier_output",
        "other_model_output",
        "transformed_image_sha256",
        "transformed_image",
        "candidate_transformed_image",
        "original_answer",
    }
)


@dataclass(frozen=True)
class C2Candidate:
    """One C2-eligible item presented to both compilers.

    C2 applies only to ChartQA-H / MMK12 / MMR1-RL / MMMU candidates (§7); the
    assembler (P11) selects them, not the compiler. ``world`` carries the source
    structured table / formal candidates when available (§7.1 "source structured
    table / recognized formal candidates가 있으면 그것"); it may be empty for
    image-only candidates, in which case the models compile from the image alone.
    """

    base_id: str
    dsl: Dsl
    question_sha256: str
    choices_sha256: str
    question_text: str
    choices: tuple[tuple[str, str], ...]  # (key, text) pairs
    image_sha256: str
    world: World


@dataclass(frozen=True)
class CompileRequest:
    """The independent, §7.1-compliant compile request for one model."""

    base_id: str
    dsl: Dsl
    request_sha256: str
    payload: dict[str, Any]
    prompt: str
    image_sha256: str = ""

    def to_dict(self) -> dict[str, Any]:
        return {
            "base_id": self.base_id,
            "dsl": self.dsl,
            "request_sha256": self.request_sha256,
            "image_sha256": self.image_sha256,
            "payload": self.payload,
        }


def _grammar(dsl: Dsl) -> list[dict[str, Any]]:
    """A deterministic, JSON-serializable summary of the DSL operator table."""
    out: list[dict[str, Any]] = []
    for op, sig in sorted(signatures(dsl).items()):
        out.append(
            {
                "op": op,
                "arg_types": list(sig.arg_types),
                "return_type": sig.return_type,
                "commutative": sig.commutative,
                "selector_kind": sig.selector_kind,
                "variadic": sig.variadic,
            }
        )
    return out


def _ast_node_schema_ref() -> dict[str, Any]:
    """A compact pointer to the response schema (the model emits an ``astNode``)."""
    return {
        "$ref": "schemas/compiled_program.schema.json#/$defs/astNode",
        "shape": {
            "op": "string",
            "args": "array of astNode | string | number | boolean",
            "return_type": "string (optional)",
        },
    }


def _world_candidates(world: World) -> dict[str, Any] | None:
    """The structured evidence §7.1 permits sending, pruned to serializable form.

    Only the data-bearing slices a program references are sent (series/points,
    table rows/cells, geometry entities/constraints) — never the rendered image
    bytes, and never any intervention metadata. Returns ``None`` for an empty
    world so image-only candidates carry no ``world_candidates`` key.
    """
    slices: dict[str, Any] = {}
    for key in ("series", "rows", "entities", "constraints"):
        value = world.get(key)
        if value:
            slices[key] = value
    return slices or None


def build_compile_request(candidate: C2Candidate) -> CompileRequest:
    """Assemble the §7.1 independent compile request for ``candidate``.

    The payload carries the DSL, grammar, astNode schema ref, question, choices,
    image content hash, and (when present) the source structured candidates. It
    never carries an intervention, a transformed image, or another model's output.
    """
    candidates = _world_candidates(candidate.world)
    payload: dict[str, Any] = {
        "dsl": candidate.dsl,
        "grammar": _grammar(candidate.dsl),
        "ast_node_schema": _ast_node_schema_ref(),
        "question": candidate.question_text,
        "choices": [{"key": k, "text": t} for k, t in candidate.choices],
        "image_sha256": candidate.image_sha256,
        "base_id": candidate.base_id,
    }
    if candidates is not None:
        payload["world_candidates"] = candidates

    leaked = _FORBIDDEN_PAYLOAD_KEYS & payload.keys()
    if leaked:
        raise AssertionError(f"§7.1 leak in compile request payload: {sorted(leaked)!r}")

    request_sha = canonical_json_hash(payload)
    prompt = _render_prompt(payload)
    return CompileRequest(
        base_id=candidate.base_id,
        dsl=candidate.dsl,
        request_sha256=request_sha,
        payload=payload,
        prompt=prompt,
        image_sha256=candidate.image_sha256,
    )


def _render_prompt(payload: dict[str, Any]) -> str:
    """The natural-language prompt wrapping the JSON payload for the model.

    The model is instructed to emit *only* a JSON object with the program
    envelope subset (``dsl`` / ``program`` / ``referent_selector`` /
    ``required_referent_cardinality``) conforming to ``$defs/astNode``. The
    payload is embedded verbatim; the prompt itself is deterministic and
    hash-stable so ``request_sha256`` (over the payload) is the canonical key.
    """
    grammar = payload["grammar"]
    ops = ", ".join(f"{g['op']}/{g['return_type']}" for g in grammar)
    return (
        "You are an independent program compiler. Compile a single deterministic "
        "question program for the question below using ONLY the given DSL grammar. "
        f"DSL={payload['dsl']}. Operators: {ops}. "
        "Emit ONLY a JSON object: "
        '{"dsl": "<dsl>", "program": <astNode>, '
        '"referent_selector": <astNode|null>, '
        '"required_referent_cardinality": <int|null>}. '
        "An astNode is {op: string, args: [astNode|string|number|boolean], "
        "return_type?: string}. Do not include explanations. "
        f"Payload={_compact_json(payload)}"
    )


def _compact_json(obj: Any) -> str:
    import json

    return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":"))


__all__ = ["C2Candidate", "CompileRequest", "build_compile_request"]