File size: 12,488 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
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
"""Exact-revision resource fetch, approval gating, and snapshot verification.

Implements the download contract in ``docs/01_RESOURCE_CATALOG.md`` §7: every
Hugging Face resource is fetched at a pinned 40-hex revision into a
root-relative directory, then a ``resource_snapshot.jsonl`` row records the
resolved commit, file count, total bytes, and a manifest hash of the sorted
``relative_path\\0size\\0sha256`` list.

Approval semantics (§1): a resource whose gate is still ``blocked`` is skipped
and never silently substituted. A downloaded tree that contains only LFS
pointers, or whose resolved commit differs from the requested revision, is a
preflight failure. ``HF_TOKEN`` is read from the environment and passed to the
download API as a keyword argument — it never appears on a command line, in a
log, or in an exception message.
"""

from __future__ import annotations

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

from .atomic_io import JsonlAppender, read_jsonl
from .config import ResourcesManifest
from .hashing import is_git_revision
from .manifests import FileEntry, resource_snapshot_row, snapshot_file_tree
from .paths import data_root, model_root

# policy/access string -> the pre-download approval gate(s) it requires.
# Resources whose policy is a *usage* constraint (evaluation_only,
# train_human_rows_only, the MMMU eval-id-freeze note, strict eval-only) map to
# no gate here; those constraints are enforced at ingest/eval time, not fetch.
_POLICY_GATES: dict[str, tuple[str, ...]] = {
    "license_clearance_c2_certificate_required_no_redistribution": ("mmk12_license",),
    "composite_terms_decontamination_and_c2_certificate_required": ("mmr1_composite_terms",),
    "disabled_until_storage_and_license_approval": (
        "bbox_docvqa_license",
        "bbox_docvqa_storage",
    ),
    "do_not_mix_with_controlled_main_training": ("baseline_unlicensed_data",),
    "auxiliary_eval_only": ("baseline_unlicensed_data",),
}
# ADR-0002 removed gated-manual-access natural-image models (SAM); no resource
# now carries a manual-access gate, so this map is empty. Retained so a future
# gated access string maps explicitly rather than silently passing.
_ACCESS_GATES: dict[str, tuple[str, ...]] = {}

_LFS_SIGNATURE = b"version https://git-lfs.github.com/spec/v1"

# A downloader takes (ref, allow_patterns, token) and returns the local Path.
Downloader = Callable[["ResourceRef", Sequence[str] | None, str | None], Path]


class ResourceError(RuntimeError):
    """Raised when a resource fetch or verification violates the download contract."""


@dataclass(frozen=True)
class ResourceRef:
    """A resolvable handle to one pinned resource."""

    logical_name: str
    kind: str  # "model" | "dataset"
    role: str
    repo_id: str
    revision: str
    local_path: Path
    required_gates: tuple[str, ...]


def required_gates_for(entry: Any) -> tuple[str, ...]:
    """Return the approval gates a resource entry requires (empty if none)."""
    gates: list[str] = []
    access = getattr(entry, "access", "public") or "public"
    gates.extend(_ACCESS_GATES.get(access, ()))
    policy = getattr(entry, "policy", "") or ""
    gates.extend(_POLICY_GATES.get(policy, ()))
    # Deduplicate while preserving order.
    return tuple(dict.fromkeys(gates))


def plan(resources: ResourcesManifest) -> list[ResourceRef]:
    """Build the fetch plan (one ``ResourceRef`` per model and dataset)."""
    refs: list[ResourceRef] = []
    mroot = model_root()
    droot = data_root()
    for name, entry in resources.models.items():
        refs.append(
            ResourceRef(
                logical_name=name,
                kind="model",
                role=entry.role,
                repo_id=entry.repo_id,
                revision=entry.revision,
                local_path=mroot / name,
                required_gates=required_gates_for(entry),
            )
        )
    for name, dentry in resources.datasets.items():
        refs.append(
            ResourceRef(
                logical_name=name,
                kind="dataset",
                role=dentry.role,
                repo_id=dentry.repo_id,
                revision=dentry.revision,
                local_path=droot / "raw" / name,
                required_gates=required_gates_for(dentry),
            )
        )
    return refs


def load_approval(path: str | Path | None) -> dict[str, dict[str, Any]]:
    """Load ``resource_approval.json`` into a ``gate -> {status, evidence}`` map.

    A missing file means every gate is unresolved (treated as blocked). A present
    but malformed file is an error: a silent ``{}`` would falsely clear gates.
    """
    if path is None:
        return {}
    p = Path(path)
    if not p.exists():
        return {}
    import json

    data = json.loads(p.read_text(encoding="utf-8"))
    if not isinstance(data, dict) or data.get("schema_version") != 1:
        raise ResourceError(f"approval file {p} must have schema_version 1")
    gates = data.get("gates")
    if not isinstance(gates, dict):
        raise ResourceError(f"approval file {p} must contain a 'gates' object")
    return {str(k): v for k, v in gates.items() if isinstance(v, dict)}


def gate_status(approval: dict[str, dict[str, Any]], gate: str) -> str:
    """Return ``approved`` | ``blocked`` | ``missing`` for one gate."""
    entry = approval.get(gate)
    if not isinstance(entry, dict):
        return "missing"
    status = entry.get("status", "missing")
    return status if status in {"approved", "blocked", "missing"} else "missing"


def block_reason(ref: ResourceRef, approval: dict[str, dict[str, Any]]) -> str | None:
    """Return why ``ref`` is blocked, or ``None`` if it is fetchable."""
    unmet = [g for g in ref.required_gates if gate_status(approval, g) != "approved"]
    if not unmet:
        return None
    return f"approval gates not approved: {', '.join(unmet)}"


def is_lfs_pointer(path: str | Path) -> bool:
    """True when ``path`` is a git-lfs pointer file (real blob not downloaded)."""
    try:
        with Path(path).open("rb") as handle:
            head = handle.read(len(_LFS_SIGNATURE) + 64)
    except OSError:
        return False
    return head.startswith(_LFS_SIGNATURE)


def scan_lfs_pointers(root: str | Path) -> list[str]:
    """Return relative paths of LFS pointer files under ``root`` (sorted)."""
    root_path = Path(root)
    pointers: list[str] = []
    if not root_path.exists():
        return pointers
    for path in sorted(root_path.rglob("*")):
        if path.is_file() and is_lfs_pointer(path):
            pointers.append(path.relative_to(root_path).as_posix())
    return pointers


def _tree_stats(root: str | Path) -> tuple[list[FileEntry], int, int]:
    entries = snapshot_file_tree(root)
    total_bytes = sum(e.size for e in entries)
    return entries, len(entries), total_bytes


def snapshot_row_for(ref: ResourceRef, downloaded_at: str) -> dict[str, Any]:
    """Build the ``resource_snapshot.jsonl`` row for an already-downloaded tree.

    Raises :class:`ResourceError` if the tree is missing, contains LFS pointers,
    or is empty (a successful fetch must produce at least one file).
    """
    if not ref.local_path.exists():
        raise ResourceError(f"local tree missing for {ref.logical_name}: {ref.local_path}")
    pointers = scan_lfs_pointers(ref.local_path)
    if pointers:
        raise ResourceError(
            f"LFS pointers (not blobs) downloaded for {ref.logical_name}: {pointers}"
        )
    entries, file_count, total_bytes = _tree_stats(ref.local_path)
    if file_count == 0:
        raise ResourceError(f"downloaded tree for {ref.logical_name} is empty")
    from .manifests import file_tree_manifest_sha256

    manifest_sha256 = file_tree_manifest_sha256(entries)
    return resource_snapshot_row(
        logical_name=ref.logical_name,
        repo_id=ref.repo_id,
        requested_revision=ref.revision,
        resolved_commit=ref.revision,
        local_path=str(ref.local_path),
        downloaded_at=downloaded_at,
        file_count=file_count,
        total_bytes=total_bytes,
        manifest_sha256=manifest_sha256,
        kind=ref.kind,
    )


def append_snapshot_row(snapshot_path: str | Path, row: dict[str, Any]) -> None:
    """Append one snapshot row to ``resource_snapshot.jsonl`` (durable, idempotent-ish)."""
    with JsonlAppender(snapshot_path) as appender:
        appender.append(row)


def default_downloader(
    ref: ResourceRef, allow_patterns: Sequence[str] | None, token: str | None
) -> Path:
    """Fetch ``ref`` at its pinned revision via ``huggingface_hub`` (real network)."""
    from huggingface_hub import snapshot_download

    snapshot_download(
        repo_id=ref.repo_id,
        repo_type=ref.kind,
        revision=ref.revision,
        local_dir=str(ref.local_path),
        allow_patterns=list(allow_patterns) if allow_patterns else None,
        token=token,
    )
    return ref.local_path


def _utc_now() -> str:
    from datetime import UTC, datetime

    return datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")


def fetch_one(
    ref: ResourceRef,
    approval: dict[str, dict[str, Any]],
    *,
    snapshot_path: str | Path,
    allow_patterns: Sequence[str] | None = None,
    downloader: Downloader = default_downloader,
    downloaded_at: str | None = None,
    token: str | None = None,
) -> dict[str, Any]:
    """Fetch one resource, returning ``{"status", ...}`` (fetched | skipped).

    A blocked gate yields a skip with a reason and never calls the downloader. A
    non-40-hex revision, an LFS-pointer-only tree, or a downloader error raises
    :class:`ResourceError`. The token is forwarded to the downloader only.
    """
    if not is_git_revision(ref.revision):
        raise ResourceError(
            f"floating revision rejected for {ref.logical_name}: {ref.revision!r} "
            "(must be a 40-hex commit)"
        )
    reason = block_reason(ref, approval)
    if reason:
        return {"status": "skipped", "logical_name": ref.logical_name, "reason": reason}
    downloader(ref, allow_patterns, token)
    row = snapshot_row_for(ref, downloaded_at or _utc_now())
    append_snapshot_row(snapshot_path, row)
    return {"status": "fetched", "logical_name": ref.logical_name, "row": row}


def latest_snapshot_row(snapshot_path: str | Path, logical_name: str) -> dict[str, Any] | None:
    """Return the most recent snapshot row for ``logical_name``, or ``None``."""
    latest: dict[str, Any] | None = None
    for row in read_jsonl(snapshot_path):
        if row.get("logical_name") == logical_name:
            latest = row
    return latest


def verify_one(
    ref: ResourceRef,
    snapshot_path: str | Path,
) -> dict[str, Any]:
    """Offline-verify a previously fetched resource against its recorded snapshot.

    Recomputes the file-tree manifest from the local tree and compares it to the
    manifest hash recorded at fetch time. A mismatch (content changed), an LFS
    pointer, or a missing recorded row is a verification failure.
    """
    recorded = latest_snapshot_row(snapshot_path, ref.logical_name)
    if recorded is None:
        raise ResourceError(f"no snapshot row recorded for {ref.logical_name}")
    if not ref.local_path.exists():
        raise ResourceError(f"local tree missing for {ref.logical_name}: {ref.local_path}")
    pointers = scan_lfs_pointers(ref.local_path)
    if pointers:
        raise ResourceError(f"LFS pointers present for {ref.logical_name}: {pointers}")
    entries, file_count, total_bytes = _tree_stats(ref.local_path)
    from .manifests import file_tree_manifest_sha256

    manifest_sha256 = file_tree_manifest_sha256(entries)
    ok = (
        manifest_sha256 == recorded.get("manifest_sha256")
        and file_count == recorded.get("file_count")
        and total_bytes == recorded.get("total_bytes")
        and ref.revision == recorded.get("resolved_commit")
    )
    return {
        "logical_name": ref.logical_name,
        "ok": ok,
        "file_count": file_count,
        "total_bytes": total_bytes,
        "manifest_sha256": manifest_sha256,
        "recorded_manifest_sha256": recorded.get("manifest_sha256"),
    }


def iter_snapshot_rows(snapshot_path: str | Path) -> Iterable[dict[str, Any]]:
    """Yield every row from a ``resource_snapshot.jsonl`` file."""
    yield from read_jsonl(snapshot_path)