diff --git a/gguf-fetch.py b/gguf-fetch.py index 1afcaa54..ddf50023 100755 --- a/gguf-fetch.py +++ b/gguf-fetch.py @@ -6,18 +6,22 @@ image or venv. llama.cpp's server image has no Python (the server stage of its . is a CUDA runtime, curl and llama-server: read at b12291, 2026-11-12), and the host has no huggingface_hub. A llama.cpp lane serves a few files of a GGUF repository that holds many (every quantization of the model, hundreds of GB), each pinned by its sha256 and its size, the way the speech -lane pins its GGUF (install-speech.sh). This fetches those files and nothing else, at the pinned +lane pins its GGUF (install-speech.sh). The embed lane's small files come the same way, pinned by +their git blob oid (40 hex digits, the name huggingface_hub gives a blob it keeps outside LFS) and +their size: their content is checked against the oid too, which is the git blob's digest of the +bytes (sha1 of its header and content), not only their size (install-embeddings.sh). This fetches those files and nothing else, at the pinned revision, into the cache's own layout: blobs/, the name huggingface_hub gives a file it keeps in LFS, and snapshots//, a relative link to it. A file huggingface_hub fetched before is the same file here, with not one byte downloaded again, and one fetched here is the same for it. gguf-fetch.py HF_HOME REPO REVISION PATH=SHA256:SIZE [PATH=SHA256:SIZE ...] + (a small file's pin is its git oid: PATH=OID:SIZE, 40 hex digits) A file whose blob is in the cache with its size answers without the network (a Load on a box that holds it, offline or throttled): its content is checked when it is downloaded, as huggingface_hub trusts a blob it wrote. One that is not is fetched from https://huggingface.co (HF_ENDPOINT moves it) -into blobs/.incomplete, which a later run resumes, then checked against its sha256 and its -size before it takes its name: a file that does not match is never kept. Refused before the first byte +into blobs/.incomplete, which a later run resumes, then checked against its sha256 (or, +for a small file, its git oid) and its size before it takes its name: a file that does not match is never kept. Refused before the first byte when the cache's disk lacks the room the missing bytes need. Five attempts per file, each resuming. The token, HF_TOKEN, is read from the environment, never from the command line, and goes to the Hub only: a header that is not passed on when the Hub redirects to its CDN. Each blob is fetched under the @@ -43,6 +47,7 @@ import urllib.request ATTEMPTS = 5 CHUNK = 8 << 20 SHA = re.compile(r"[0-9a-f]{64}") +OID = re.compile(r"[0-9a-f]{40}") COMMIT = re.compile(r"[0-9a-f]{40}") REPO = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*") @@ -58,8 +63,9 @@ def spec(text): parts = path.split("/") if not sep or not path or path.startswith("/") or any(p in ("", ".", "..") for p in parts): raise argparse.ArgumentTypeError(f"{text}: not PATH=SHA256:SIZE with a path inside the repository") - if not SHA.fullmatch(sha) or not size.isdigit() or int(size) <= 0: - raise argparse.ArgumentTypeError(f"{text}: the sha256 is 64 lowercase hex digits and the size a number of bytes") + if not (SHA.fullmatch(sha) or OID.fullmatch(sha)) or not size.isdigit() or int(size) <= 0: + raise argparse.ArgumentTypeError(f"{text}: the digest is 64 (sha256) or 40 (a git oid) lowercase hex " + f"digits and the size a number of bytes") return path, sha, int(size) @@ -177,6 +183,19 @@ def digest(path): h.update(chunk) +def git_oid(path): + """The git blob oid of a file: sha1 of its blob header ("blob \\0") and its bytes, + the name huggingface_hub gives a blob it keeps outside LFS, and a digest of the bytes.""" + h = hashlib.sha1() + with open(path, "rb") as f: + h.update(b"blob %d\0" % os.path.getsize(path)) + while True: + chunk = f.read(CHUNK) + if not chunk: + return h.hexdigest() + h.update(chunk) + + @contextlib.contextmanager def blob_lock(hf_home, repo, sha): """huggingface_hub's own lock of this blob (filelock, an flock on the same file).""" @@ -215,9 +234,16 @@ def fetch_one(hf_home, repo, rev, path, sha, size, timeout, say): say(f"download interrupted ({type(e).__name__}), resuming ({attempt}/{ATTEMPTS})...") time.sleep(10) got = digest(part) - if got != sha: + if len(sha) == 64 and got != sha: os.unlink(part) raise Refused(f"{path} does not match its pinned sha256 (got {got[:12]}, pinned {sha[:12]}): not kept") + if len(sha) == 40: + # a small file's pin is its git oid, itself a digest of the bytes: checked the same + # way, where it was checked by size alone until the review of 2026-11-19 + got = git_oid(part) + if got != sha: + os.unlink(part) + raise Refused(f"{path} does not match its pinned git oid (got {got[:12]}, pinned {sha[:12]}): not kept") os.chmod(part, 0o644) os.replace(part, blob) @@ -254,7 +280,7 @@ def main(argv=None, say=say_line): ap.add_argument("hf_home", help="the Hugging Face home: its hub/ holds the cache") ap.add_argument("repo") ap.add_argument("rev", help="the pinned commit, 40 hex digits") - ap.add_argument("files", nargs="+", type=spec, metavar="PATH=SHA256:SIZE") + ap.add_argument("files", nargs="+", type=spec, metavar="PATH=SHA256:SIZE") # a small file: PATH=OID:SIZE a = ap.parse_args(argv) if not REPO.fullmatch(a.repo): raise Refused(f"{a.repo}: not a repository id (owner/name)") diff --git a/tests/test_flash_unsloth_lane.py b/tests/test_flash_unsloth_lane.py index ae6bd76f..dd93f6f3 100644 --- a/tests/test_flash_unsloth_lane.py +++ b/tests/test_flash_unsloth_lane.py @@ -731,6 +731,24 @@ class TheFetch(unittest.TestCase): blobs = self.t / "hub" / "models--org--model" / "blobs" self.assertEqual([p.name for p in blobs.iterdir() if not p.name.endswith(".lock")], []) + def test_a_small_file_pinned_by_oid_is_checked_by_it(self): + """A 40-digit pin was checked by size alone (the review of 2026-11-19): a file of + another revision at the same size passed. The git oid is a digest of the bytes + (sha1 of the blob's header and content), so it is checked like the sha256.""" + path, body = next(iter(self.data.items())) + oid = hashlib.sha1(b"blob %d\0" % len(body) + body).hexdigest() + os.environ["HF_ENDPOINT"] = self.hub({path: body + b"tampered"}).url + spec = f"{path}={oid}:{len(body) + 8}" + with self.assertRaises(SystemExit) as e: + self.run_fetch([spec]) + self.assertIn("does not match its pinned git oid", str(e.exception.code)) + blobs = self.t / "hub" / "models--org--model" / "blobs" + self.assertEqual([p.name for p in blobs.iterdir() if not p.name.endswith(".lock")], []) + # and the bytes the oid names pass, landing under the oid as huggingface_hub lays them out + os.environ["HF_ENDPOINT"] = self.hub().url + self.run_fetch([f"{path}={oid}:{len(body)}"]) + self.assertEqual((blobs / oid).read_bytes(), body) + def test_the_token_goes_to_the_hub_and_never_past_its_redirect(self): cdn = self.hub() hub = self.hub(files={}, redirect=cdn.url)