"""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)