"""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("= 9: break M.time.sleep(0.01) gate.set() threading.Thread(target=release, daemon=True).start() with mock.patch.object(M, "get", get): list(M.ranged("u", 0, 40 * 1000 - 1, 1000, 4)) self.assertGreaterEqual(len(started), 9) # four connections, nine ranges started before range 0 ended def test_a_failing_range_stops_the_parallel_read(self): def get(url, a, b): if a >= 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]) class Progress(FetchCase): """#3257: the fetch says how far it is in the form of setup's own download line, so the app can show it.""" def test_progress_lines_name_the_whole_download_and_end_at_100(self): err = self.fetch(Mirror()) lines = [x for x in err.splitlines() if "MTP draft layer:" in x] total = len(A) + len(B) self.assertTrue(lines) self.assertIn("/ %.2f GB" % (total / 1e9), lines[-1]) self.assertIn("(100%)", lines[-1]) import re for x in lines: # the shape tools/strata_mcp.py install_progress reads self.assertTrue(re.match(r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)", x), x) def test_a_resumed_fetch_starts_from_what_is_already_there(self): self.fetch(Mirror()) err = self.fetch(Mirror()) self.assertIn("(100%)", [x for x in err.splitlines() if "MTP draft layer:" in x][0]) def test_the_progress_figure_follows_the_job_in_strata_mcp(self): import strata_mcp as MCP got = MCP.install_progress(["=== Step 6: preparing the model for Strata ===", " MTP draft layer: 1.23 / 5.04 GB (24%)"]) self.assertEqual(got["download"], {"file": "MTP draft layer", "done_gb": 1.23, "total_gb": 5.04, "percent": 24}) class Flaky(FetchCase): def test_a_connection_that_drops_mid_tensor_does_not_end_the_run(self): """#3214: every range of the tensor fails past get()'s own retries once: the tensor is tried again (fewer connections).""" honest, fails = Mirror(), [0] def mirror(req, timeout=None): if req.get_header("Range") and req.full_url.endswith("model-2.safetensors") and fails[0] < 12: a, b = map(int, req.get_header("Range").split("=")[1].split("-")) if (a, b) == Mirror.span("model-2.safetensors", "mtp.b"): fails[0] += 1 raise IOError("timed out") return honest(req, timeout) err = self.fetch(mirror) self.assertEqual(self.tensor("mtp.b"), B) self.assertIn("continuing with", err) def test_a_link_that_never_works_ends_with_a_plain_sentence(self): def mirror(req, timeout=None): if req.get_header("Range") and req.full_url.endswith("model-2.safetensors"): a, b = map(int, req.get_header("Range").split("=")[1].split("-")) if (a, b) == Mirror.span("model-2.safetensors", "mtp.b"): raise IOError("timed out") return Mirror()(req, timeout) with self.assertRaisesRegex(SystemExit, "keeps failing"): self.fetch(mirror) class OneAtATime(unittest.TestCase): def test_a_second_fetch_in_the_same_folder_waits_for_the_first(self): with tempfile.TemporaryDirectory() as d: first = M.lock_folder(d) told = io.StringIO() with mock.patch.object(M.time, "sleep", lambda s: None), contextlib.redirect_stderr(told), \ self.assertRaisesRegex(SystemExit, "another MTP download"): M.lock_folder(d, wait=0.0) first.close() M.lock_folder(d).close() # free again once the first ends def test_a_download_ends_with_the_process_that_started_it(self): """#3257: setup killed, its child must not go on: a grandchild whose parent is gone.""" import subprocess import time child_code = ("import sys,time; sys.path.insert(0, %r); import mtp_fetch as M; M.exit_with_parent(); " "print('up', flush=True); time.sleep(60)" % str(ROOT / "tools")) parent_code = ("import subprocess,sys,os; env=dict(os.environ, STRATA_EXIT_WITH_PARENT='1'); " "p=subprocess.Popen([sys.executable,'-c',%r], env=env, stdout=subprocess.PIPE, text=True); " "print(p.pid, flush=True); p.stdout.readline(); print('ready', flush=True); sys.stdout.flush(); os._exit(0)" % child_code) r = subprocess.Popen([sys.executable, "-c", parent_code], stdout=subprocess.PIPE, text=True) pid = int(r.stdout.readline()) r.stdout.readline() r.wait(30) end = time.time() + 15 alive = True while time.time() < end and alive: time.sleep(0.5) if os.name == "nt": out = subprocess.run(["tasklist", "/FI", "PID eq %d" % pid], capture_output=True, text=True).stdout alive = str(pid) in out else: try: os.kill(pid, 0) alive = True except OSError: alive = False if alive: if os.name == "nt": subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True) else: os.kill(pid, 9) self.assertFalse(alive, "the download kept running after its parent ended") if __name__ == "__main__": unittest.main()