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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
545
546
547
"""Training-dataset admission with external group/certificate validation hooks."""

from __future__ import annotations

import copy
import json
from collections.abc import Callable, Iterator, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal

from ..hashing import (
    canonical_json_hash,
    choices_sha256,
    is_sha256,
    question_sha256,
    sha256_file,
)
from ..paths import repo_root
from ..schema_io import load_schema, validate
from .answers import NormalizationError, normalize_answer
from .targets import TargetMappingError, ours_target, target_text

AdmissionKind = Literal["group", "image", "certificate"]


class AdmissionError(ValueError):
    """Raised when an artifact is not safe to expose to a training loader."""


@dataclass(frozen=True)
class AdmissionRequest:
    """One hook invocation for an external schema/certificate validator."""

    kind: AdmissionKind
    group: Mapping[str, Any]
    view: Mapping[str, Any] | None = None
    image: Mapping[str, Any] | None = None
    resolved_path: Path | None = None
    certificate_id: str | None = None


AdmissionValidator = Callable[[AdmissionRequest], bool | None]


@dataclass(frozen=True)
class AdmittedGroup:
    """A deep-copied group that passed core and external admission checks."""

    row: dict[str, Any]
    dataset_root: Path
    canonical_sha256: str

    @property
    def group_id(self) -> str:
        return str(self.row["group_id"])

    @property
    def base_id(self) -> str:
        return str(self.row["base_id"])


def _require_mapping(value: Any, label: str) -> Mapping[str, Any]:
    if not isinstance(value, Mapping):
        raise AdmissionError(f"{label} must be an object")
    return value


def _run_validator(validator: AdmissionValidator, request: AdmissionRequest) -> None:
    try:
        accepted = validator(request)
    except AdmissionError:
        raise
    except Exception as exc:
        raise AdmissionError(f"{request.kind} validator failed: {exc}") from exc
    if accepted is False:
        raise AdmissionError(f"{request.kind} validator rejected artifact")


def _safe_image_path(raw_path: Any) -> Path:
    if not isinstance(raw_path, str):
        raise AdmissionError(f"unsafe image path: {raw_path!r}")
    text = raw_path
    relative = Path(text)
    if (
        not text
        or relative.is_absolute()
        or ".." in relative.parts
        or "\\" in text
        or relative.parts[0].endswith(":")
    ):
        raise AdmissionError(f"unsafe image path: {text!r}")
    return relative


def _resolve_image(root: Path, raw_path: Any) -> Path:
    relative = _safe_image_path(raw_path)
    text = str(raw_path)
    root_resolved = root.resolve()
    candidate = (root_resolved / relative).resolve()
    try:
        candidate.relative_to(root_resolved)
    except ValueError as exc:
        raise AdmissionError(f"image path escapes dataset root: {text!r}") from exc
    if not candidate.is_file():
        raise AdmissionError(f"image file not found: {candidate}")
    return candidate


def _validate_image_decode(path: Path, image_row: Mapping[str, Any]) -> None:
    """Check that a linked raster decodes and has its declared dimensions."""

    from PIL import Image

    try:
        with Image.open(path) as image:
            image.load()
            actual_size = image.size
    except (OSError, ValueError) as exc:
        raise AdmissionError(f"image cannot be decoded: {path}: {exc}") from exc
    expected_size = (image_row.get("width"), image_row.get("height"))
    if actual_size != expected_size:
        raise AdmissionError(
            f"image dimensions differ from annotation: {actual_size} != {expected_size}"
        )


def _load_json_object(path: Path, label: str) -> Mapping[str, Any]:
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise AdmissionError(f"{label} cannot be loaded: {exc}") from exc
    if not isinstance(value, Mapping):
        raise AdmissionError(f"{label} must contain a JSON object")
    return value


def _validate_lightweight_view_artifacts(
    *,
    root: Path,
    group: Mapping[str, Any],
    view: Mapping[str, Any],
    view_dir: Path,
    certificate: Mapping[str, Any],
) -> None:
    """Decode required linked assets and validate state linkage without rehashing."""

    from PIL import Image

    images = view.get("images")
    if not isinstance(images, list) or not images:
        raise AdmissionError("lightweight artifact validation requires an image")
    image_row = _require_mapping(images[0], "image")
    expected_size = (image_row.get("width"), image_row.get("height"))
    required_json = (
        "render_manifest.json",
        "text_manifest.json",
        "world_before.json",
        "world_after.json",
        "program.json",
    )
    parsed = {name: _load_json_object(view_dir / name, name) for name in required_json}
    manifest = parsed["render_manifest.json"]
    if (manifest.get("width"), manifest.get("height")) != expected_size:
        raise AdmissionError("render manifest dimensions differ from the image annotation")

    from ..renderers.base import decode_uint32_png

    try:
        owners = decode_uint32_png((view_dir / "node_map.uint32.png").read_bytes())
    except (OSError, ValueError) as exc:
        raise AdmissionError(f"node map cannot be decoded: {exc}") from exc
    if tuple(reversed(owners.shape)) != expected_size:
        raise AdmissionError("node-map dimensions differ from the image annotation")

    mask_names = ["diff_mask.png"]
    if str(group.get("source")) in {"gqa", "clevr"}:
        mask_names.append("evidence_mask.png")
    for name in mask_names:
        try:
            with Image.open(view_dir / name) as image:
                image.load()
                size = image.size
        except (OSError, ValueError) as exc:
            raise AdmissionError(f"{name} cannot be decoded: {exc}") from exc
        if size != expected_size:
            raise AdmissionError(f"{name} dimensions differ from the image annotation")

    state = str(view.get("state"))
    proof = _require_mapping(certificate.get("proof"), "certificate proof")
    if proof.get("state") != state:
        raise AdmissionError("certificate proof state differs from the group view")
    if certificate.get("base_id") != group.get("base_id"):
        raise AdmissionError("certificate base_id differs from the group")
    if certificate.get("view_id") != view.get("view_id"):
        raise AdmissionError("certificate view_id differs from the group view")
    if state == "U_MISSING" and str(group.get("source")) in {"gqa", "clevr"}:
        for name in ("completion_a.json", "completion_b.json"):
            _load_json_object(view_dir / name, name)
    if str(group.get("source")) == "gqa":
        source_path = view_dir / "source.jpg"
        try:
            with Image.open(source_path) as source_image:
                source_image.load()
        except (OSError, ValueError) as exc:
            raise AdmissionError(f"GQA source image cannot be decoded: {exc}") from exc


def _validate_core_group(
    group: Mapping[str, Any],
) -> tuple[Mapping[str, Any], list[Mapping[str, Any]]]:
    for field in (
        "group_id",
        "base_id",
        "question_sha256",
        "choices_sha256",
        "question",
        "choices",
        "full_answer_canonical",
        "answer_type",
        "views",
    ):
        if field not in group:
            raise AdmissionError(f"group missing {field}")
    for field in ("group_id", "base_id", "question_sha256", "choices_sha256"):
        if not is_sha256(str(group[field])):
            raise AdmissionError(f"group {field} is not a SHA-256")
    if not isinstance(group["question"], str):
        raise AdmissionError("group question must be a string")
    if question_sha256(group["question"]) != group["question_sha256"]:
        raise AdmissionError("group question_sha256 does not match exact question bytes")
    if not isinstance(group["choices"], list):
        raise AdmissionError("group choices must be a list")
    try:
        actual_choices_sha256 = choices_sha256(group["choices"])
    except (KeyError, TypeError) as exc:
        raise AdmissionError(f"group choices are malformed: {exc}") from exc
    if actual_choices_sha256 != group["choices_sha256"]:
        raise AdmissionError("group choices_sha256 does not match canonical choices")
    try:
        normalize_answer(
            group["full_answer_canonical"],
            str(group["answer_type"]),
            choices=group["choices"],
        )
    except NormalizationError as exc:
        raise AdmissionError(f"group full answer is invalid: {exc}") from exc

    raw_views = group["views"]
    if not isinstance(raw_views, list) or len(raw_views) < 2:
        raise AdmissionError("group must contain FULL plus at least one transformed view")
    views = [_require_mapping(view, "view") for view in raw_views]
    full_views = [view for view in views if view.get("state") == "FULL"]
    if len(full_views) != 1:
        raise AdmissionError(f"expected exactly one FULL view, found {len(full_views)}")
    full = full_views[0]

    view_ids = [str(view.get("view_id", "")) for view in views]
    if any(not view_id for view_id in view_ids) or len(view_ids) != len(set(view_ids)):
        raise AdmissionError("view_id values must be non-empty and unique")

    for view in views:
        view_id = str(view["view_id"])
        if view.get("question_sha256") != group["question_sha256"]:
            raise AdmissionError(f"view {view_id}: question hash mismatch")
        if view.get("choices_sha256") != group["choices_sha256"]:
            raise AdmissionError(f"view {view_id}: choices hash mismatch")
        certificate_id = str(view.get("certificate_id", ""))
        if not is_sha256(certificate_id):
            raise AdmissionError(f"view {view_id}: invalid certificate_id")
        audit = _require_mapping(view.get("automated_audit"), f"view {view_id} automated_audit")
        if audit.get("certificate_id") != certificate_id:
            raise AdmissionError(f"view {view_id}: certificate/audit mismatch")

        state = str(view.get("state", ""))
        role = str(view.get("role", ""))
        operator = str(view.get("operator", ""))
        if state == "FULL":
            if role != "POSITIVE" or operator != "NONE":
                raise AdmissionError(f"view {view_id}: FULL must be POSITIVE/NONE")
        else:
            if role == "POSITIVE" or operator == "NONE":
                raise AdmissionError(f"view {view_id}: transformed view has invalid role/operator")
        if role == "CONTROL" and state != "A_SAME":
            raise AdmissionError(f"view {view_id}: CONTROL must be A_SAME")
        if role == "SUBSTITUTE" and operator != "SUBSTITUTE_V1":
            raise AdmissionError(f"view {view_id}: SUBSTITUTE role/operator mismatch")
        if role not in {
            "POSITIVE",
            "CONTROL",
            "TARGET_EVIDENCE",
            "TARGET_REFERENT",
            "SUBSTITUTE",
        }:
            raise AdmissionError(f"view {view_id}: unsupported role {role!r}")
        if group.get("split") == "certified_eval" and view.get("certification_tier") != (
            "C1_SOURCE_NATIVE"
        ):
            raise AdmissionError(f"view {view_id}: certified_eval must be C1")
        try:
            target = ours_target(view, group["full_answer_canonical"])
            normalize_answer(
                target,
                str(group["answer_type"]),
                choices=group["choices"],
            )
        except (NormalizationError, TargetMappingError) as exc:
            raise AdmissionError(f"view {view_id}: {exc}") from exc

    if ours_target(full, group["full_answer_canonical"]) != target_text(
        group["full_answer_canonical"]
    ):
        raise AdmissionError("FULL target mismatch")
    return full, views


def admit_group(
    group: Mapping[str, Any],
    *,
    dataset_root: str | Path,
    validator: AdmissionValidator,
    verify_assets: bool = True,
) -> AdmittedGroup:
    """Admit one group and invoke the external hook for group/image/certificate.

    The callback is mandatory: this layer owns training admission but not JSON
    Schema or certificate replay.  It must therefore receive an affirmative hook
    opportunity for all three artifact kinds.  Core checks are still enforced
    here so a permissive callback cannot bypass prompt/target/image integrity.
    """

    if validator is None:
        raise AdmissionError("an external admission validator callback is required")
    copied = copy.deepcopy(dict(group))
    root = Path(dataset_root)
    _, views = _validate_core_group(copied)
    _run_validator(validator, AdmissionRequest("group", copied))

    for view in views:
        images = view.get("images")
        if not isinstance(images, list) or not images:
            raise AdmissionError(f"view {view['view_id']}: images must be non-empty")
        image_rows = [_require_mapping(image, "image") for image in images]
        indices = [image.get("image_index") for image in image_rows]
        if indices != list(range(len(image_rows))):
            raise AdmissionError(
                f"view {view['view_id']}: image_index must be contiguous and in list order"
            )
        paths: set[str] = set()
        for image in image_rows:
            image_path = str(image.get("path", ""))
            _safe_image_path(image_path)
            if image_path in paths:
                raise AdmissionError(f"view {view['view_id']}: duplicate image path")
            paths.add(image_path)
            expected_sha = str(image.get("sha256", ""))
            if not is_sha256(expected_sha):
                raise AdmissionError(f"view {view['view_id']}: invalid image sha256")
            resolved: Path | None = None
            if verify_assets:
                resolved = _resolve_image(root, image_path)
                if sha256_file(resolved) != expected_sha:
                    raise AdmissionError(f"view {view['view_id']}: image SHA-256 mismatch")
            _run_validator(
                validator,
                AdmissionRequest(
                    "image",
                    copied,
                    view=view,
                    image=image,
                    resolved_path=resolved,
                ),
            )
        certificate_id = str(view["certificate_id"])
        _run_validator(
            validator,
            AdmissionRequest(
                "certificate",
                copied,
                view=view,
                certificate_id=certificate_id,
            ),
        )

    return AdmittedGroup(
        row=copied,
        dataset_root=root.resolve(),
        canonical_sha256=canonical_json_hash(copied),
    )


def _read_jsonl(path: Path) -> Iterator[Mapping[str, Any]]:
    with path.open("r", encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, 1):
            if not line.strip():
                continue
            try:
                value = json.loads(line)
            except json.JSONDecodeError as exc:
                raise AdmissionError(f"{path}:{line_number}: invalid JSON: {exc}") from exc
            if not isinstance(value, Mapping):
                raise AdmissionError(f"{path}:{line_number}: row must be an object")
            yield value


def load_groups(
    path: str | Path,
    *,
    dataset_root: str | Path,
    validator: AdmissionValidator,
    verify_assets: bool = True,
) -> tuple[AdmittedGroup, ...]:
    """Load and admit a non-empty JSONL dataset with unique group/base IDs."""

    source = Path(path)
    if not source.is_file():
        raise AdmissionError(f"group JSONL not found: {source}")
    groups = tuple(
        admit_group(
            row,
            dataset_root=dataset_root,
            validator=validator,
            verify_assets=verify_assets,
        )
        for row in _read_jsonl(source)
    )
    if not groups:
        raise AdmissionError("group JSONL contains no rows")
    group_ids = [group.group_id for group in groups]
    base_ids = [group.base_id for group in groups]
    if len(group_ids) != len(set(group_ids)):
        raise AdmissionError("duplicate group_id in dataset")
    if len(base_ids) != len(set(base_ids)):
        raise AdmissionError("duplicate base_id in dataset")
    return groups


def certified_release_validator(
    dataset_root: str | Path,
    *,
    replayed_view_dirs: frozenset[Path] | None = None,
    replay_certificates: bool = True,
) -> AdmissionValidator:
    """Return the built-in validator for release bundles.

    Group/schema/relationship checks are always enforced.  Expensive byte/hash
    replay is opt-in through ``replay_certificates``; the research release uses
    the lightweight path and only checks that linked images and annotation
    records exist.  The replay path remains available as a debugging tool.
    """
    root = Path(dataset_root).resolve()
    schema = load_schema(repo_root() / "schemas" / "intervention_group.schema.json")

    def _validate(request: AdmissionRequest) -> bool:
        if request.kind == "group":
            errors = validate(dict(request.group), schema)
            if errors:
                raise AdmissionError("group schema failed: " + "; ".join(errors[:3]))
            states = [str(view.get("state")) for view in request.group.get("views", [])]
            source = str(request.group.get("source", ""))
            expected_states = {
                "plotqa": ["FULL", "U_MISSING", "A_CHANGED", "U_INVALID", "A_SAME"],
                "gqa": ["FULL", "A_SAME", "U_MISSING"],
                "clevr": ["FULL", "A_SAME", "A_CHANGED", "U_MISSING"],
            }.get(source)
            if expected_states is None:
                raise AdmissionError(f"unsupported certified source {source!r}")
            if states != expected_states:
                raise AdmissionError(f"{source} release state order/set mismatch: {states!r}")
            quality = _require_mapping(request.group.get("quality"), "group quality")
            if (
                quality.get("certificate_valid") is not True
                or quality.get("model_agreement_is_gold") is not False
            ):
                raise AdmissionError("group quality authority contract failed")
            if request.group.get("split") == "certified_eval":
                if quality.get("reference_executor_agreement") is not True:
                    raise AdmissionError("certified eval lacks reference-executor agreement")
                if not all(
                    view.get("held_out_renderer") is True for view in request.group.get("views", [])
                ):
                    raise AdmissionError("certified eval contains a non-held-out render")
            return True
        if request.kind == "image":
            if request.resolved_path is not None:
                return request.resolved_path.is_file()
            if not replay_certificates and request.image is not None:
                path = _resolve_image(root, request.image.get("path"))
                _validate_image_decode(path, request.image)
                return True
            return False
        if request.kind == "certificate":
            if request.view is None:
                raise AdmissionError("certificate request has no view")
            images = request.view.get("images")
            if not isinstance(images, list) or not images:
                raise AdmissionError("certificate view has no image path")
            relative = _safe_image_path(images[0].get("path"))
            view_dir = (root / relative.parent).resolve()
            try:
                view_dir.relative_to(root)
            except ValueError as exc:
                raise AdmissionError("certificate directory escapes dataset root") from exc
            certificate_path = view_dir / "certificate.json"
            try:
                candidate = json.loads(certificate_path.read_text(encoding="utf-8"))
            except (OSError, json.JSONDecodeError) as exc:
                raise AdmissionError(f"cannot read certificate: {exc}") from exc
            if not isinstance(candidate, Mapping):
                raise AdmissionError("certificate must contain a JSON object")
            if not replay_certificates:
                if candidate.get("certificate_id") != request.certificate_id:
                    raise AdmissionError("certificate link differs from group view")
                _validate_lightweight_view_artifacts(
                    root=root,
                    group=request.group,
                    view=request.view,
                    view_dir=view_dir,
                    certificate=candidate,
                )
                return True
            if replayed_view_dirs is None:
                from ..certificates.evi_core import is_core_certificate, replay_core_view
                from ..certificates.replay import replay_view

                replay = (
                    replay_core_view(view_dir)
                    if isinstance(candidate, Mapping) and is_core_certificate(candidate)
                    else replay_view(view_dir)
                )
                if not replay.ok:
                    raise AdmissionError(
                        "certificate replay failed: " + "; ".join(replay.errors[:3])
                    )
            elif view_dir not in replayed_view_dirs:
                raise AdmissionError("certificate directory lacks a current all-pass replay")
            from ..certificates.build import certificate_id

            if certificate_id(candidate) != request.certificate_id:
                raise AdmissionError("certificate content address differs from group view")
            if candidate.get("certificate_id") != request.certificate_id:
                raise AdmissionError("certificate content ID differs from group view")
            return True
        raise AdmissionError(f"unsupported admission request kind: {request.kind}")

    return _validate