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
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
"""Grouped data and pinned-TRL contracts for EVI-PO.

EVI-PO never exposes intervention labels to the model.  The labels below are
loader-side relationships used to bind four independently rendered prompts:

``FULL(I0, a)``, ``CONTROL(Ic, a)``, and
``MISSING(Im, <UNANSWERABLE>)`` are mandatory. ``SUBSTITUTE(Id, a')`` is
optional because real-image sources such as GQA do not have a certified
answer-changing edit.

The evidence target is not a changed-pixel heuristic.  It is the executor's
dependency-node trace projected through the renderer's lossless node map.  The
trainer later projects that pixel ownership mask onto the processor's visual
token grid.
"""

from __future__ import annotations

import copy
import inspect
import json
from collections import defaultdict
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from ..certificates.build import certificate_id
from ..hashing import canonical_json_hash
from ..renderers.node_map import decode_uint32_png
from .answers import UNANSWERABLE_TOKEN
from .slots import ComparisonSlot
from .targets import ours_target, target_text

EVI_PO_ADAPTER_VERSION = "evi_po_on_trl_1.9.1_v1"
EVI_RELATION_ORDER = ("FULL", "CONTROL", "SUBSTITUTE", "MISSING")
EVI_REQUIRED_RELATIONS = ("FULL", "CONTROL", "MISSING")

_RELATION_CONTRACT = {
    "FULL": ("FULL", "POSITIVE"),
    "CONTROL": ("A_SAME", "CONTROL"),
    "SUBSTITUTE": ("A_CHANGED", "SUBSTITUTE"),
    "MISSING": ("U_MISSING", "TARGET_EVIDENCE"),
}


class EVIContractError(ValueError):
    """Raised when grouped data cannot support the registered EVI-PO loss."""


@dataclass(frozen=True)
class EVIGroupContract:
    """One complete, question-identical four-view EVI-PO relationship."""

    group_id: str
    base_id: str
    question: str
    answer_type: str
    choices: tuple[dict[str, Any], ...]
    full_answer: str
    substitute_answer: str | None
    relations: tuple[tuple[str, ComparisonSlot], ...]

    @property
    def candidates(self) -> tuple[str, ...]:
        """Finite candidate support used by the FULL/CONTROL JS term."""

        values = [self.full_answer]
        if self.substitute_answer is not None:
            values.append(self.substitute_answer)
        values.append(UNANSWERABLE_TOKEN)
        return tuple(values)

    def relation(self, name: str) -> ComparisonSlot:
        try:
            return dict(self.relations)[name]
        except KeyError:
            raise EVIContractError(f"group {self.group_id}: missing EVI relation {name}") from None


def build_evi_group_contracts(
    slots: Iterable[ComparisonSlot],
) -> dict[str, EVIGroupContract]:
    """Group persisted comparison slots and enforce the EVI relationship.

    ``U_INVALID`` and any future independently scored views may remain in the
    comparison schedule, but they do not replace one of the four directional
    relationship members.
    """

    by_group: dict[str, list[ComparisonSlot]] = defaultdict(list)
    for slot in slots:
        by_group[slot.group_id].append(slot)
    if not by_group:
        raise EVIContractError("cannot build EVI groups from an empty slot sequence")

    grouped: dict[str, EVIGroupContract] = {}
    for group_id, group_slots in by_group.items():
        first = group_slots[0]
        relation_slots: dict[str, ComparisonSlot] = {}
        first_full_hash = canonical_json_hash(first.full_view)
        first_choices_hash = canonical_json_hash(list(first.choices))
        for slot in group_slots:
            if (
                slot.base_id != first.base_id
                or slot.question != first.question
                or slot.answer_type != first.answer_type
                or canonical_json_hash(list(slot.choices)) != first_choices_hash
                or canonical_json_hash(slot.full_view) != first_full_hash
                or target_text(slot.full_answer) != target_text(first.full_answer)
            ):
                raise EVIContractError(
                    f"group {group_id}: prompt, answer, or FULL-view identity drift"
                )
            state = str(slot.selected_view.get("state", ""))
            role = str(slot.selected_view.get("role", ""))
            for relation, expected in _RELATION_CONTRACT.items():
                if (state, role) != expected:
                    continue
                if relation in relation_slots:
                    raise EVIContractError(
                        f"group {group_id}: multiple {relation} relationship views"
                    )
                relation_slots[relation] = slot

        missing = [name for name in EVI_REQUIRED_RELATIONS if name not in relation_slots]
        if missing:
            raise EVIContractError(
                f"group {group_id}: incomplete EVI relationship; missing {', '.join(missing)}"
            )
        full_answer = target_text(first.full_answer)
        if ours_target(relation_slots["FULL"].selected_view, first.full_answer) != full_answer:
            raise EVIContractError(f"group {group_id}: FULL target differs from group answer")
        if ours_target(relation_slots["CONTROL"].selected_view, first.full_answer) != full_answer:
            raise EVIContractError(f"group {group_id}: CONTROL target differs from FULL")
        substitute_answer: str | None = None
        if "SUBSTITUTE" in relation_slots:
            substitute_answer = ours_target(
                relation_slots["SUBSTITUTE"].selected_view,
                first.full_answer,
            )
            if substitute_answer in {full_answer, UNANSWERABLE_TOKEN}:
                raise EVIContractError(
                    f"group {group_id}: SUBSTITUTE target is not a distinct concrete answer"
                )
        if (
            ours_target(relation_slots["MISSING"].selected_view, first.full_answer)
            != UNANSWERABLE_TOKEN
        ):
            raise EVIContractError(f"group {group_id}: MISSING target is not unanswerable")
        grouped[group_id] = EVIGroupContract(
            group_id=group_id,
            base_id=first.base_id,
            question=first.question,
            answer_type=first.answer_type,
            choices=tuple(copy.deepcopy(first.choices)),
            full_answer=full_answer,
            substitute_answer=substitute_answer,
            relations=tuple(
                (name, relation_slots[name])
                for name in EVI_RELATION_ORDER
                if name in relation_slots
            ),
        )
    return grouped


def _load_object(path: Path, label: str) -> dict[str, Any]:
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise EVIContractError(f"cannot read {label} {path}: {exc}") from exc
    if not isinstance(value, dict):
        raise EVIContractError(f"{label} must be an object: {path}")
    return value


def _inside(root: Path, path: Path, label: str) -> Path:
    resolved_root = root.resolve()
    resolved = path.resolve()
    try:
        resolved.relative_to(resolved_root)
    except ValueError as exc:
        raise EVIContractError(f"{label} escapes dataset root: {path}") from exc
    return resolved


def evidence_spec_for_view(
    view: Mapping[str, Any],
    *,
    dataset_root: str | Path,
) -> dict[str, Any]:
    """Resolve and verify the certificate/node-map inputs for evidence loss.

    Every returned spec carries ``evidence_available``: ``True`` when the
    certified trace projects to at least one source pixel, ``False`` when the
    artifacts are well-formed but the dependency node has no visible footprint
    (a structural property of some GQA/CLEVR renders — the executor depends on
    a node that occupies zero pixels in the lossless node map). A spec with
    ``evidence_available=False`` is a graceful per-group skip signal: the
    trainer drops that group's evidence term while keeping its answer and
    direction terms, so every arm still trains on the same slot set.

    A *total* absence of evidence artifacts (no node map, no source mask, no
    annotation boxes) still fails closed — that is a data defect, not a
    renderable-but-empty trace.
    """

    root = Path(dataset_root).resolve()
    images = view.get("images")
    if not isinstance(images, list) or len(images) != 1 or not isinstance(images[0], Mapping):
        raise EVIContractError("EVI evidence projection requires exactly one image per view")
    raw_image = images[0].get("path")
    if not isinstance(raw_image, str) or not raw_image:
        raise EVIContractError("EVI view image path is missing")
    relative = Path(raw_image)
    if relative.is_absolute() or ".." in relative.parts or "\\" in raw_image:
        raise EVIContractError(f"unsafe EVI image path: {raw_image!r}")
    image_path = _inside(root, root / relative, "EVI image")
    if not image_path.is_file():
        raise EVIContractError(f"EVI image is missing: {image_path}")
    image_width = int(images[0].get("width", 0))
    image_height = int(images[0].get("height", 0))
    if image_width <= 0 or image_height <= 0:
        raise EVIContractError("EVI image dimensions are invalid")

    artifact_dir = image_path.parent
    certificate_path = _inside(root, artifact_dir / "certificate.json", "certificate")
    manifest_path = _inside(root, artifact_dir / "render_manifest.json", "render manifest")
    node_map_path = _inside(root, artifact_dir / "node_map.uint32.png", "node map")
    structured_paths = (certificate_path, manifest_path, node_map_path)
    if all(path.is_file() for path in structured_paths):
        certificate = _load_object(certificate_path, "certificate")
        manifest = _load_object(manifest_path, "render manifest")
        if (
            certificate.get("certificate_id") != view.get("certificate_id")
            or certificate_id(certificate) != certificate.get("certificate_id")
            or certificate.get("view_id") != view.get("view_id")
        ):
            raise EVIContractError(f"view {view.get('view_id')}: certificate identity mismatch")
        program = certificate.get("program")
        dependency_ids = (
            program.get("dependency_node_ids") if isinstance(program, Mapping) else None
        )
        if (
            not isinstance(dependency_ids, list)
            or not dependency_ids
            or any(not isinstance(node_id, str) or not node_id for node_id in dependency_ids)
        ):
            raise EVIContractError(
                f"view {view.get('view_id')}: certificate has no executor dependency trace"
            )
        node_table = manifest.get("node_table")
        if (
            not isinstance(node_table, list)
            or not node_table
            or node_table[0] != "__background__"
            or any(not isinstance(node_id, str) for node_id in node_table)
        ):
            raise EVIContractError(f"view {view.get('view_id')}: malformed node table")

        try:
            owners = decode_uint32_png(node_map_path.read_bytes())
            import numpy as np

            owner_indices = [
                node_table.index(node_id) for node_id in dependency_ids if node_id in node_table
            ]
            evidence_pixels = int(np.isin(owners, owner_indices).sum()) if owner_indices else 0
            height, width = (int(value) for value in owners.shape)
        except (OSError, TypeError, ValueError) as exc:
            raise EVIContractError(
                f"view {view.get('view_id')}: cannot decode executor evidence mask: {exc}"
            ) from exc
        if (
            (width, height) != (image_width, image_height)
            or manifest.get("width") != width
            or manifest.get("height") != height
        ):
            raise EVIContractError(f"view {view.get('view_id')}: node-map/image dimensions differ")
        return {
            "schema_version": 1,
            "source": "executor_dependency_nodes_projected_through_node_map",
            "certificate_path": str(certificate_path),
            "certificate_id": str(certificate["certificate_id"]),
            "render_manifest_path": str(manifest_path),
            "render_manifest_sha256": view.get("render_manifest_sha256"),
            "node_map_path": str(node_map_path),
            "node_map_sha256": manifest.get("node_map_sha256"),
            "dependency_node_ids": list(dependency_ids),
            "node_table": list(node_table),
            "width": width,
            "height": height,
            "positive_pixel_count": evidence_pixels,
            "evidence_available": evidence_pixels > 0,
        }
    if any(path.exists() for path in structured_paths):
        raise EVIContractError(
            f"view {view.get('view_id')}: structured evidence artifacts are incomplete"
        )

    # Real-image sources can carry a source-native binary evidence mask.
    raw_mask_path = view.get("evidence_mask_path", images[0].get("evidence_mask_path"))
    raw_mask_sha = view.get("evidence_mask_sha256", images[0].get("evidence_mask_sha256"))
    if isinstance(raw_mask_path, str) and raw_mask_path:
        relative_mask = Path(raw_mask_path)
        if relative_mask.is_absolute() or ".." in relative_mask.parts or "\\" in raw_mask_path:
            raise EVIContractError(f"unsafe evidence-mask path: {raw_mask_path!r}")
        mask_path = _inside(root, root / relative_mask, "evidence mask")
        if not mask_path.is_file():
            raise EVIContractError(f"view {view.get('view_id')}: evidence mask is missing")
        try:
            import numpy as np
            from PIL import Image

            with Image.open(mask_path) as mask_image:
                mask = np.asarray(mask_image.convert("L")) > 0
            height, width = (int(value) for value in mask.shape)
            evidence_pixels = int(mask.sum())
        except (OSError, TypeError, ValueError) as exc:
            raise EVIContractError(
                f"view {view.get('view_id')}: cannot decode explicit evidence mask: {exc}"
            ) from exc
        if (width, height) != (image_width, image_height):
            raise EVIContractError(
                f"view {view.get('view_id')}: evidence-mask/image dimensions differ"
            )
        return {
            "schema_version": 1,
            "source": "source_annotation_explicit_mask",
            "mask_path": str(mask_path),
            "mask_sha256": raw_mask_sha,
            "width": width,
            "height": height,
            "positive_pixel_count": evidence_pixels,
            "evidence_available": evidence_pixels > 0,
        }

    # Or it can carry one or more source-annotation boxes in source pixels.
    raw_regions = view.get("regions")
    annotation_regions: list[dict[str, Any]] = []
    width = image_width
    height = image_height
    if isinstance(raw_regions, list):
        for region in raw_regions:
            if not isinstance(region, Mapping) or region.get("source") != "source_annotation":
                continue
            bbox = region.get("bbox_xyxy")
            if (
                region.get("image_index") != 0
                or not isinstance(bbox, list)
                or len(bbox) != 4
                or any(
                    isinstance(value, bool) or not isinstance(value, int | float) for value in bbox
                )
            ):
                raise EVIContractError(
                    f"view {view.get('view_id')}: malformed source evidence region"
                )
            x0, y0, x1, y1 = (float(value) for value in bbox)
            if not (0 <= x0 < x1 <= width and 0 <= y0 < y1 <= height):
                raise EVIContractError(
                    f"view {view.get('view_id')}: source evidence region is out of bounds"
                )
            annotation_regions.append(
                {
                    "region_id": str(region.get("region_id", "")),
                    "bbox_xyxy": [x0, y0, x1, y1],
                }
            )
    if annotation_regions:
        evidence_pixels = int(
            sum(
                (region["bbox_xyxy"][2] - region["bbox_xyxy"][0])
                * (region["bbox_xyxy"][3] - region["bbox_xyxy"][1])
                for region in annotation_regions
            )
        )
        return {
            "schema_version": 1,
            "source": "source_annotation_bboxes",
            "regions": annotation_regions,
            "width": width,
            "height": height,
            "positive_pixel_count": evidence_pixels,
            "evidence_available": evidence_pixels > 0,
        }
    raise EVIContractError(
        f"view {view.get('view_id')}: no executor node map or source-annotation evidence"
    )


def validate_trl_parent_contract(grpo_trainer_class: Any) -> None:
    """Fail when the private TRL methods used by the adapter have drifted."""

    loss_parameters = tuple(inspect.signature(grpo_trainer_class._compute_loss).parameters)
    if loss_parameters != ("self", "model", "inputs"):
        raise RuntimeError(f"unsupported GRPOTrainer._compute_loss signature: {loss_parameters}")
    generation_parameters = tuple(
        inspect.signature(grpo_trainer_class._generate_and_score_completions).parameters
    )
    if generation_parameters != ("self", "inputs"):
        raise RuntimeError(
            "unsupported GRPOTrainer._generate_and_score_completions signature: "
            f"{generation_parameters}"
        )
    preparation_parameters = tuple(inspect.signature(grpo_trainer_class._prepare_inputs).parameters)
    if preparation_parameters != ("self", "generation_batch"):
        raise RuntimeError(
            f"unsupported GRPOTrainer._prepare_inputs signature: {preparation_parameters}"
        )