okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""Tests for tools/mtp_fetch.py (#327): a range read needs a 206 with the asked Content-Range, the pinned revision's 2tensors are checked against their sha256 (a wrong one is fetched again; a corrupt install is found by `verify` and 3setup fetches it again), and an inventory from another revision is read again. A fake checkpoint behind a mocked 4urlopen - nothing is downloaded. 5 6python -m unittest tools.test_mtp_fetch 7""" 8from __future__import annotations 9 10import contextlib 11import hashlib 12import io 13import json 14import os 15import struct 16import sys 17import tempfile 18import unittest 19from pathlib import Path 20from unittest import mock 21 22ROOT = Path (__file__ ).resolve ().parents [1 ] 23sys .path .insert (0 ,str (ROOT )) 24sys .path .insert (0 ,str (ROOT / "tools" )) 25import mtp_fetch as M # noqa: E402 26 27 28def shard (tensors ): 29"""A safetensors file: [u64 header length][JSON header][data].""" 30header ,data = {},b"" 31for name ,blob in tensors : 32header [name ]= {"dtype" :"BF16" ,"shape" : [len (blob )// 2 ],"data_offsets" : [len (data ),len (data )+ len (blob )]} 33data += blob 34h = json .dumps (header ).encode () 35return struct .pack ("<Q" ,len (h ))+ h + data 36 37 38A ,B ,X = bytes (range (64 )),bytes (range (100 ,164 ))* 2 ,b"\x07" * 48 39FILES = {"model-1.safetensors" :shard ([("model.x" ,X ), ("mtp.a" ,A )]),"model-2.safetensors" :shard ([("mtp.b" ,B )])} 40INDEX = json .dumps ({"weight_map" : {"model.x" :"model-1.safetensors" ,"mtp.a" :"model-1.safetensors" , 41"mtp.b" :"model-2.safetensors" }}).encode () 42HASHES = {"mtp.a" :hashlib .sha256 (A ).hexdigest (),"mtp.b" :hashlib .sha256 (B ).hexdigest ()} 43 44 45class Response (io .BytesIO ): 46def __init__ (self ,body ,status ,headers ): 47super ().__init__ (body ) 48self .status ,self .headers = status ,headers 49 50def __enter__ (self ): 51return self 52 53def __exit__ (self ,* exc ): 54self .close () 55 56 57class Mirror : 58"""urlopen for the fake checkpoint. `ignore_range`: 200 and the whole file (`cut`: cut to the asked length, as 59the proxy in #327 did); `wrong`: the bytes of these tensors' ranges are flipped (a source that sends bad data).""" 60 61def __init__ (self ,ignore_range = False ,cut = False ,wrong = ()): 62self .ignore_range ,self .cut ,self .wrong ,self .ranges = ignore_range ,cut ,set (wrong ), [] 63 64def __call__ (self ,req ,timeout = None ): 65name = req .full_url .rsplit ("/" ,1 )[1 ] 66body = INDEX if name == "model.safetensors.index.json" else FILES [name ] 67rng = req .get_header ("Range" ) 68if rng is None : 69return Response (body ,200 , {"Content-Length" :str (len (body ))}) 70a ,b = map (int ,rng .split ("=" )[1 ].split ("-" )) 71self .ranges .append ((name ,a ,b )) 72if self .ignore_range : 73return Response (body [:b - a + 1 ]if self .cut else body ,200 , {}) 74part = body [a :b + 1 ] 75if any (t in self .wrong and self .span (name ,t )== (a ,b )for t in ("mtp.a" ,"mtp.b" )): 76part = bytes (x ^ 0xFF for x in part ) 77return Response (part ,206 , {"Content-Range" :"bytes %d-%d/%d" % (a ,b ,len (body ))}) 78 79@staticmethod 80def span (name ,tensor ): 81raw = FILES [name ] 82n = struct .unpack ("<Q" ,raw [:8 ])[0 ] 83meta = json .loads (raw [8 :8 + n ]).get (tensor ) 84return (8 + n + meta ["data_offsets" ][0 ],8 + n + meta ["data_offsets" ][1 ]- 1 )if meta else None 85 86 87class FetchCase (unittest .TestCase ): 88def setUp (self ): 89self .tmp = tempfile .TemporaryDirectory () 90self .out = Path (self .tmp .name ) 91self .patches = [mock .patch .object (M ,"SHA256" ,HASHES ),mock .patch .object (M .time ,"sleep" ,lambda s :None ), 92mock .patch .object (M ,"REPO" ,M .PINNED )] 93for p in self .patches : 94p .start () 95 96def tearDown (self ): 97for p in reversed (self .patches ): 98p .stop () 99self .tmp .cleanup () 100 101def fetch (self ,mirror ): 102with mock .patch .object (M .netpolicy ,"urlopen" ,mirror ),contextlib .redirect_stdout (io .StringIO ()), \ 103contextlib .redirect_stderr (io .StringIO ())as err : 104M .fetch (str (self .out ),None ) 105return err .getvalue () 106 107def tensor (self ,name ): 108return (self .out / "tensors" / (name + ".bin" )).read_bytes () 109 110 111class Ranges (FetchCase ): 112def test_check_range (self ): 113M .check_range (206 ,"bytes 10-19/100" ,10 ,19 ) 114for status ,cr in ((200 ,None ), (200 ,"bytes 10-19/100" ), (206 ,"bytes 0-9/100" ), (206 ,None )): 115with self .subTest (status = status ,cr = cr ),self .assertRaises (IOError ): 116M .check_range (status ,cr ,10 ,19 ) 117 118def test_a_mirror_that_ignores_range_is_refused (self ): 119for cut in (False ,True ):# the whole file, or cut to the asked length (#327's proxy) 120with self .subTest (cut = cut ),mock .patch .object (M .netpolicy ,"urlopen" ,Mirror (True ,cut )), \ 121contextlib .redirect_stderr (io .StringIO ()),self .assertRaisesRegex (IOError ,"not honoured" ): 122M .get (M .REPO + "model-1.safetensors" ,8 ,15 ) 123 124def test_fetch_from_an_honest_mirror (self ): 125self .fetch (Mirror ()) 126self .assertEqual ((self .tensor ("mtp.a" ),self .tensor ("mtp.b" )), (A ,B )) 127manifest = json .loads ((self .out / "mtp-manifest.json" ).read_text ()) 128self .assertEqual ({r ["name" ]:r ["sha256" ]for r in manifest },HASHES ) 129self .assertEqual (M .verify (str (self .out )), []) 130 131def test_ranges_are_read_in_parallel_and_come_back_in_order (self ): 132data = bytes (range (256 ))* 40 133seen = [] 134 135def get (url ,a ,b ): 136seen .append ((a ,b )) 137return data [a :b + 1 ] 138 139for workers in (1 ,4 ,32 ): 140seen .clear () 141with self .subTest (workers = workers ),mock .patch .object (M ,"get" ,get ): 142got = b"" .join (M .ranged ("u" ,100 ,len (data )- 1 ,1000 ,workers )) 143self .assertEqual (got ,data [100 :]) 144self .assertEqual (sorted (seen )[0 ], (100 ,1099 )) 145with mock .patch .dict (M .os .environ , {"STRATA_DL_CONNECTIONS" :"1" }): 146self .assertEqual (M .connections (),1 ) 147with mock .patch .dict (M .os .environ , {"STRATA_DL_CONNECTIONS" :"" }): 148self .assertEqual (M .connections (),16 ) 149 150def test_the_cdn_address_is_reused_and_forgotten_after_an_error (self ): 151"""HF redirects /resolve/ to a signed CDN address: only the first range goes through the redirect (the rest of a 152tensor's ranges use the CDN address), and any error makes the next try ask the original address again.""" 153asked = [] 154 155def opener (req ,timeout = None ): 156asked .append (req .full_url ) 157a ,b = (int (x )for x in req .headers ["Range" ].split ("=" )[1 ].split ("-" )) 158r = Response (bytes (b - a + 1 ),206 , {"Content-Range" :"bytes %d-%d/1000" % (a ,b )}) 159r .geturl = lambda :"https://cdn.example/x?sig=1" 160return r 161 162M ._cdn .clear () 163with mock .patch .object (M .netpolicy ,"urlopen" ,opener ): 164for a in (0 ,100 ,200 ): 165M .get ("https://hf.example/f" ,a ,a + 99 ) 166self .assertEqual (asked , ["https://hf.example/f" ]+ ["https://cdn.example/x?sig=1" ]* 2 ) 167asked .clear () 168fails = [True ] 169 170def flaky (req ,timeout = None ): 171if fails .pop ()if fails else False : 172raise IOError ("expired" ) 173return opener (req ,timeout ) 174 175with mock .patch .object (M .netpolicy ,"urlopen" ,flaky ),mock .patch .object (M .time ,"sleep" ,lambda s :None ),contextlib .redirect_stderr (io .StringIO ()): 176M .get ("https://hf.example/f" ,300 ,399 ) 177self .assertEqual (asked , ["https://hf.example/f" ])# the cached address failed: the original is asked again 178M ._cdn .clear () 179 180def test_a_slow_first_range_does_not_stop_the_ones_behind_it (self ): 181import threading 182gate = threading .Event () 183started = [] 184 185def get (url ,a ,b ): 186started .append (a ) 187if a == 0 : 188gate .wait (5 ) 189return bytes (b - a + 1 ) 190 191def release ():# lets the first range go once the later ones have been started 192for _ in range (200 ): 193if len (started )>= 9 : 194break 195M .time .sleep (0.01 ) 196gate .set () 197 198threading .Thread (target = release ,daemon = True ).start () 199with mock .patch .object (M ,"get" ,get ): 200list (M .ranged ("u" ,0 ,40 * 1000 - 1 ,1000 ,4 )) 201self .assertGreaterEqual (len (started ),9 )# four connections, nine ranges started before range 0 ended 202 203def test_a_failing_range_stops_the_parallel_read (self ): 204def get (url ,a ,b ): 205if a >= 2000 : 206raise IOError ("boom" ) 207return bytes (b - a + 1 ) 208 209with mock .patch .object (M ,"get" ,get ),self .assertRaises (IOError ): 210list (M .ranged ("u" ,0 ,9999 ,1000 ,4 )) 211 212def test_wrong_bytes_are_fetched_again_once_then_refused (self ): 213self .fetch (Mirror ()) 214bad = bytes (len (A ))# an install the #327 mirror corrupted: right size, wrong bytes 215 (self .out / "tensors" / "mtp.a.bin" ).write_bytes (bad ) 216self .assertEqual (M .verify (str (self .out )), ["mtp.a" ]) 217err = self .fetch (Mirror ())# setup runs fetch again: the bad one is fetched again 218self .assertIn ("mtp.a: wrong bytes" ,err ) 219self .assertEqual (self .tensor ("mtp.a" ),A ) 220self .assertEqual (M .verify (str (self .out )), []) 221os .remove (self .out / "tensors" / "mtp.b.bin" ) 222with self .assertRaises (SystemExit )as cm : 223self .fetch (Mirror (wrong = {"mtp.b" }))# a source that keeps sending wrong data 224self .assertIn ("is not the checkpoint's" ,str (cm .exception )) 225self .assertFalse ((self .out / "tensors" / "mtp.b.bin" ).exists ()) 226 227def test_an_inventory_from_another_revision_is_read_again (self ): 228self .fetch (Mirror ()) 229inv = json .loads ((self .out / "mtp-inventory.json" ).read_text ()) 230inv ["repo" ]= "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/" 231for r in inv ["tensors" ]: 232r ["start" ]+= 1 # that revision's ranges: not this one's 233r ["end" ]+= 1 234 (self .out / "mtp-inventory.json" ).write_text (json .dumps (inv )) 235 (self .out / "tensors" / "mtp.b.bin" ).write_bytes (B [:10 ])# half a tensor from that revision 236mirror = Mirror () 237self .fetch (mirror ) 238self .assertEqual (json .loads ((self .out / "mtp-inventory.json" ).read_text ())["repo" ],M .REPO ) 239self .assertEqual ((self .tensor ("mtp.a" ),self .tensor ("mtp.b" )), (A ,B )) 240fetched = [r for r in mirror .ranges if r [2 ]- r [1 ]+ 1 in (len (A ),len (B ))] 241self .assertEqual (fetched , [("model-2.safetensors" ,)+ Mirror .span ("model-2.safetensors" ,"mtp.b" )], 242"mtp.a was right and is kept; mtp.b is fetched whole" ) 243 244def test_verify_keeps_its_verdict_and_skips_other_revisions (self ): 245self .fetch (Mirror ()) 246self .assertEqual (M .verify (str (self .out )), []) 247stamps = json .loads ((self .out / "tensors" / "verified.json" ).read_text ()) 248self .assertEqual (sorted (stamps ), ["mtp.a" ,"mtp.b" ]) 249with mock .patch .object (M ,"sha256_of" ,side_effect = AssertionError ("hashed an unchanged file" )): 250self .assertEqual (M .verify (str (self .out )), []) 251with mock .patch .object (M ,"REPO" ,"https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/" ): 252 (self .out / "tensors" / "mtp.a.bin" ).write_bytes (b"x" ) 253self .assertEqual (M .verify (str (self .out )), [])# STRATA_MTP_REVISION: other hashes 254self .assertEqual (M .verify (str (self .out )), ["mtp.a" ]) 255self .assertEqual (M .verify (str (self .out / "nothing" )), []) 256 257 258class Pinned (unittest .TestCase ): 259def test_every_tensor_has_a_hash (self ): 260self .assertEqual (len (M .SHA256 ),31 ) 261for name ,h in M .SHA256 .items (): 262self .assertTrue (name .startswith ("mtp." )) 263self .assertRegex (h ,"^[0-9a-f]{64}$" ) 264self .assertIn (M .PINNED_REVISION ,M .PINNED ) 265 266 267class Setup (unittest .TestCase ): 268def test_setup_rebuilds_a_corrupt_install (self ): 269import setup 270with tempfile .TemporaryDirectory ()as d : 271mtp = Path (d ) 272self .assertFalse (setup .mtp_corrupt (mtp ))# no tensors kept: nothing to check 273 (mtp / "tensors" ).mkdir () 274for code ,want in ((0 ,False ), (3 ,True ), (1 ,False )): 275with self .subTest (code = code ),mock .patch .object ( 276setup .subprocess ,"run" ,return_value = mock .Mock (returncode = code ))as run : 277self .assertEqual (setup .mtp_corrupt (mtp ),want ) 278self .assertIn ("verify" ,run .call_args [0 ][0 ]) 279 280 281 282 283class Progress (FetchCase ): 284"""#3257: the fetch says how far it is in the form of setup's own download line, so the app can show it.""" 285 286def test_progress_lines_name_the_whole_download_and_end_at_100 (self ): 287err = self .fetch (Mirror ()) 288lines = [x for x in err .splitlines ()if "MTP draft layer:" in x ] 289total = len (A )+ len (B ) 290self .assertTrue (lines ) 291self .assertIn ("/ %.2f GB" % (total / 1e9 ),lines [- 1 ]) 292self .assertIn ("(100%)" ,lines [- 1 ]) 293import re 294for x in lines :# the shape tools/strata_mcp.py install_progress reads 295self .assertTrue (re .match (r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)" ,x ),x ) 296 297def test_a_resumed_fetch_starts_from_what_is_already_there (self ): 298self .fetch (Mirror ()) 299err = self .fetch (Mirror ()) 300self .assertIn ("(100%)" , [x for x in err .splitlines ()if "MTP draft layer:" in x ][0 ]) 301 302def test_the_progress_figure_follows_the_job_in_strata_mcp (self ): 303import strata_mcp as MCP 304got = MCP .install_progress (["=== Step 6: preparing the model for Strata ===" , 305" MTP draft layer: 1.23 / 5.04 GB (24%)" ]) 306self .assertEqual (got ["download" ], {"file" :"MTP draft layer" ,"done_gb" :1.23 ,"total_gb" :5.04 ,"percent" :24 }) 307 308 309class Flaky (FetchCase ): 310def test_a_connection_that_drops_mid_tensor_does_not_end_the_run (self ): 311"""#3214: every range of the tensor fails past get()'s own retries once: the tensor is tried again (fewer connections).""" 312honest ,fails = Mirror (), [0 ] 313 314def mirror (req ,timeout = None ): 315if req .get_header ("Range" )and req .full_url .endswith ("model-2.safetensors" )and fails [0 ]< 12 : 316a ,b = map (int ,req .get_header ("Range" ).split ("=" )[1 ].split ("-" )) 317if (a ,b )== Mirror .span ("model-2.safetensors" ,"mtp.b" ): 318fails [0 ]+= 1 319raise IOError ("timed out" ) 320return honest (req ,timeout ) 321 322err = self .fetch (mirror ) 323self .assertEqual (self .tensor ("mtp.b" ),B ) 324self .assertIn ("continuing with" ,err ) 325 326def test_a_link_that_never_works_ends_with_a_plain_sentence (self ): 327def mirror (req ,timeout = None ): 328if req .get_header ("Range" )and req .full_url .endswith ("model-2.safetensors" ): 329a ,b = map (int ,req .get_header ("Range" ).split ("=" )[1 ].split ("-" )) 330if (a ,b )== Mirror .span ("model-2.safetensors" ,"mtp.b" ): 331raise IOError ("timed out" ) 332return Mirror ()(req ,timeout ) 333 334with self .assertRaisesRegex (SystemExit ,"keeps failing" ): 335self .fetch (mirror ) 336 337 338class OneAtATime (unittest .TestCase ): 339def test_a_second_fetch_in_the_same_folder_waits_for_the_first (self ): 340with tempfile .TemporaryDirectory ()as d : 341first = M .lock_folder (d ) 342told = io .StringIO () 343with mock .patch .object (M .time ,"sleep" ,lambda s :None ),contextlib .redirect_stderr (told ), \ 344self .assertRaisesRegex (SystemExit ,"another MTP download" ): 345M .lock_folder (d ,wait = 0.0 ) 346first .close () 347M .lock_folder (d ).close ()# free again once the first ends 348 349def test_a_download_ends_with_the_process_that_started_it (self ): 350"""#3257: setup killed, its child must not go on: a grandchild whose parent is gone.""" 351import subprocess 352import time 353child_code = ("import sys,time; sys.path.insert(0, %r); import mtp_fetch as M; M.exit_with_parent(); " 354"print('up', flush=True); time.sleep(60)" % str (ROOT / "tools" )) 355parent_code = ("import subprocess,sys,os; env=dict(os.environ, STRATA_EXIT_WITH_PARENT='1'); " 356"p=subprocess.Popen([sys.executable,'-c',%r], env=env, stdout=subprocess.PIPE, text=True); " 357"print(p.pid, flush=True); p.stdout.readline(); print('ready', flush=True); sys.stdout.flush(); os._exit(0)" % child_code ) 358r = subprocess .Popen ([sys .executable ,"-c" ,parent_code ],stdout = subprocess .PIPE ,text = True ) 359pid = int (r .stdout .readline ()) 360r .stdout .readline () 361r .wait (30 ) 362end = time .time ()+ 15 363alive = True 364while time .time ()< end and alive : 365time .sleep (0.5 ) 366if os .name == "nt" : 367out = subprocess .run (["tasklist" ,"/FI" ,"PID eq %d" % pid ],capture_output = True ,text = True ).stdout 368alive = str (pid )in out 369else : 370try : 371os .kill (pid ,0 ) 372alive = True 373except OSError : 374alive = False 375if alive : 376if os .name == "nt" : 377subprocess .run (["taskkill" ,"/PID" ,str (pid ),"/F" ],capture_output = True ) 378else : 379os .kill (pid ,9 ) 380self .assertFalse (alive ,"the download kept running after its parent ended" ) 381 382 383if __name__ == "__main__" : 384unittest .main ()