okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
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 6python -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 ): 31def __init__ (self ,body = b"" ,status = 200 ,length = None ): 32super ().__init__ (body ) 33self .status = status 34self .headers = {"Content-Length" :str (len (body )if length is None else length )} 35 36def __enter__ (self ): 37return self 38 39def __exit__ (self ,* exc ): 40self .close () 41 42 43def quiet (fn ,* args ,** kw ): 44out = io .StringIO () 45with contextlib .redirect_stdout (out ): 46return fn (* args ,** kw ),out .getvalue () 47 48 49def pinned_url (name ): 50return 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.""" 55pins = dict (setup .REPO_PINS ) 56pins [REPO ]= {** pins [REPO ],name : (len (data ),hashlib .sha256 (data ).hexdigest ())} 57return mock .patch .object (setup ,"REPO_PINS" ,pins ) 58 59 60class EveryFileIsPinned (unittest .TestCase ): 61def pinned (self ,url ): 62pin = setup .file_pin (url ) 63self .assertIsNotNone (pin ,url ) 64self .assertGreater (pin [0 ],0 ) 65self .assertRegex (pin [1 ],HEX ) 66 67def test_every_shard_of_every_choice (self ): 68for fam_name ,fam in {** setup .FAMILIES ,** setup .OWN_PATH_FAMILIES }.items (): 69if fam .get ("ready" ):# ready-made packs: pinned file by file (ready_files) 70continue 71for model in (setup .MODELS if fam_name in setup .FAMILIES else fam ["models" ]): 72if fam_name in setup .FAMILIES and fam_name not in setup .MODELS [model ].get ("families" , ("qwen" ,"swift" )): 73continue 74with self .subTest (family = fam_name ,model = model ): 75if fam_name in setup .FAMILIES : 76for i in range (1 ,setup .model_shards (fam ,model )+ 1 ): 77self .pinned (fam ["hf" ].format (q = model )+ setup .model_file (fam ,model ,i )) 78else : 79self .pinned (fam ["hf" ]+ fam ["file" ].format (q = model )) 80 81def test_the_picture_reader_of_every_family (self ): 82for name ,fam in {** setup .FAMILIES ,** setup .OWN_PATH_FAMILIES }.items (): 83with self .subTest (family = name ): 84self .pinned (fam ["mmproj_hf" ]+ fam ["mmproj" ]) 85 86def test_the_nvfp4_packs_still_pin_their_files (self ): 87for model in setup .MODELS : 88if setup .MODELS [model ].get ("repo" ): 89for f in setup .ready_files (model ): 90self .assertRegex (f [5 ],HEX ) 91 92def test_every_pin_is_well_formed_and_every_repository_is_pinned (self ): 93for repo ,files in setup .REPO_PINS .items (): 94self .assertIn (repo ,setup .HF_REVISIONS ) 95for name , (size ,sha )in files .items (): 96with self .subTest (repo = repo ,file = name ): 97self .assertIsInstance (size ,int ) 98self .assertGreater (size ,1000 ) 99self .assertRegex (sha ,HEX ) 100 101def test_known_values (self ): 102# the Hub's LFS pointers; the picture reader is the same file the NVFP4 family already pinned 103self .assertEqual (setup .file_pin (pinned_url ("mmproj-Qwen3.8-Flash-Next-BF16.gguf" )), 104setup .FAMILIES ["nvfp4" ]["mmproj_sha256" ]) 105self .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 108shard2 = {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" )} 110self .assertEqual (len (shard2 ),1 ) 111self .assertEqual (setup .CODER_FILES ["Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf" ],shard2 .pop ()) 112 113def test_an_unknown_file_has_no_pin (self ): 114self .assertIsNone (setup .file_pin (pinned_url ("nothing.gguf" ))) 115self .assertIsNone (setup .file_pin ("https://example.com/a/b/resolve/main/x.gguf" )) 116 117 118class DownloadChecksThePin (unittest .TestCase ): 119def serve (self ,body ,length = None ): 120seen = [] 121 122def urlopen (req ,timeout = None ): 123seen .append (req .get_method ()) 124if req .get_method ()== "HEAD" : 125return Response (b"" ,length = length ) 126return Response (body ,status = 200 ) 127 128return seen ,mock .patch .object (setup .netpolicy ,"urlopen" ,urlopen ) 129 130def run_download (self ,name ,served ,pinned ,length = None ): 131seen ,patch = self .serve (served ,length if length is not None else len (served )) 132with tempfile .TemporaryDirectory ()as d ,with_pin (name ,pinned ),patch , \ 133mock .patch .dict (setup .os .environ , {"STRATA_SOURCE" :"huggingface" }): 134setup .os .environ .pop ("STRATA_ALLOW_UNPINNED" ,None ) 135dst = Path (d )/ name 136try : 137_ ,out = quiet (setup .download ,pinned_url (name ),dst ) 138code = None 139except SystemExit as e : 140code ,out = e .code ,"" 141result = (code ,dst .exists (),dst .with_name (dst .name + ".done" ).exists (), 142dst .with_name (dst .name + ".part" ).exists (), 143dst .with_name (dst .name + ".done" ).read_text ()if dst .with_name (dst .name + ".done" ).exists ()else "" ) 144return seen ,result 145 146def test_the_right_file_is_kept_with_its_hash_in_the_mark (self ): 147data = b"the model" * 100 148seen , (code ,exists ,marked ,part ,mark_text )= self .run_download ("t.gguf" ,data ,data ) 149self .assertIsNone (code ) 150self .assertTrue (exists and marked and not part ) 151self .assertIn ("sha256 " + hashlib .sha256 (data ).hexdigest (),mark_text ) 152 153def test_a_wrong_file_is_deleted_and_setup_stops (self ): 154data = b"the model" * 100 155wrong = b"THE MODEL" * 100 # the pinned size, another content 156seen , (code ,exists ,marked ,part ,_ )= self .run_download ("t.gguf" ,wrong ,data ) 157self .assertEqual (code ,1 ) 158self .assertFalse (exists or marked or part ) 159 160def test_a_wrong_size_stops_before_the_download (self ): 161data = b"the model" * 100 162seen , (code ,exists ,marked ,part ,_ )= self .run_download ("t.gguf" ,data + b"x" ,data ) 163self .assertEqual (code ,1 ) 164self .assertEqual (seen , ["HEAD" ])# no GET: nothing of the wrong file was fetched 165self .assertFalse (exists or marked or part ) 166 167 168class NotFoundOnThePinnedCommit (unittest .TestCase ): 169def urlopen (self ,seen ): 170def urlopen (req ,timeout = None ): 171seen .append ((req .get_method (),req .full_url )) 172if "/resolve/main/" not in req .full_url : 173raise urllib .error .HTTPError (req .full_url ,404 ,"Not Found" , {},None ) 174return Response (b"current file" ) 175return urlopen 176 177def test_it_stops_with_a_plain_message (self ): 178seen = [] 179out = io .StringIO () 180with tempfile .TemporaryDirectory ()as d ,mock .patch .object (setup .netpolicy ,"urlopen" ,self .urlopen (seen )), \ 181mock .patch .dict (setup .os .environ , {"STRATA_SOURCE" :"huggingface" }),contextlib .redirect_stdout (out ): 182setup .os .environ .pop ("STRATA_ALLOW_UNPINNED" ,None ) 183dst = Path (d )/ "t.gguf" 184with self .assertRaises (SystemExit ): 185setup .download (pinned_url ("Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" ),dst ,"the model" ) 186self .assertFalse (dst .exists ()) 187self .assertIn ("the pinned version of the model is no longer on Hugging Face" ,out .getvalue ()) 188self .assertIn ("update Strata" ,out .getvalue ()) 189self .assertEqual (len (seen ),1 )# no second try on main 190 191def test_the_opt_out_takes_the_current_file_and_says_so (self ): 192seen = [] 193with tempfile .TemporaryDirectory ()as d ,mock .patch .object (setup .netpolicy ,"urlopen" ,self .urlopen (seen )), \ 194mock .patch .dict (setup .os .environ , {"STRATA_SOURCE" :"huggingface" ,"STRATA_ALLOW_UNPINNED" :"1" }), \ 195mock .patch .object (setup ,"_unpinned_said" , []): 196dst = 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 ) 198self .assertEqual (dst .read_bytes (),b"current file" )# not checked against the pin: it is not the pinned file 199self .assertIn ("STRATA_ALLOW_UNPINNED=1" ,out ) 200 201def test_the_opt_out_is_off_by_default (self ): 202with mock .patch .dict (setup .os .environ , {},clear = False ): 203setup .os .environ .pop ("STRATA_ALLOW_UNPINNED" ,None ) 204self .assertFalse (setup .allow_unpinned ()) 205for value in ("" ,"0" ,"no" ): 206setup .os .environ ["STRATA_ALLOW_UNPINNED" ]= value 207self .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 213def test_an_installed_file_is_not_asked_for (self ): 214def urlopen (req ,timeout = None ): 215raise AssertionError ("network used for an installed file: " + req .full_url ) 216 217with tempfile .TemporaryDirectory ()as d ,mock .patch .object (setup .netpolicy ,"urlopen" ,urlopen ), \ 218mock .patch .dict (setup .os .environ , {"HF_ENDPOINT" :"http://127.0.0.1:9" ,"STRATA_SOURCE" :"auto" }): 219dst = Path (d )/ "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" 220dst .write_bytes (b"installed by an earlier setup" )# no hash in its mark (installed before the pins) 221setup .mark (dst ) 222_ ,out = quiet (setup .download ,pinned_url ("Q2_0/" + dst .name ),dst ) 223self .assertIn ("already downloaded" ,out ) 224self .assertEqual (dst .read_bytes (),b"installed by an earlier setup" )# kept, not hashed, not deleted 225 226def test_a_dead_host_is_reported_for_a_download_only (self ): 227def urlopen (req ,timeout = None ): 228raise urllib .error .URLError ("no route to host" ) 229 230with tempfile .TemporaryDirectory ()as d ,mock .patch .object (setup .netpolicy ,"urlopen" ,urlopen ), \ 231mock .patch .object (setup .time ,"sleep" ,lambda s :None ), \ 232mock .patch .dict (setup .os .environ , {"STRATA_SOURCE" :"huggingface" }): 233with self .assertRaises (SystemExit ): 234quiet (setup .download ,pinned_url ("Q2_0/x.gguf" ),Path (d )/ "x.gguf" ) 235 236def 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 238tools only (and strata_control.acquisition refuses a download under STRATA_NO_ACQUIRE=1).""" 239hosts = 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). 246harmless = ('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)' ) 251found = [] 252for folder in ("strata_cli" ,"serve" ,"strata_control" ): 253for p in (ROOT / folder ).rglob ("*.py" ): 254if "test" in p .name : 255continue 256text = p .read_text (encoding = "utf-8" ,errors = "replace" ) 257for line in harmless : 258text = text .replace (line ,"" ) 259if hosts .search (text ): 260found .append (str (p .relative_to (ROOT ))) 261self .assertEqual (found , []) 262 263def test_a_download_is_refused_while_serving (self ): 264from strata_control import acquisition 265with acquisition .forbidden (): 266with self .assertRaises (acquisition .AcquisitionRefused ): 267setup .download (pinned_url ("Q2_0/x.gguf" ),Path (tempfile .gettempdir ())/ "strata-never.gguf" ) 268 269 270if __name__ == "__main__" : 271unittest .main ()