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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
"""Common normalized item schema, content-addressed images, and the eval registry.

Stage 1 of the data pipeline (``docs/02_DATA_PIPELINE.md`` §4) maps every source
row to one immutable :class:`NormalizedItem` matching
``schemas/normalized_item.schema.json``. The canonical ``base_id`` is the
content-addressed hash of ``docs/02`` §3.1 (source identity + question +
choices + image family); ``question_sha256`` / ``choices_sha256`` are over the
exact UTF-8 source bytes (the model input string is never normalized). Images
are content-addressed by their SHA-256 so the same bytes are stored once and
referenced by hash from any mount.

Stage 0 (``docs/02`` §3) freezes the evaluation registry
(``evaluation_items.v1.jsonl``) *before* any training source is touched. The
registry is write-once: a second freeze that would change its bytes is a hard
failure, never a silent overwrite.
"""

from __future__ import annotations

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

from ..atomic_io import JsonlAppender, atomic_write_bytes, atomic_write_jsonl, read_jsonl
from ..hashing import (
    base_id as compute_base_id,
)
from ..hashing import (
    canonical_json,
    choices_sha256,
    sha256_bytes,
)
from ..hashing import (
    image_family_sha256 as compute_image_family_sha256,
)
from ..hashing import question_sha256 as compute_question_sha256
from ..paths import repo_root
from ..schema_io import load_schema, validate

SCHEMA_VERSION = 2

AnswerType = Literal["multiple_choice", "integer", "number", "expression", "short_text", "boolean"]
# ADR-0002 normalized-item policies (schemas/normalized_item.schema.json v2).
# C1 rows come from source-native structured worlds (PlotQA, Geometry3K); C2 rows
# are dual-compiled train candidates; untouched rows are retention-eval only;
# blocked rows are held back and never substituted.
Policy = Literal[
    "c1_train_candidate",
    "c1_certified_eval_candidate",
    "c2_train_candidate",
    "untouched_evaluation_only",
    "blocked",
]

# A resolver turns one native image reference (a path/relative name in the raw
# row) into its raw bytes. The importer never opens files itself, so importers
# are unit-testable with an in-memory resolver.
ImageResolver = Callable[[str], bytes]

_NORMALIZED_ITEM_SCHEMA: dict[str, Any] | None = None


class IngestError(ValueError):
    """Raised when a source row violates an ingest invariant.

    Invariants are hard failures (never silently dropped): a non-math MMK12 row
    is source revision drift, not a row to skip.
    """


class RegistryFrozenError(IngestError):
    """Raised when a write-once registry would be changed by a re-freeze."""


def normalized_item_schema() -> dict[str, Any]:
    """Load and cache the compiled ``normalized_item`` JSON Schema."""
    global _NORMALIZED_ITEM_SCHEMA
    if _NORMALIZED_ITEM_SCHEMA is None:
        _NORMALIZED_ITEM_SCHEMA = load_schema(
            repo_root() / "schemas" / "normalized_item.schema.json"
        )
    return _NORMALIZED_ITEM_SCHEMA


def validate_normalized_item(row: Mapping[str, Any]) -> None:
    """Raise :class:`IngestError` if ``row`` violates the normalized item schema."""
    errors = validate(dict(row), normalized_item_schema())
    if errors:
        raise IngestError("normalized item failed schema validation: " + "; ".join(errors))


# --- content-addressed image store -----------------------------------------


def _ext_for(data: bytes) -> str:
    """Infer a file extension from image bytes (PNG/JPEG), else ``bin``."""
    if data.startswith(b"\x89PNG\r\n\x1a\n"):
        return "png"
    if data.startswith(b"\xff\xd8\xff"):
        return "jpg"
    return "bin"


@dataclass
class ImageStore:
    """Store image bytes content-addressed under ``<output>/images/<sha>.<ext>``.

    The same bytes are written once; repeat stores are a no-op. Paths are
    returned relative to ``base_dir`` so artifacts reproduce across mounts.
    """

    base_dir: Path

    def __post_init__(self) -> None:
        (self.base_dir / "images").mkdir(parents=True, exist_ok=True)

    def store(self, data: bytes) -> tuple[str, str]:
        """Store ``data``; return ``(relative_path, sha256)``."""
        digest = sha256_bytes(data)
        ext = _ext_for(data)
        relative = f"images/{digest}.{ext}"
        target = self.base_dir / relative
        if not target.exists():
            atomic_write_bytes(target, data)
        return relative, digest


class DirectoryImageResolver:
    """Resolve native image refs to bytes by reading from a root directory."""

    def __init__(self, root: str | Path) -> None:
        self.root = Path(root)

    def __call__(self, ref: str) -> bytes:
        return (self.root / ref).read_bytes()


# --- normalized item -------------------------------------------------------


@dataclass(frozen=True)
class Choice:
    """One multiple-choice option in source order."""

    key: str
    text: str

    def to_dict(self) -> dict[str, str]:
        return {"key": self.key, "text": self.text}


@dataclass(frozen=True)
class NormalizedItem:
    """One immutable normalized source row (``docs/02`` §4 schema)."""

    base_id: str
    source: str
    source_revision: str
    source_config: str
    source_split: str
    source_native_id: str
    question: str
    question_sha256: str
    choices: tuple[Choice, ...]
    choices_sha256: str
    answer_raw: str | int | bool
    answer_canonical: str | int | bool
    answer_type: AnswerType
    image_paths: tuple[str, ...]
    image_sha256: tuple[str, ...]
    policy: Policy
    provenance: dict[str, Any]
    subject: str | None = None
    license_gate: str | None = None

    def to_row(self) -> dict[str, Any]:
        """Serialize to the schema-conforming dict written to ``items.jsonl``."""
        row: dict[str, Any] = {
            "schema_version": SCHEMA_VERSION,
            "base_id": self.base_id,
            "source": self.source,
            "source_revision": self.source_revision,
            "source_config": self.source_config,
            "source_split": self.source_split,
            "source_native_id": self.source_native_id,
            "question": self.question,
            "question_sha256": self.question_sha256,
            "choices": [c.to_dict() for c in self.choices],
            "choices_sha256": self.choices_sha256,
            "answer_raw": self.answer_raw,
            "answer_canonical": self.answer_canonical,
            "answer_type": self.answer_type,
            "image_paths": list(self.image_paths),
            "image_sha256": list(self.image_sha256),
            "provenance": dict(self.provenance),
            "policy": self.policy,
        }
        if self.subject is not None:
            row["subject"] = self.subject
        if self.license_gate is not None:
            row["license_gate"] = self.license_gate
        return row


def _native_row_sha256(row: Mapping[str, Any]) -> str:
    """SHA-256 of the native row's canonical JSON (the source-record fingerprint)."""
    return sha256_bytes(canonical_json(dict(row)).encode("utf-8"))


def canonicalize_mc_answer(answer: str, choices: Sequence[Choice]) -> str | int | bool:
    """Map a multiple-choice answer to its choice key when it matches a text.

    Sources disagree on whether the answer is a key (``"B"``) or the option
    text (``"42"``). The canonical form is the choice key when the raw answer
    equals one option's text; otherwise the raw string is preserved.
    """
    text_answer = str(answer).strip()
    for choice in choices:
        if text_answer == str(choice.text).strip():
            return choice.key
    return text_answer


def make_item(
    *,
    source: str,
    source_revision: str,
    source_config: str,
    source_split: str,
    source_native_id: str,
    question: str,
    choices: Sequence[Choice] | Sequence[Mapping[str, str]],
    answer_raw: str | int | bool,
    answer_canonical: str | int | bool,
    answer_type: AnswerType,
    image_paths: Sequence[str],
    image_sha256: Sequence[str],
    policy: Policy,
    native_row: Mapping[str, Any],
    subject: str | None = None,
    license_gate: str | None = None,
    extra_provenance: Mapping[str, Any] | None = None,
) -> NormalizedItem:
    """Build a :class:`NormalizedItem`, computing ``base_id`` and byte hashes.

    ``base_id`` is the content-addressed hash of ``docs/02`` §3.1 —
    sha256(canonical_json({source, source_revision, source_native_id,
    image_family_sha256, question_sha256, choices_sha256})). ``source_config``
    and ``source_split`` are stored on the item but excluded from the ID. The
    native row's canonical-JSON SHA-256 is recorded in provenance so a row can
    be traced back to its source record.
    """
    if not question:
        raise IngestError(f"{source}: question must be non-empty")
    if not image_paths or len(image_paths) != len(image_sha256):
        raise IngestError(
            f"{source}/{source_native_id}: image_paths and image_sha256 must be "
            "parallel non-empty sequences"
        )
    norm_choices = tuple(
        c if isinstance(c, Choice) else Choice(key=str(c["key"]), text=str(c["text"]))
        for c in choices
    )
    q_sha = compute_question_sha256(question)
    c_sha = choices_sha256([{"key": c.key, "text": c.text} for c in norm_choices])
    fam_sha = compute_image_family_sha256(image_sha256)
    bid = compute_base_id(
        source=source,
        source_revision=source_revision,
        source_native_id=source_native_id,
        image_family_sha256=fam_sha,
        question_sha256=q_sha,
        choices_sha256=c_sha,
    )
    provenance: dict[str, Any] = {
        "native_row_json_sha256": _native_row_sha256(native_row),
    }
    if extra_provenance:
        provenance.update(extra_provenance)
    item = NormalizedItem(
        base_id=bid,
        source=source,
        source_revision=source_revision,
        source_config=source_config,
        source_split=source_split,
        source_native_id=str(source_native_id),
        question=question,
        question_sha256=q_sha,
        choices=norm_choices,
        choices_sha256=c_sha,
        answer_raw=answer_raw,
        answer_canonical=answer_canonical,
        answer_type=answer_type,
        image_paths=tuple(image_paths),
        image_sha256=tuple(image_sha256),
        policy=policy,
        provenance=provenance,
        subject=subject,
        license_gate=license_gate,
    )
    validate_normalized_item(item.to_row())
    return item


# --- ingest driver ---------------------------------------------------------


@dataclass
class IngestResult:
    """Summary of one ingest run."""

    source: str
    split: str
    written: int
    dropped: int
    output_path: Path

    @property
    def ok(self) -> bool:
        return self.written > 0 or self.dropped > 0


def write_items(
    output_path: str | Path,
    items: Iterable[NormalizedItem],
    *,
    fsync: bool = True,
) -> int:
    """Atomically write ``items`` as canonical JSONL; return the row count."""
    rows = [item.to_row() for item in items]
    atomic_write_jsonl(output_path, rows, fsync_dir=fsync)
    return len(rows)


def append_items(output_path: str | Path, items: Iterable[NormalizedItem]) -> int:
    """Append items to an existing JSONL with per-record fsync (resume-friendly)."""
    count = 0
    with JsonlAppender(output_path) as appender:
        for item in items:
            appender.append(item.to_row())
            count += 1
    return count


def read_items(path: str | Path) -> Iterator[dict[str, Any]]:
    """Yield parsed normalized-item rows from ``path``."""
    yield from read_jsonl(path)


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


def registry_row(item: NormalizedItem) -> dict[str, Any]:
    """Build one ``evaluation_items.v1.jsonl`` row from a normalized item.

    Fingerprint fields (``image_phash``, ``ocr_minhash_ref``,
    ``question_minhash_ref``) are left ``None`` here and populated by the P3
    ``fingerprint`` stage; the identity + content fields are frozen now.
    """
    return {
        "base_id": item.base_id,
        "source": item.source,
        "source_revision": item.source_revision,
        "config": item.source_config,
        "split": item.source_split,
        "native_id": item.source_native_id,
        "question_sha256": item.question_sha256,
        "choices_sha256": item.choices_sha256,
        "image_sha256": list(item.image_sha256),
        "image_phash": None,
        "ocr_minhash_ref": None,
        "question_minhash_ref": None,
        "policy": item.policy,
    }


def text_registry_row(
    *,
    source: str,
    source_revision: str,
    config: str,
    split: str,
    native_id: str,
    question: str,
    choices: Sequence[Choice] | Sequence[Mapping[str, str]],
    answer_canonical: str | int | bool,
    policy: Policy = "untouched_evaluation_only",
) -> dict[str, Any]:
    """Build a registry row for a text-only eval item (no image, e.g. MMLU-Pro).

    Text-only ``untouched`` probes are retention checks, not intervention
    candidates, so they carry no image fingerprints. They are recorded directly
    in the registry rather than as visual :class:`NormalizedItem` rows.
    """
    norm_choices = tuple(
        c if isinstance(c, Choice) else Choice(key=str(c["key"]), text=str(c["text"]))
        for c in choices
    )
    q_sha = compute_question_sha256(question)
    c_sha = choices_sha256([{"key": c.key, "text": c.text} for c in norm_choices])
    # Text-only probes carry no images: their image family is the empty set.
    fam_sha = compute_image_family_sha256([])
    return {
        "base_id": compute_base_id(
            source=source,
            source_revision=source_revision,
            source_native_id=native_id,
            image_family_sha256=fam_sha,
            question_sha256=q_sha,
            choices_sha256=c_sha,
        ),
        "source": source,
        "source_revision": source_revision,
        "config": config,
        "split": split,
        "native_id": str(native_id),
        "question_sha256": q_sha,
        "choices_sha256": c_sha,
        "image_sha256": [],
        "image_phash": None,
        "ocr_minhash_ref": None,
        "question_minhash_ref": None,
        "policy": policy,
        "answer_canonical": answer_canonical,
    }


@dataclass(frozen=True)
class FrozenRegistry:
    """A write-once evaluation registry on disk."""

    path: Path
    sha256: str
    row_count: int


def _registry_rows_keyed(rows: Iterable[Mapping[str, Any]]) -> dict[str, dict[str, Any]]:
    return {str(r["base_id"]): dict(r) for r in rows}


def freeze_registry(
    output_path: str | Path,
    rows: Sequence[Mapping[str, Any]],
    *,
    force: bool = False,
    resume: bool = False,
) -> FrozenRegistry:
    """Write the evaluation registry write-once; return its hash and row count.

    If the registry already exists:
      - ``force`` overwrites it atomically.
      - ``resume`` succeeds only if the existing rows are byte-identical to the
        computed rows (idempotent re-freeze); a mismatch raises
        :class:`RegistryFrozenError`.
      - otherwise the existing file is left untouched and a
        :class:`RegistryFrozenError` is raised.
    """
    path = Path(output_path)
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists():
        if not force and not resume:
            raise RegistryFrozenError(
                f"evaluation registry already frozen at {path}; "
                "use --force to overwrite or --resume to verify"
            )
        if resume:
            existing = _registry_rows_keyed(read_jsonl(path))
            computed = _registry_rows_keyed(rows)
            if existing != computed:
                raise RegistryFrozenError(
                    f"evaluation registry at {path} differs from the computed "
                    "freeze; refusing to overwrite a frozen registry"
                )
            return _hash_registry(path)
    atomic_write_jsonl(path, rows)
    return _hash_registry(path)


def _hash_registry(path: str | Path) -> FrozenRegistry:
    from ..hashing import sha256_file

    rows = list(read_jsonl(path))
    return FrozenRegistry(path=Path(path), sha256=sha256_file(path), row_count=len(rows))


# --- helpers shared by importers -------------------------------------------


def infer_open_answer_type(answer: str) -> AnswerType:
    """Classify an open-ended answer string as integer/number/short_text."""
    text = str(answer).strip()
    if text.lstrip("-+").isdigit():
        return "integer"
    try:
        float(text)
    except ValueError:
        return "short_text"
    return "number"


def mc_choices(texts: Sequence[str], *, keys: Sequence[str] | None = None) -> list[Choice]:
    """Build lettered choices (A, B, C, ...) from option texts in source order."""
    if keys is None:
        keys = [chr(ord("A") + i) for i in range(len(texts))]
    if len(keys) != len(texts):
        raise IngestError(f"choices/keys length mismatch: {len(keys)} keys vs {len(texts)} texts")
    return [Choice(key=k, text=str(t)) for k, t in zip(keys, texts, strict=True)]