|
| 1 | +"""MiniLM hub-cache copy, C: -> D: (plan v2.4 Phase 3; decision D2 |
| 2 | +*Approved 2026-10-19*: "Copy MiniLM cache C: -> D:; project-local HF_HOME |
| 3 | +(no system env changes)"; section 10.2 "MiniLM cache copied C:->D: (D2 - a |
| 4 | +read from C:, all writes land on D:)"; Z9 (C: is read-only for the project), |
| 5 | +Z6 (no downloads - the existing cache is reused, never re-fetched). |
| 6 | +
|
| 7 | +Rules this module enforces: |
| 8 | +
|
| 9 | +- **Read-only on the source.** The source is an *existing* Hugging Face hub |
| 10 | + model cache (the user cache on C:). Files are opened for reading and |
| 11 | + hashing only; nothing is ever written, moved, or deleted at the source. |
| 12 | +- **Writes strictly contained (Z9).** The destination is resolved through |
| 13 | + :func:`rag_platform.db.sqlite.resolve_under_project` *before* any |
| 14 | + directory or file is created; an escaped destination raises |
| 15 | + :class:`~rag_platform.db.sqlite.PathContainmentError` and leaves nothing |
| 16 | + behind. |
| 17 | +- **No download, no model load.** Only ``hashlib``/``shutil`` file |
| 18 | + operations on already-present artifacts; this module never imports an |
| 19 | + embedding library and never opens a socket. |
| 20 | +- **Full-replica copy with hash verification.** Every file in the model |
| 21 | + directory (``refs/``, ``snapshots/``, ``blobs/``, ``.no_exist/``) is |
| 22 | + copied byte-for-byte (``copy2``, metadata preserved) and each destination |
| 23 | + file is SHA256-verified against the source immediately after copying; a |
| 24 | + final independent verification pass re-checks the whole tree and the |
| 25 | + ``refs``/``snapshots`` revision consistency. |
| 26 | +- **Idempotent.** A destination file whose size and SHA256 already match |
| 27 | + the source is skipped, so re-running is cheap and safe. Divergent |
| 28 | + destination files are re-copied (the original cache is the source of |
| 29 | + truth; the destination is a derived artifact). |
| 30 | +""" |
| 31 | + |
| 32 | +from __future__ import annotations |
| 33 | + |
| 34 | +import hashlib |
| 35 | +import shutil |
| 36 | +from collections.abc import Iterator |
| 37 | +from dataclasses import dataclass |
| 38 | +from pathlib import Path |
| 39 | + |
| 40 | +from rag_platform.db.sqlite import resolve_under_project |
| 41 | +from rag_platform.embeddings.minilm import EmbeddingError |
| 42 | + |
| 43 | + |
| 44 | +class CacheCopyError(EmbeddingError): |
| 45 | + """Cache source layout invalid, or a copied file failed verification.""" |
| 46 | + |
| 47 | + |
| 48 | +@dataclass(frozen=True) |
| 49 | +class CacheCopyReport: |
| 50 | + """Result of a copy or verification run (no secrets, hash summaries only).""" |
| 51 | + |
| 52 | + source: Path |
| 53 | + destination: Path |
| 54 | + snapshot_revision: str | None |
| 55 | + file_count: int |
| 56 | + total_bytes: int |
| 57 | + copied: int |
| 58 | + skipped_identical: int |
| 59 | + verified: bool |
| 60 | + |
| 61 | + |
| 62 | +def _sha256_file(path: Path) -> str: |
| 63 | + digest = hashlib.sha256() |
| 64 | + with path.open("rb") as handle: |
| 65 | + for chunk in iter(lambda: handle.read(1024 * 1024), b""): |
| 66 | + digest.update(chunk) |
| 67 | + return digest.hexdigest() |
| 68 | + |
| 69 | + |
| 70 | +def _iter_files(root: Path) -> Iterator[Path]: |
| 71 | + """All regular files under *root*, sorted for deterministic ordering.""" |
| 72 | + yield from sorted(path for path in root.rglob("*") if path.is_file()) |
| 73 | + |
| 74 | + |
| 75 | +def _validate_source(source: Path) -> tuple[str | None, list[Path]]: |
| 76 | + """Validate the hub model-cache layout; return (revision, files). |
| 77 | +
|
| 78 | + Raises :class:`CacheCopyError` for anything that is not a well-formed |
| 79 | + model cache - a missing or ambiguous source stops the operation instead |
| 80 | + of copying a partial tree or substituting another model. |
| 81 | + """ |
| 82 | + if not source.exists(): |
| 83 | + raise CacheCopyError(f"cache source does not exist: {source}") |
| 84 | + if not source.is_dir(): |
| 85 | + raise CacheCopyError(f"cache source is not a directory: {source}") |
| 86 | + refs = source / "refs" |
| 87 | + snapshots = source / "snapshots" |
| 88 | + if not refs.is_dir() or not snapshots.is_dir(): |
| 89 | + raise CacheCopyError( |
| 90 | + f"not a Hugging Face hub model cache (missing refs/ or " |
| 91 | + f"snapshots/): {source}" |
| 92 | + ) |
| 93 | + revision: str | None = None |
| 94 | + main_ref = refs / "main" |
| 95 | + if main_ref.is_file(): |
| 96 | + revision = main_ref.read_text(encoding="utf-8").strip() or None |
| 97 | + if revision is not None: |
| 98 | + snapshot_dir = snapshots / revision |
| 99 | + if not snapshot_dir.is_dir(): |
| 100 | + raise CacheCopyError( |
| 101 | + f"refs/main revision {revision!r} has no matching snapshot " |
| 102 | + f"directory under {snapshots} (inconsistent cache)" |
| 103 | + ) |
| 104 | + if not any(path.is_file() for path in snapshot_dir.rglob("*")): |
| 105 | + raise CacheCopyError( |
| 106 | + f"snapshot {revision!r} contains no files (incomplete cache): " |
| 107 | + f"{snapshot_dir}" |
| 108 | + ) |
| 109 | + elif not any(path.is_file() for path in snapshots.rglob("*")): |
| 110 | + raise CacheCopyError( |
| 111 | + f"snapshots/ contains no files (incomplete cache): {snapshots}" |
| 112 | + ) |
| 113 | + files = list(_iter_files(source)) |
| 114 | + if not files: |
| 115 | + raise CacheCopyError(f"cache source contains no files: {source}") |
| 116 | + return revision, files |
| 117 | + |
| 118 | + |
| 119 | +def copy_model_cache(source: str | Path, destination: str | Path) -> CacheCopyReport: |
| 120 | + """Copy the model cache at *source* to *destination* (both model dirs). |
| 121 | +
|
| 122 | + *source* is read-only; *destination* must resolve strictly under the |
| 123 | + project root (validated first). Every copied file is SHA256-verified, |
| 124 | + followed by a full independent verification pass - the returned report |
| 125 | + always has ``verified=True`` or the function has raised. |
| 126 | + """ |
| 127 | + source_path = Path(source) |
| 128 | + revision, files = _validate_source(source_path) |
| 129 | + dest_path = resolve_under_project(destination) # Z9: before any mkdir |
| 130 | + if dest_path.exists() and not dest_path.is_dir(): |
| 131 | + raise CacheCopyError(f"destination exists and is not a directory: {dest_path}") |
| 132 | + |
| 133 | + copied = 0 |
| 134 | + skipped = 0 |
| 135 | + total_bytes = 0 |
| 136 | + # Replicate the full directory tree first, including empty directories |
| 137 | + # (an empty blobs/ is part of the hub layout); containment was validated |
| 138 | + # above, so every mkdir stays under the project root. |
| 139 | + for src_dir in sorted(path for path in source_path.rglob("*") if path.is_dir()): |
| 140 | + (dest_path / src_dir.relative_to(source_path)).mkdir( |
| 141 | + parents=True, exist_ok=True |
| 142 | + ) |
| 143 | + for src_file in files: |
| 144 | + relative = src_file.relative_to(source_path) |
| 145 | + dst_file = dest_path / relative |
| 146 | + size = src_file.stat().st_size |
| 147 | + total_bytes += size |
| 148 | + if ( |
| 149 | + dst_file.is_file() |
| 150 | + and dst_file.stat().st_size == size |
| 151 | + and _sha256_file(dst_file) == _sha256_file(src_file) |
| 152 | + ): |
| 153 | + skipped += 1 |
| 154 | + continue |
| 155 | + dst_file.parent.mkdir(parents=True, exist_ok=True) |
| 156 | + shutil.copy2(src_file, dst_file) |
| 157 | + if _sha256_file(dst_file) != _sha256_file(src_file): |
| 158 | + raise CacheCopyError(f"copied file failed SHA256 verification: {relative}") |
| 159 | + copied += 1 |
| 160 | + |
| 161 | + report = verify_cache_copy(source_path, dest_path) |
| 162 | + if not report.verified: # defensive: copy loop already checks each file |
| 163 | + raise CacheCopyError( |
| 164 | + f"post-copy verification failed for {dest_path}; " |
| 165 | + f"mismatched files remain - re-run the copy" |
| 166 | + ) |
| 167 | + return CacheCopyReport( |
| 168 | + source=report.source, |
| 169 | + destination=report.destination, |
| 170 | + snapshot_revision=revision, |
| 171 | + file_count=report.file_count, |
| 172 | + total_bytes=report.total_bytes, |
| 173 | + copied=copied, |
| 174 | + skipped_identical=skipped, |
| 175 | + verified=True, |
| 176 | + ) |
| 177 | + |
| 178 | + |
| 179 | +def verify_cache_copy(source: str | Path, destination: str | Path) -> CacheCopyReport: |
| 180 | + """Read-only verification: destination must mirror the source exactly. |
| 181 | +
|
| 182 | + Checks file-set equality (no missing and no extra files), per-file size |
| 183 | + and SHA256 equality, and ``refs``/``snapshots`` revision consistency. |
| 184 | + Never writes anything. |
| 185 | + """ |
| 186 | + source_path = Path(source) |
| 187 | + revision, files = _validate_source(source_path) |
| 188 | + dest_path = Path(destination) |
| 189 | + if not dest_path.is_dir(): |
| 190 | + raise CacheCopyError(f"destination is not a directory: {dest_path}") |
| 191 | + |
| 192 | + total_bytes = 0 |
| 193 | + ok = True |
| 194 | + for src_file in files: |
| 195 | + relative = src_file.relative_to(source_path) |
| 196 | + dst_file = dest_path / relative |
| 197 | + size = src_file.stat().st_size |
| 198 | + total_bytes += size |
| 199 | + if not dst_file.is_file(): |
| 200 | + ok = False |
| 201 | + continue |
| 202 | + if dst_file.stat().st_size != size or _sha256_file(dst_file) != _sha256_file( |
| 203 | + src_file |
| 204 | + ): |
| 205 | + ok = False |
| 206 | + expected = {file.relative_to(source_path) for file in files} |
| 207 | + actual = {path.relative_to(dest_path) for path in _iter_files(dest_path)} |
| 208 | + if actual != expected: |
| 209 | + ok = False # extra or missing files at the destination |
| 210 | + |
| 211 | + return CacheCopyReport( |
| 212 | + source=source_path, |
| 213 | + destination=dest_path, |
| 214 | + snapshot_revision=revision, |
| 215 | + file_count=len(files), |
| 216 | + total_bytes=total_bytes, |
| 217 | + copied=0, |
| 218 | + skipped_identical=0, |
| 219 | + verified=ok, |
| 220 | + ) |
0 commit comments