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
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
"""Per-source importers and the ingest / freeze-eval drivers.

The importer registry maps a resource logical name to its normalization function
(``docs/02_DATA_PIPELINE.md`` §4). Two drivers consume it:

  * :func:`ingest_source` — normalize one *training* source to
    ``normalized/<source>/<split>/items.jsonl``. It hard-refuses MathVista (a
    training-prohibited source) and skips BBox DocVQA when its dual approval
    gate is not cleared, and it requires the evaluation registry to exist first.
  * :func:`freeze_eval` — build and write-once freeze the evaluation registry
    (``evaluation_items.v1.jsonl``) from the evaluation sources, before any
    training ingest runs.
"""

from __future__ import annotations

from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from ..atomic_io import atomic_write_jsonl, read_jsonl
from ..config import ExperimentConfig, ResourcesManifest
from ..hashing import sha256_file
from ..manifests import write_dataset_manifest
from ..vcs import current_code_commit
from . import base, bbox_docvqa, chartqa, eval_sources, mmk12, mmmu, mmr1
from .base import (
    DirectoryImageResolver,
    FrozenRegistry,
    ImageResolver,
    ImageStore,
    IngestError,
    IngestResult,
    NormalizedItem,
    Policy,
    RegistryFrozenError,
    freeze_registry,
    registry_row,
)

# (row, images, resolve, *, revision, split, config) -> NormalizedItem | None
NormalizeFunc = Callable[..., "NormalizedItem | None"]


@dataclass(frozen=True)
class ImporterSpec:
    """One registered source importer."""

    name: str
    normalize: NormalizeFunc
    policy: Policy


TRAIN_IMPORTERS: dict[str, ImporterSpec] = {
    "mmk12": ImporterSpec("mmk12", mmk12.normalize, "c2_train_candidate"),
    "mmr1_rl": ImporterSpec("mmr1_rl", mmr1.normalize, "c2_train_candidate"),
    "mmmu": ImporterSpec("mmmu", mmmu.normalize, "c2_train_candidate"),
    "chartqa": ImporterSpec("chartqa", chartqa.normalize, "c2_train_candidate"),
    "bbox_docvqa_train": ImporterSpec(
        "bbox_docvqa_train", bbox_docvqa.normalize, "c2_train_candidate"
    ),
}

EVAL_VISUAL_IMPORTERS: dict[str, NormalizeFunc] = {
    "mmmu_pro": eval_sources.normalize_mmmu_pro,
    "mathvision": eval_sources.normalize_mathvision,
    "mathvista": eval_sources.normalize_mathvista,
}

TEXT_EVAL_SOURCES = {"mmlu_pro_text"}

# MathVista's card prohibits training; it may only ever be frozen as eval.
FORBIDDEN_TRAIN_SOURCES = frozenset({"mathvista"})
TRAIN_SOURCES = frozenset(TRAIN_IMPORTERS)
EVAL_SOURCES = frozenset(EVAL_VISUAL_IMPORTERS) | TEXT_EVAL_SOURCES


def importer_for(name: str) -> ImporterSpec:
    """Return the train importer registered for ``name``."""
    spec = TRAIN_IMPORTERS.get(name)
    if spec is None:
        raise IngestError(f"no train importer registered for source {name!r}")
    return spec


def read_native_rows(path: str | Path) -> list[dict[str, Any]]:
    """Read native rows from a JSONL file (skipping blank lines)."""
    return [dict(row) for row in read_jsonl(path)]


def ingest_source(
    name: str,
    split: str,
    rows: Sequence[Mapping[str, Any]],
    image_resolver: ImageResolver,
    output_dir: str | Path,
    *,
    revision: str,
    config: str = "default",
    approval: Mapping[str, Mapping[str, Any]] | None = None,
    eval_registry_path: str | Path | None = None,
    require_eval_registry: bool = True,
    config_sha256: str = "",
    created_at: str = "",
) -> IngestResult:
    """Normalize one training source to ``<output_dir>/items.jsonl``.

    Hard failures (nonzero semantics): ingesting a forbidden/eval-only source
    as train (MathVista), a split the importer rejects, or an invariant
    violation. BBox DocVQA with an uncleared gate is a *skip* (zero rows), not
    an error — the core pipeline runs without it.
    """
    if name in FORBIDDEN_TRAIN_SOURCES or name in EVAL_SOURCES:
        raise IngestError(
            f"source {name!r} is evaluation-only and must never be ingested as a training source"
        )
    spec = importer_for(name)

    if name == "bbox_docvqa_train":
        reason = bbox_docvqa.block_reason(approval or {})
        if reason is not None:
            # Disabled source: write an empty items file + manifest noting the skip.
            out = Path(output_dir)
            out.mkdir(parents=True, exist_ok=True)
            items_path = out / "items.jsonl"
            base.write_items(items_path, [])
            _write_ingest_manifest(
                out / "items.manifest.json",
                items_path=items_path,
                source=name,
                split=split,
                row_count=0,
                dropped=0,
                input_manifest_sha256=_registry_sha(eval_registry_path),
                config_sha256=config_sha256,
                created_at=created_at,
                extra={"skipped": True, "skip_reason": reason},
            )
            return IngestResult(name, split, 0, 0, items_path)

    if require_eval_registry and (
        eval_registry_path is None or not Path(eval_registry_path).exists()
    ):
        raise IngestError(
            "evaluation registry must be frozen before any training ingest "
            "(run `explicit-data freeze-eval` first, or pass --no-require-eval-registry)"
        )

    out = Path(output_dir)
    out.mkdir(parents=True, exist_ok=True)
    images = ImageStore(out)
    items: list[NormalizedItem] = []
    dropped = 0
    for row in rows:
        result = spec.normalize(
            row, images, image_resolver, revision=revision, split=split, config=config
        )
        if result is None:
            dropped += 1
            continue
        items.append(result)

    items_path = out / "items.jsonl"
    base.write_items(items_path, items)
    _write_ingest_manifest(
        out / "items.manifest.json",
        items_path=items_path,
        source=name,
        split=split,
        row_count=len(items),
        dropped=dropped,
        input_manifest_sha256=_registry_sha(eval_registry_path),
        config_sha256=config_sha256,
        created_at=created_at,
    )
    return IngestResult(name, split, len(items), dropped, items_path)


def _registry_sha(path: str | Path | None) -> str | None:
    if path is None or not Path(path).exists():
        return None
    return sha256_file(path)


def ingest_structured_source(
    name: str,
    split: str,
    raw_dir: str | Path,
    output_dir: str | Path,
    *,
    revision: str,
    source_config: Mapping[str, Any] | None = None,
    expected_sha256: Mapping[str, str] | None = None,
    eval_registry_path: str | Path | None = None,
    require_eval_registry: bool = True,
    config_sha256: str = "",
    created_at: str = "",
) -> IngestResult:
    """Normalize one C1 structured source (PlotQA/Geometry3K) to ``items.jsonl``.

    The structured path reads from a materialized ``raw_dir``. If the split's
    artifacts are absent, ``adapter.materialize`` fetches them (idempotent,
    sha256-verified); a blocked or missing artifact raises
    :class:`~explicit_learning.sources.base.AdapterError` — never a silent skip
    and never a substitute source. Train/validation splits carry
    ``c1_train_candidate`` and require the evaluation registry to be frozen
    first (mirroring :func:`ingest_source`); the test split
    (``c1_certified_eval_candidate``) is eval and skips that gate — certified-eval
    is generated later by ``build-certified-eval`` (P3).
    """
    from ..sources import ADAPTERS
    from ..sources.base import AdapterError

    if name not in ADAPTERS:
        raise IngestError(f"no structured-source adapter registered for {name!r}")
    adapter_cls = ADAPTERS[name]
    raw_dir = Path(raw_dir)
    out = Path(output_dir)
    out.mkdir(parents=True, exist_ok=True)

    is_train = split in ("train", "validation")
    if (
        is_train
        and require_eval_registry
        and (eval_registry_path is None or not Path(eval_registry_path).exists())
    ):
        raise IngestError(
            "evaluation registry must be frozen before any training ingest "
            "(run `explicit-data freeze-eval` first, or pass --no-require-eval-registry)"
        )

    if not adapter_cls.is_materialized(raw_dir, split):
        try:
            adapter_cls.materialize(
                raw_dir,
                split,
                source_config=source_config or {},
                expected_sha256=expected_sha256,
            )
        except AdapterError as exc:
            raise IngestError(
                f"structured source {name!r} could not be materialized: {exc}"
            ) from exc

    store = ImageStore(out)
    adapter = adapter_cls(raw_dir, store, revision=revision)
    items: list[NormalizedItem] = []
    for raw in adapter.iter_base_items(split):
        items.append(adapter.normalize(raw))

    items_path = out / "items.jsonl"
    base.write_items(items_path, items)
    _write_ingest_manifest(
        out / "items.manifest.json",
        items_path=items_path,
        source=name,
        split=split,
        row_count=len(items),
        dropped=0,
        input_manifest_sha256=_registry_sha(eval_registry_path) if is_train else None,
        config_sha256=config_sha256,
        created_at=created_at,
        extra={"certificate_tier": "C1_SOURCE_NATIVE"},
    )
    return IngestResult(name, split, len(items), 0, items_path)


def _write_ingest_manifest(
    output_path: Path,
    *,
    items_path: Path,
    source: str,
    split: str,
    row_count: int,
    dropped: int,
    input_manifest_sha256: str | None,
    config_sha256: str,
    created_at: str,
    extra: Mapping[str, Any] | None = None,
) -> None:
    record_extra: dict[str, Any] = {
        "source": source,
        "split": split,
        "dropped": dropped,
        "input_manifest_sha256": input_manifest_sha256,
        "code_commit": current_code_commit(),
        "config_sha256": config_sha256 or None,
        "created_at": created_at or None,
    }
    if extra:
        record_extra.update(extra)
    write_dataset_manifest(
        output_path=output_path,
        dataset_name=f"{source}.{split}",
        items_path=items_path,
        extra=record_extra,
    )


# --- evaluation registry freeze -------------------------------------------


@dataclass(frozen=True)
class EvalSourceSpec:
    """One evaluation source to freeze, with its config and split.

    ADR-0002 freezes only the *untouched* retention registry (MMMU-Pro,
    MathVision, MathVista, MMLU-Pro) before any training ingest. The certified
    intervention eval (PlotQA/Geometry3K test) is generated later by
    ``build-certified-eval``, not by this freeze. ``from_gold`` is retained for
    callers that pin a split verbatim; the default freeze path carries an
    implicit ``test`` placeholder that the caller resolves to the source's real
    freeze split via :func:`default_split_for`.
    """

    name: str
    config: str
    split: str
    from_gold: bool = False


def eval_freeze_plan(experiment: ExperimentConfig) -> list[EvalSourceSpec]:
    """Build the ordered, de-duplicated list of untouched evaluation sources to freeze.

    ADR-0002 freezes only the *untouched* retention registry (MMMU-Pro,
    MathVision, MathVista, MMLU-Pro) before any training ingest. The certified
    intervention eval (PlotQA/Geometry3K test) is generated later by
    ``build-certified-eval``, not by this freeze. Each spec's real freeze split
    is resolved by the caller via :func:`default_split_for`.
    """
    specs: dict[str, EvalSourceSpec] = {}
    for name in experiment.data.evaluation.get("untouched", []):
        # Untouched text/visual probe: default split resolved by the caller.
        specs[name] = EvalSourceSpec(name=name, config="default", split="test")
    return list(specs.values())


def default_split_for(name: str, resources: ResourcesManifest) -> str:
    """Pick the freeze split for an untouched source from its resource metadata."""
    if name not in resources.datasets:
        return "test"
    splits = resources.datasets[name].splits or {}
    for candidate in ("testmini", "test", "validation"):
        if candidate in splits:
            return candidate
    # No conventional eval split key present (e.g. MMMU-Pro records a per-config
    # count under "test_per_config" rather than a real HF split name). The
    # canonical untouched freeze split is "test"; never return a count-style
    # pseudo-key, which the importers would reject.
    return "test"


def freeze_eval(
    plan: Sequence[EvalSourceSpec],
    resources: ResourcesManifest,
    *,
    rows_dir: str | Path,
    image_root: str | Path | None,
    output_path: str | Path,
    force: bool = False,
    resume: bool = False,
) -> FrozenRegistry:
    """Build and write-once freeze the evaluation registry.

    For each eval source, native rows are read from
    ``<rows_dir>/<source>.<split>.jsonl``. Visual sources go through their
    importer; text MMLU-Pro is recorded as a text registry row. The combined,
    base_id-sorted rows are written once.

    A companion ``<registry>.items.jsonl`` of the *full* normalized eval items
    (text + ``image_paths``) is written beside the write-once registry so the P3
    ``fingerprint`` stage can compute text and pixel fingerprints for eval — the
    frozen registry itself carries only hashes, not the text needed for MinHash.
    Eval images are content-addressed under ``<registry_dir>/eval_images`` so a
    single image root serves every eval source.
    """
    rows_dir = Path(rows_dir)
    registry_path = Path(output_path)
    eval_images_dir = registry_path.parent / "eval_images"
    resolver = DirectoryImageResolver(image_root) if image_root else None
    store = ImageStore(eval_images_dir)
    registry_rows: list[dict[str, Any]] = []
    eval_item_rows: list[dict[str, Any]] = []
    for spec in plan:
        revision = resources.datasets[spec.name].revision
        rows_path = rows_dir / f"{spec.name}.{spec.split}.jsonl"
        if not rows_path.exists():
            raise IngestError(f"missing native rows for eval source {spec.name!r}: {rows_path}")
        rows = read_native_rows(rows_path)
        if spec.name in TEXT_EVAL_SOURCES:
            for row in rows:
                reg = eval_sources.registry_row_mmlu_pro_text(
                    row, revision=revision, split=spec.split, config=spec.config
                )
                registry_rows.append(reg)
                choices = base.mc_choices([str(o) for o in row["options"]])
                eval_item_rows.append(
                    {
                        "schema_version": base.SCHEMA_VERSION,
                        "base_id": reg["base_id"],
                        "source": reg["source"],
                        "source_revision": reg["source_revision"],
                        "source_config": reg["config"],
                        "source_split": reg["split"],
                        "source_native_id": reg["native_id"],
                        "question": str(row["question"]),
                        "choices": [c.to_dict() for c in choices],
                        "choices_sha256": reg["choices_sha256"],
                        "question_sha256": reg["question_sha256"],
                        "image_paths": [],
                        "image_sha256": [],
                        "answer_raw": str(row["answer"]),
                        "answer_canonical": reg["answer_canonical"],
                        "answer_type": "multiple_choice",
                        "policy": reg["policy"],
                        "provenance": {},
                        "subject": str(row.get("subject") or "unknown"),
                        "license_gate": None,
                    }
                )
            continue
        normalize = EVAL_VISUAL_IMPORTERS[spec.name]
        if resolver is None:
            raise IngestError(f"visual eval source {spec.name!r} requires --image-root")
        for row in rows:
            item = normalize(
                row, store, resolver, revision=revision, split=spec.split, config=spec.config
            )
            if item is None:
                raise IngestError(
                    f"eval importer for {spec.name!r} dropped a row; eval sources "
                    "must never be filtered at freeze time"
                )
            registry_rows.append(registry_row(item))
            eval_item_rows.append(item.to_row())
    registry_rows.sort(key=lambda r: str(r["base_id"]))
    frozen = freeze_registry(output_path, registry_rows, force=force, resume=resume)
    # Companion items file (regenerable, not write-once) for the fingerprint stage.
    companion_path = registry_path.with_name(registry_path.stem + ".items.jsonl")
    eval_item_rows.sort(key=lambda r: str(r["base_id"]))
    atomic_write_jsonl(companion_path, eval_item_rows)
    return frozen


__all__ = [
    "EvalSourceSpec",
    "ImporterSpec",
    "ImageStore",
    "IngestError",
    "IngestResult",
    "NormalizedItem",
    "RegistryFrozenError",
    "EVAL_SOURCES",
    "EVAL_VISUAL_IMPORTERS",
    "FORBIDDEN_TRAIN_SOURCES",
    "TEXT_EVAL_SOURCES",
    "TRAIN_IMPORTERS",
    "TRAIN_SOURCES",
    "base",
    "default_split_for",
    "eval_freeze_plan",
    "freeze_eval",
    "importer_for",
    "ingest_source",
    "ingest_structured_source",
    "read_native_rows",
]