"""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///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 ``/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 ``/..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 ``.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 ``/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", ]