File size: 10,147 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Structured-source adapter protocol and shared fetch helpers (``docs/02`` §4).

A *structured source* is a C1 source whose gold authority is a machine-checkable
certificate built from a structured world (PlotQA, Geometry3K) rather than a
human label. Each source ships an adapter implementing
:class:`StructuredSourceAdapter`:

  * :meth:`iter_base_items` — stream joined native records for one split,
    deterministically ordered, with image bytes attached so ``normalize`` is a
    pure function.
  * :meth:`normalize` — map one raw record to a schema-conforming
    :class:`~explicit_learning.ingest.base.NormalizedItem` (policy
    ``c1_train_candidate`` / ``c1_certified_eval_candidate``).
  * :meth:`build_world` — emit the source's structured world (``plot_world_v1``
    / ``geometry_world_v1``) with channel provenance. P1 builds the *structure*;
    the typed DSL AST (P2) and executor (P3) come later.
  * :meth:`official_answer` — the released/canonical answer (executor-tolerance
    reproduction is a P3 gate, not P1).
  * :meth:`source_certificate_tier` — ``C1_SOURCE_NATIVE`` for both C1 sources.

Fetch helpers here download pinned archives idempotently and verify SHA-256. A
failed fetch is a hard :class:`AdapterError` — a blocked source is skipped, never
substituted (runbook).
"""

from __future__ import annotations

import io
import urllib.request
import zipfile
from collections.abc import Iterator, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal, Protocol, runtime_checkable

from ..hashing import is_sha256, sha256_file
from ..ingest.base import ImageStore, IngestError, NormalizedItem

# A structured world is a plain JSON-serializable mapping (``plot_world_v1`` /
# ``geometry_world_v1``); the typed AST lives in the DSL layer (P2).
World = dict[str, Any]

CertificateTier = Literal["C1_SOURCE_NATIVE", "C2_DUAL_COMPILED"]

# Provenance channel for a world constraint (``docs/02`` §6.2): a fact stated in
# the question/problem text is ``text``; a fact only visible in the diagram is
# ``visual``; stated in both is ``redundant``. Interventions alter only the
# ``visual`` channel, so an executor can still recover the value from ``text``.
Channel = Literal["text", "visual", "redundant"]


class AdapterError(IngestError):
    """Raised when a structured source cannot be fetched or parsed.

    Fetch/parse failures are hard errors: the runbook skips a blocked source
    rather than substituting another, and never fakes success.
    """


@dataclass(frozen=True)
class RawItem:
    """One joined native record ready for :meth:`StructuredSourceAdapter.normalize`.

    ``payload`` is the source-specific joined record (e.g. Geometry3K
    ``data.json`` + annotated logic forms, or PlotQA QA pair + plot annotation).
    ``images`` maps a stable reference name to its raw bytes in source order, so
    ``normalize`` can content-address images through an
    :class:`~explicit_learning.ingest.base.ImageStore` without touching the
    filesystem — keeping adapters unit-testable with in-memory inputs.
    """

    source: str
    split: str
    source_revision: str
    native_id: str
    payload: Mapping[str, Any]
    images: Mapping[str, bytes]


@runtime_checkable
class StructuredSourceAdapter(Protocol):
    """One C1/C2 structured source (``docs/02`` §4)."""

    def __init__(self, raw_dir: Path, store: ImageStore, *, revision: str) -> None: ...

    def iter_base_items(self, split: str) -> Iterator[RawItem]: ...
    def normalize(self, raw: RawItem) -> NormalizedItem: ...
    def build_world(self, item: NormalizedItem) -> World: ...
    def get_or_compile_program(self, item: NormalizedItem) -> Any:
        """Compile the canonical question program (P2 DSL). Not yet implemented."""
        ...

    def official_answer(self, item: NormalizedItem) -> Any: ...
    def source_certificate_tier(self, item: NormalizedItem) -> CertificateTier: ...

    @classmethod
    def is_materialized(cls, raw_dir: Path, split: str) -> bool: ...
    @classmethod
    def materialize(
        cls,
        raw_dir: Path,
        split: str,
        *,
        source_config: Mapping[str, Any],
        expected_sha256: Mapping[str, str] | None = None,
    ) -> Path: ...


# --- fetch helpers ---------------------------------------------------------


def _verify(path: Path, expected_sha256: str | None) -> None:
    if expected_sha256 is None:
        return
    if not is_sha256(expected_sha256):
        raise AdapterError(f"invalid expected sha256 for {path}: {expected_sha256!r}")
    actual = sha256_file(path)
    if actual != expected_sha256:
        raise AdapterError(f"{path} sha256 mismatch: expected {expected_sha256}, got {actual}")


def http_download(
    url: str,
    dst: Path,
    *,
    expected_sha256: str | None = None,
    timeout: float = 120.0,
) -> Path:
    """Download ``url`` to ``dst`` atomically; verify SHA-256 if given.

    Idempotent: an existing file with a matching hash is left untouched. A
    mismatched existing file is re-downloaded. Network/size errors raise
    :class:`AdapterError` (never a silent skip).
    """
    dst = Path(dst)
    if dst.exists() and expected_sha256 is not None:
        try:
            _verify(dst, expected_sha256)
            return dst
        except AdapterError:
            dst.unlink()  # stale/corrupt — re-download
    dst.parent.mkdir(parents=True, exist_ok=True)
    tmp = dst.with_suffix(dst.suffix + ".part")
    try:
        req = urllib.request.Request(url, headers={"User-Agent": "explicit-learning"})
        with (
            urllib.request.urlopen(req, timeout=timeout) as resp,  # noqa: S310
            tmp.open("wb") as handle,
        ):
            while True:
                chunk = resp.read(1 << 20)
                if not chunk:
                    break
                handle.write(chunk)
    except OSError as exc:  # pragma: no cover - network path
        tmp.unlink(missing_ok=True)
        raise AdapterError(f"download failed for {url}: {exc}") from exc
    tmp.replace(dst)
    _verify(dst, expected_sha256)
    return dst


def github_raw_url(repo_id: str, revision: str, path: str) -> str:
    """Build a pinned raw.githubusercontent URL for one file in a repo."""
    return f"https://raw.githubusercontent.com/{repo_id}/{revision}/{path}"


def extract_zip(zip_path: Path, dest_dir: Path) -> Path:
    """Extract ``zip_path`` into ``dest_dir``; return ``dest_dir``.

    Idempotent: extraction is skipped if a marker file recording the archive's
    sha256 already indicates a complete prior extraction.
    """
    zip_path = Path(zip_path)
    dest_dir = Path(dest_dir)
    dest_dir.mkdir(parents=True, exist_ok=True)
    marker = dest_dir / f".{zip_path.stem}.extracted"
    digest = sha256_file(zip_path)
    if marker.exists() and marker.read_text().strip() == digest:
        return dest_dir
    try:
        with zipfile.ZipFile(zip_path) as archive:
            archive.extractall(dest_dir)
    except (zipfile.BadZipFile, OSError) as exc:
        raise AdapterError(f"cannot extract {zip_path}: {exc}") from exc
    marker.write_text(digest)
    return dest_dir


def read_zip_member(zip_path: Path, member: str) -> bytes:
    """Read one member from a zip without extracting the whole archive."""
    try:
        with zipfile.ZipFile(zip_path) as archive, archive.open(member) as handle:
            return handle.read()
    except (KeyError, zipfile.BadZipFile, OSError) as exc:
        raise AdapterError(f"cannot read {member!r} from {zip_path}: {exc}") from exc


def gdrive_download(
    file_id: str,
    dst: Path,
    *,
    expected_sha256: str | None = None,
) -> Path:
    """Download a Google Drive file via ``gdown`` (PlotQA data is Drive-hosted).

    The Drive file id is not git-pinned, so SHA-256 is the integrity anchor and
    is recorded in the ingest manifest. ``gdown`` is imported lazily; its absence
    is a hard :class:`AdapterError`, not a silent skip.
    """
    dst = Path(dst)
    if dst.exists() and expected_sha256 is not None:
        try:
            _verify(dst, expected_sha256)
            return dst
        except AdapterError:
            dst.unlink()
    try:
        import gdown
    except ImportError as exc:  # pragma: no cover - environment path
        raise AdapterError(
            "gdown is required to fetch Google-Drive-hosted sources "
            "(PlotQA); install it into the data venv"
        ) from exc
    dst.parent.mkdir(parents=True, exist_ok=True)
    try:  # pragma: no cover - network path
        gdown.download(id=file_id, output=str(dst), quiet=True, fuzzy=True)
    except Exception as exc:  # noqa: BLE001 - gdown raises varied types
        raise AdapterError(f"gdown download failed for file id {file_id}: {exc}") from exc
    _verify(dst, expected_sha256)
    return dst


def in_memory_zip(members: Mapping[str, bytes]) -> bytes:
    """Build an in-memory zip from ``{member: bytes}`` (for unit-test fixtures)."""
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as archive:
        for name, data in members.items():
            archive.writestr(name, data)
    return buf.getvalue()


def store_images(
    store: ImageStore, images: Mapping[str, bytes]
) -> tuple[tuple[str, ...], tuple[str, ...]]:
    """Content-address every image in source order; return (paths, sha256)."""
    paths: list[str] = []
    shas: list[str] = []
    for _ref, data in images.items():
        rel, sha = store.store(data)
        paths.append(rel)
        shas.append(sha)
    return tuple(paths), tuple(shas)


__all__ = [
    "ADAPTERS",
    "AdapterError",
    "CertificateTier",
    "Channel",
    "RawItem",
    "StructuredSourceAdapter",
    "World",
    "extract_zip",
    "gdrive_download",
    "github_raw_url",
    "http_download",
    "in_memory_zip",
    "read_zip_member",
    "store_images",
]


# Registry is populated by ``sources/__init__.py`` after the concrete adapters
# import their dependencies, to avoid a circular import through this module.
ADAPTERS: dict[str, type[StructuredSourceAdapter]] = {}