okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
13.4 KiB271 linesraw
1"""Tests for the fixed SHA-256 and size of every model file setup downloads (REPO_PINS): every file a choice can
2download has one, a wrong file is deleted and setup stops, a pinned commit that answers 404 stops the download
3(STRATA_ALLOW_UNPINNED=1 is the tester's opt-out), and an installed model needs no network.  Mocked network - nothing
4is downloaded.
5
6    python -m unittest tools.test_setup_model_pins
7"""
8from __future__ import annotations
9
10import contextlib
11import hashlib
12import io
13import re
14import sys
15import tempfile
16import unittest
17import urllib.error
18from pathlib import Path
19from unittest import mock
20
21ROOT = Path(__file__).resolve().parents[1]
22sys.path.insert(0, str(ROOT))
23sys.path.insert(0, str(ROOT / "tools"))
24import setup  # noqa: E402
25
26REPO = "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"
27HEX = re.compile(r"^[0-9a-f]{64}$")
28
29
30class Response(io.BytesIO):
31    def __init__(self, body=b"", status=200, length=None):
32        super().__init__(body)
33        self.status = status
34        self.headers = {"Content-Length": str(len(body) if length is None else length)}
35
36    def __enter__(self):
37        return self
38
39    def __exit__(self, *exc):
40        self.close()
41
42
43def quiet(fn, *args, **kw):
44    out = io.StringIO()
45    with contextlib.redirect_stdout(out):
46        return fn(*args, **kw), out.getvalue()
47
48
49def pinned_url(name):
50    return setup.hf(REPO) + name
51
52
53def with_pin(name, data):
54    """REPO_PINS with one more file of the repository: `data`'s size and SHA-256."""
55    pins = dict(setup.REPO_PINS)
56    pins[REPO] = {**pins[REPO], name: (len(data), hashlib.sha256(data).hexdigest())}
57    return mock.patch.object(setup, "REPO_PINS", pins)
58
59
60class EveryFileIsPinned(unittest.TestCase):
61    def pinned(self, url):
62        pin = setup.file_pin(url)
63        self.assertIsNotNone(pin, url)
64        self.assertGreater(pin[0], 0)
65        self.assertRegex(pin[1], HEX)
66
67    def test_every_shard_of_every_choice(self):
68        for fam_name, fam in {**setup.FAMILIES, **setup.OWN_PATH_FAMILIES}.items():
69            if fam.get("ready"):                       # ready-made packs: pinned file by file (ready_files)
70                continue
71            for model in (setup.MODELS if fam_name in setup.FAMILIES else fam["models"]):
72                if fam_name in setup.FAMILIES and fam_name not in setup.MODELS[model].get("families", ("qwen", "swift")):
73                    continue
74                with self.subTest(family=fam_name, model=model):
75                    if fam_name in setup.FAMILIES:
76                        for i in range(1, setup.model_shards(fam, model) + 1):
77                            self.pinned(fam["hf"].format(q=model) + setup.model_file(fam, model, i))
78                    else:
79                        self.pinned(fam["hf"] + fam["file"].format(q=model))
80
81    def test_the_picture_reader_of_every_family(self):
82        for name, fam in {**setup.FAMILIES, **setup.OWN_PATH_FAMILIES}.items():
83            with self.subTest(family=name):
84                self.pinned(fam["mmproj_hf"] + fam["mmproj"])
85
86    def test_the_nvfp4_packs_still_pin_their_files(self):
87        for model in setup.MODELS:
88            if setup.MODELS[model].get("repo"):
89                for f in setup.ready_files(model):
90                    self.assertRegex(f[5], HEX)
91
92    def test_every_pin_is_well_formed_and_every_repository_is_pinned(self):
93        for repo, files in setup.REPO_PINS.items():
94            self.assertIn(repo, setup.HF_REVISIONS)
95            for name, (size, sha) in files.items():
96                with self.subTest(repo=repo, file=name):
97                    self.assertIsInstance(size, int)
98                    self.assertGreater(size, 1000)
99                    self.assertRegex(sha, HEX)
100
101    def test_known_values(self):
102        # the Hub's LFS pointers; the picture reader is the same file the NVFP4 family already pinned
103        self.assertEqual(setup.file_pin(pinned_url("mmproj-Qwen3.8-Flash-Next-BF16.gguf")),
104                         setup.FAMILIES["nvfp4"]["mmproj_sha256"])
105        self.assertEqual(setup.file_pin(pinned_url("Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf")),
106                         (37623740192, "69820c02ec7d0b45ef2ebb19d6620299db749fe2aded7f39f93c6b88b199b720"))
107        # the n-gram table is one file for the four sizes and the Coder
108        shard2 = {setup.ISTA_FILES["Qwen3.8-Flash-Next-GSQ-RCO-%s-00002-of-00002.gguf" % q] for q in
109                  ("Q2_0", "IQ2_XS", "IQ3_XXS", "IQ3_S")}
110        self.assertEqual(len(shard2), 1)
111        self.assertEqual(setup.CODER_FILES["Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf"], shard2.pop())
112
113    def test_an_unknown_file_has_no_pin(self):
114        self.assertIsNone(setup.file_pin(pinned_url("nothing.gguf")))
115        self.assertIsNone(setup.file_pin("https://example.com/a/b/resolve/main/x.gguf"))
116
117
118class DownloadChecksThePin(unittest.TestCase):
119    def serve(self, body, length=None):
120        seen = []
121
122        def urlopen(req, timeout=None):
123            seen.append(req.get_method())
124            if req.get_method() == "HEAD":
125                return Response(b"", length=length)
126            return Response(body, status=200)
127
128        return seen, mock.patch.object(setup.netpolicy, "urlopen", urlopen)
129
130    def run_download(self, name, served, pinned, length=None):
131        seen, patch = self.serve(served, length if length is not None else len(served))
132        with tempfile.TemporaryDirectory() as d, with_pin(name, pinned), patch, \
133                mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface"}):
134            setup.os.environ.pop("STRATA_ALLOW_UNPINNED", None)
135            dst = Path(d) / name
136            try:
137                _, out = quiet(setup.download, pinned_url(name), dst)
138                code = None
139            except SystemExit as e:
140                code, out = e.code, ""
141            result = (code, dst.exists(), dst.with_name(dst.name + ".done").exists(),
142                      dst.with_name(dst.name + ".part").exists(),
143                      dst.with_name(dst.name + ".done").read_text() if dst.with_name(dst.name + ".done").exists() else "")
144        return seen, result
145
146    def test_the_right_file_is_kept_with_its_hash_in_the_mark(self):
147        data = b"the model" * 100
148        seen, (code, exists, marked, part, mark_text) = self.run_download("t.gguf", data, data)
149        self.assertIsNone(code)
150        self.assertTrue(exists and marked and not part)
151        self.assertIn("sha256 " + hashlib.sha256(data).hexdigest(), mark_text)
152
153    def test_a_wrong_file_is_deleted_and_setup_stops(self):
154        data = b"the model" * 100
155        wrong = b"THE MODEL" * 100                     # the pinned size, another content
156        seen, (code, exists, marked, part, _) = self.run_download("t.gguf", wrong, data)
157        self.assertEqual(code, 1)
158        self.assertFalse(exists or marked or part)
159
160    def test_a_wrong_size_stops_before_the_download(self):
161        data = b"the model" * 100
162        seen, (code, exists, marked, part, _) = self.run_download("t.gguf", data + b"x", data)
163        self.assertEqual(code, 1)
164        self.assertEqual(seen, ["HEAD"])               # no GET: nothing of the wrong file was fetched
165        self.assertFalse(exists or marked or part)
166
167
168class NotFoundOnThePinnedCommit(unittest.TestCase):
169    def urlopen(self, seen):
170        def urlopen(req, timeout=None):
171            seen.append((req.get_method(), req.full_url))
172            if "/resolve/main/" not in req.full_url:
173                raise urllib.error.HTTPError(req.full_url, 404, "Not Found", {}, None)
174            return Response(b"current file")
175        return urlopen
176
177    def test_it_stops_with_a_plain_message(self):
178        seen = []
179        out = io.StringIO()
180        with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.netpolicy, "urlopen", self.urlopen(seen)), \
181                mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface"}), contextlib.redirect_stdout(out):
182            setup.os.environ.pop("STRATA_ALLOW_UNPINNED", None)
183            dst = Path(d) / "t.gguf"
184            with self.assertRaises(SystemExit):
185                setup.download(pinned_url("Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf"), dst, "the model")
186            self.assertFalse(dst.exists())
187        self.assertIn("the pinned version of the model is no longer on Hugging Face", out.getvalue())
188        self.assertIn("update Strata", out.getvalue())
189        self.assertEqual(len(seen), 1)                 # no second try on main
190
191    def test_the_opt_out_takes_the_current_file_and_says_so(self):
192        seen = []
193        with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.netpolicy, "urlopen", self.urlopen(seen)), \
194                mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface", "STRATA_ALLOW_UNPINNED": "1"}), \
195                mock.patch.object(setup, "_unpinned_said", []):
196            dst = Path(d) / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf"
197            _, out = quiet(setup.download, pinned_url("Q2_0/" + dst.name), dst)
198            self.assertEqual(dst.read_bytes(), b"current file")     # not checked against the pin: it is not the pinned file
199        self.assertIn("STRATA_ALLOW_UNPINNED=1", out)
200
201    def test_the_opt_out_is_off_by_default(self):
202        with mock.patch.dict(setup.os.environ, {}, clear=False):
203            setup.os.environ.pop("STRATA_ALLOW_UNPINNED", None)
204            self.assertFalse(setup.allow_unpinned())
205            for value in ("", "0", "no"):
206                setup.os.environ["STRATA_ALLOW_UNPINNED"] = value
207                self.assertFalse(setup.allow_unpinned())
208
209
210class InstalledModelsNeedNoNetwork(unittest.TestCase):
211    """Once a model is downloaded, setup and the start do not contact Hugging Face (they run offline)."""
212
213    def test_an_installed_file_is_not_asked_for(self):
214        def urlopen(req, timeout=None):
215            raise AssertionError("network used for an installed file: " + req.full_url)
216
217        with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.netpolicy, "urlopen", urlopen), \
218                mock.patch.dict(setup.os.environ, {"HF_ENDPOINT": "http://127.0.0.1:9", "STRATA_SOURCE": "auto"}):
219            dst = Path(d) / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf"
220            dst.write_bytes(b"installed by an earlier setup")       # no hash in its mark (installed before the pins)
221            setup.mark(dst)
222            _, out = quiet(setup.download, pinned_url("Q2_0/" + dst.name), dst)
223            self.assertIn("already downloaded", out)
224            self.assertEqual(dst.read_bytes(), b"installed by an earlier setup")   # kept, not hashed, not deleted
225
226    def test_a_dead_host_is_reported_for_a_download_only(self):
227        def urlopen(req, timeout=None):
228            raise urllib.error.URLError("no route to host")
229
230        with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.netpolicy, "urlopen", urlopen), \
231                mock.patch.object(setup.time, "sleep", lambda s: None), \
232                mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface"}):
233            with self.assertRaises(SystemExit):
234                quiet(setup.download, pinned_url("Q2_0/x.gguf"), Path(d) / "x.gguf")
235
236    def test_the_runtime_has_no_model_host_in_it(self):
237        """strata launch, serve, the monitor and the API reach no model host: the names are in setup.py and the install
238        tools only (and strata_control.acquisition refuses a download under STRATA_NO_ACQUIRE=1)."""
239        hosts = re.compile(r"huggingface\.co|hf-mirror|HF_ENDPOINT|modelscope|hf_hub_download", re.I)
240        # The harmless mentions: the model-card link a benchmark result file names (nothing opens it), and the pinned
241        # DFlash2 drafter address, which only `strata drafting fetch` downloads from, behind acquisition.require (refused
242        # under STRATA_NO_ACQUIRE, so a start or a server never reaches it). Dropping just those lines from the scan keeps
243        # the rule exact for everything else.
244        # strata_control/pictures.py names the host for the picture-reader files that Load fetches when Read pictures is on and the files
245        # are missing: its download calls acquisition.require first (refused under STRATA_NO_ACQUIRE, so a start or a server never reaches it).
246        harmless = ('MODEL_CARD_URL = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next"',
247                    'BASE_URL = f"https://huggingface.co/{REPO}/resolve/{REVISION}/"',
248                    'https://huggingface.co/nazeshinjite/Qwen3.8-Flash-Next-DFlash2-GGUF',   # the credit link in drafting.py's comment and drafting_fetch.py's docstring (nothing opens it)
249                    'HF_DEFAULT = "https://huggingface.co"',
250                    'base = (endpoint if endpoint is not None else (os.environ.get("HF_ENDPOINT") or "").strip().rstrip("/") or HF_DEFAULT)')
251        found = []
252        for folder in ("strata_cli", "serve", "strata_control"):
253            for p in (ROOT / folder).rglob("*.py"):
254                if "test" in p.name:
255                    continue
256                text = p.read_text(encoding="utf-8", errors="replace")
257                for line in harmless:
258                    text = text.replace(line, "")
259                if hosts.search(text):
260                    found.append(str(p.relative_to(ROOT)))
261        self.assertEqual(found, [])
262
263    def test_a_download_is_refused_while_serving(self):
264        from strata_control import acquisition
265        with acquisition.forbidden():
266            with self.assertRaises(acquisition.AcquisitionRefused):
267                setup.download(pinned_url("Q2_0/x.gguf"), Path(tempfile.gettempdir()) / "strata-never.gguf")
268
269
270if __name__ == "__main__":
271    unittest.main()