"""Tests for tools/mtp_fetch.py (#327): a range read needs a 206 with the asked Content-Range, the pinned revision's tensors are checked against their sha256 (a wrong one is fetched again; a corrupt install is found by `verify` and setup fetches it again), and an inventory from another revision is read again. A fake checkpoint behind a mocked urlopen - nothing is downloaded. python -m unittest tools.test_mtp_fetch """ from __future__ import annotations import contextlib import hashlib import io import json import os import struct import sys import tempfile import unittest from pathlib import Path from unittest import mock ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "tools")) import mtp_fetch as M # noqa: E402 def shard(tensors): """A safetensors file: [u64 header length][JSON header][data].""" header, data = {}, b"" for name, blob in tensors: header[name] = {"dtype": "BF16", "shape": [len(blob) // 2], "data_offsets": [len(data), len(data) + len(blob)]} data += blob h = json.dumps(header).encode() return struct.pack("= 2000: raise IOError("boom") return bytes(b - a + 1) with mock.patch.object(M, "get", get), self.assertRaises(IOError): list(M.ranged("u", 0, 9999, 1000, 4)) def test_wrong_bytes_are_fetched_again_once_then_refused(self): self.fetch(Mirror()) bad = bytes(len(A)) # an install the #327 mirror corrupted: right size, wrong bytes (self.out / "tensors" / "mtp.a.bin").write_bytes(bad) self.assertEqual(M.verify(str(self.out)), ["mtp.a"]) err = self.fetch(Mirror()) # setup runs fetch again: the bad one is fetched again self.assertIn("mtp.a: wrong bytes", err) self.assertEqual(self.tensor("mtp.a"), A) self.assertEqual(M.verify(str(self.out)), []) os.remove(self.out / "tensors" / "mtp.b.bin") with self.assertRaises(SystemExit) as cm: self.fetch(Mirror(wrong={"mtp.b"})) # a source that keeps sending wrong data self.assertIn("is not the checkpoint's", str(cm.exception)) self.assertFalse((self.out / "tensors" / "mtp.b.bin").exists()) def test_an_inventory_from_another_revision_is_read_again(self): self.fetch(Mirror()) inv = json.loads((self.out / "mtp-inventory.json").read_text()) inv["repo"] = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/" for r in inv["tensors"]: r["start"] += 1 # that revision's ranges: not this one's r["end"] += 1 (self.out / "mtp-inventory.json").write_text(json.dumps(inv)) (self.out / "tensors" / "mtp.b.bin").write_bytes(B[:10]) # half a tensor from that revision mirror = Mirror() self.fetch(mirror) self.assertEqual(json.loads((self.out / "mtp-inventory.json").read_text())["repo"], M.REPO) self.assertEqual((self.tensor("mtp.a"), self.tensor("mtp.b")), (A, B)) fetched = [r for r in mirror.ranges if r[2] - r[1] + 1 in (len(A), len(B))] self.assertEqual(fetched, [("model-2.safetensors",) + Mirror.span("model-2.safetensors", "mtp.b")], "mtp.a was right and is kept; mtp.b is fetched whole") def test_verify_keeps_its_verdict_and_skips_other_revisions(self): self.fetch(Mirror()) self.assertEqual(M.verify(str(self.out)), []) stamps = json.loads((self.out / "tensors" / "verified.json").read_text()) self.assertEqual(sorted(stamps), ["mtp.a", "mtp.b"]) with mock.patch.object(M, "sha256_of", side_effect=AssertionError("hashed an unchanged file")): self.assertEqual(M.verify(str(self.out)), []) with mock.patch.object(M, "REPO", "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/"): (self.out / "tensors" / "mtp.a.bin").write_bytes(b"x") self.assertEqual(M.verify(str(self.out)), []) # STRATA_MTP_REVISION: other hashes self.assertEqual(M.verify(str(self.out)), ["mtp.a"]) self.assertEqual(M.verify(str(self.out / "nothing")), []) class Pinned(unittest.TestCase): def test_every_tensor_has_a_hash(self): self.assertEqual(len(M.SHA256), 31) for name, h in M.SHA256.items(): self.assertTrue(name.startswith("mtp.")) self.assertRegex(h, "^[0-9a-f]{64}$") self.assertIn(M.PINNED_REVISION, M.PINNED) class Setup(unittest.TestCase): def test_setup_rebuilds_a_corrupt_install(self): import setup with tempfile.TemporaryDirectory() as d: mtp = Path(d) self.assertFalse(setup.mtp_corrupt(mtp)) # no tensors kept: nothing to check (mtp / "tensors").mkdir() for code, want in ((0, False), (3, True), (1, False)): with self.subTest(code=code), mock.patch.object( setup.subprocess, "run", return_value=mock.Mock(returncode=code)) as run: self.assertEqual(setup.mtp_corrupt(mtp), want) self.assertIn("verify", run.call_args[0][0]) if __name__ == "__main__": unittest.main()