okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""Tests for setup.py's parallel ranged downloads (0.2.0): a local threaded HTTP server that supports Range stands in 2for Hugging Face's CDN. Covers the parallel path, a resume after a kill and after a failed round, a server without Range, 3a piece that fails once, a signed address that runs out, the SHA-256 pin, STRATA_DL_CONNECTIONS=1 and the progress line. 4 5python -m unittest tools.test_setup_download 6""" 7from __future__import annotations 8 9import contextlib 10import hashlib 11import http .server 12import io 13import json 14import os 15import re 16import subprocess 17import sys 18import tempfile 19import threading 20import time 21import unittest 22from pathlib import Path 23from unittest import mock 24 25ROOT = Path (__file__ ).resolve ().parents [1 ] 26sys .path .insert (0 ,str (ROOT )) 27sys .path .insert (0 ,str (ROOT / "tools" )) 28import setup # noqa: E402 29import strata_mcp # noqa: E402 30 31CHUNK = 64 << 10 # the tests' piece size (setup uses 32 MiB) 32DATA = bytes ((i * 7 + (i >> 8 ))& 0xFF for i in range (CHUNK * 40 + 12345 ))# 40 whole pieces and a short last one 33BIG = (bytes ((i * 11 + (i >> 9 ))& 0xFF for i in range (1 << 16 ))* 170 )[:(10 << 20 )+ 12345 ]# 10 MiB and a bit: longer than the one-stream read 34NAME = "t.gguf" 35 36 37class Server : 38"""A threaded HTTP server for one file. `faults(path, start, end, nth)` may answer a request with an error.""" 39 40def __init__ (self ,data = DATA ,ranges = True ,length = True ,redirect = False ,delay = 0.002 ,faults = None ,hold_from = None ): 41self .data ,self .ranges ,self .length ,self .redirect ,self .delay = data ,ranges ,length ,redirect ,delay 42self .faults = faults 43# hold_from: a body byte at this file offset or later is not sent until the "release" event is set (the headers and every byte before it are): 44# a client is at a known place, with no timing in it, until the test lets go (a kill test; release.set() also frees the handlers) 45self .hold_from ,self .release = hold_from ,threading .Event () 46self .lock = threading .Lock () 47self .gets ,self .heads ,self .redirects = [],0 ,0 # gets: (start, end) of every ranged GET 48self .active = self .max_active = 0 49self .streams = self .max_streams = 0 # the same without setup's one-byte probes (Range: bytes=0-0) 50self .nth = {} 51outer = self 52 53class Handler (http .server .BaseHTTPRequestHandler ): 54def log_message (self ,* a ): 55pass 56 57def do_HEAD (self ): 58outer .handle (self ,head = True ) 59 60def do_GET (self ): 61outer .handle (self ,head = False ) 62 63self .httpd = http .server .ThreadingHTTPServer (("127.0.0.1" ,0 ),Handler ) 64self .httpd .daemon_threads = True 65self .port = self .httpd .server_address [1 ] 66self .thread = threading .Thread (target = self .httpd .serve_forever ,daemon = True ) 67 68@property 69def url (self ): 70return f"http://127.0.0.1: { self . port } / { NAME } " 71 72def __enter__ (self ): 73self .thread .start () 74return self 75 76def __exit__ (self ,* exc ): 77self .httpd .shutdown () 78self .httpd .server_close () 79 80def handle (self ,h ,head ): 81path = h .path .split ("?" )[0 ] 82if self .redirect and path == "/" + NAME : 83with self .lock : 84self .redirects += 1 85h .send_response (302 ) 86h .send_header ("Location" ,f"http://127.0.0.1: { self . port } /cdn/ { NAME } ?Expires= { int ( time . time ()) + 3600 } &Signature=x" ) 87h .send_header ("Content-Length" ,"0" ) 88h .end_headers () 89return 90size = len (self .data ) 91rng = h .headers .get ("Range" ) 92start ,end = 0 ,size - 1 93if rng and self .ranges : 94m = re .match (r"bytes=(\d+)-(\d*)$" ,rng ) 95start = int (m .group (1 )) 96end = min (int (m .group (2 )),size - 1 )if m .group (2 )else size - 1 97if head : 98with self .lock : 99self .heads += 1 100h .send_response (200 ) 101if self .length : 102h .send_header ("Content-Length" ,str (size )) 103h .send_header ("Content-Type" ,"application/octet-stream" ) 104h .end_headers () 105return 106with self .lock : 107self .gets .append ((start ,end )if rng and self .ranges else (0 ,size - 1 )) 108key = (start ,end ) 109self .nth [key ]= n = self .nth .get (key ,0 )+ 1 110self .active += 1 111self .max_active = max (self .max_active ,self .active ) 112probe = rng == "bytes=0-0" 113if not probe : 114self .streams += 1 115self .max_streams = max (self .max_streams ,self .streams ) 116try : 117fault = self .faults (path ,start ,end ,n )if self .faults else None 118if fault and fault [0 ]== "status" : 119h .send_response (fault [1 ]) 120h .send_header ("Content-Length" ,"0" ) 121h .end_headers () 122return 123body = self .data [start :end + 1 ] 124if rng and self .ranges : 125h .send_response (206 ) 126h .send_header ("Content-Range" ,f"bytes { start } - { end } / { size } " ) 127else : 128h .send_response (200 ) 129h .send_header ("Content-Length" ,str (len (body ))) 130h .end_headers () 131cut = fault [1 ]if fault and fault [0 ]== "cut" else None 132try : 133for i in range (0 ,len (body ),16384 ): 134if self .hold_from is not None and start + i >= self .hold_from : 135self .release .wait (120 ) 136if cut is not None and i >= cut : 137h .connection .shutdown (2 )# the connection drops in the middle of the body 138return 139h .wfile .write (body [i :i + 16384 ]) 140if self .delay : 141time .sleep (self .delay ) 142except OSError : 143pass 144finally : 145with self .lock : 146self .active -= 1 147if not probe : 148self .streams -= 1 149 150 151def pin_of (data ): 152return len (data ),hashlib .sha256 (data ).hexdigest () 153 154 155@ contextlib . contextmanager 156def small_pieces (** extra ): 157"""Setup's piece size, size floor and waits scaled down to the test file.""" 158consts = dict (DL_CHUNK = CHUNK ,DL_RUN = 1 ,DL_MIN_PARALLEL = 0 ,DL_BACKOFF = 0.0 ,DL_SAVE_EVERY = 0.05 ,DL_CONNECTIONS = 4 ) 159consts .update (extra ) 160with contextlib .ExitStack ()as st : 161for k ,v in consts .items (): 162st .enter_context (mock .patch .object (setup ,k ,v )) 163st .enter_context (mock .patch .object (setup .time ,"sleep" ,lambda s :None )) 164env = {k :v for k ,v in os .environ .items ()if k not in ("STRATA_DL_CONNECTIONS" ,"STRATA_ALLOW_UNPINNED" )} 165env ["STRATA_SOURCE" ]= "huggingface" 166st .enter_context (mock .patch .dict (os .environ ,env ,clear = True )) 167yield 168 169 170def run (server ,d ,pin = "auto" ,name = NAME ): 171"""setup.download() of the server's file into folder d; returns (exit code or None, stdout).""" 172dst = Path (d )/ name 173want = pin_of (DATA )if pin == "auto" else pin 174out = io .StringIO () 175code = None 176with mock .patch .object (setup ,"file_pin" ,lambda u :want ),contextlib .redirect_stdout (out ): 177try : 178setup .download (server .url ,dst ,"the model" ) 179except SystemExit as e : 180code = e .code if e .code is not None else 0 181return code ,out .getvalue () 182 183 184def asked (srv ): 185"""The pieces (indexes) the server was asked for, one entry per request; the one-byte probe is left out, and so is the 186plain whole-file GET that Python before 3.13 sends when it follows the HEAD's redirect (urllib turns the redirected HEAD into 187a GET and the download closes it at once); no piece is that big.""" 188whole = (0 ,len (srv .data )- 1 ) 189return [s // CHUNK for s ,e in srv .gets if (s ,e )not in ((0 ,0 ),whole )] 190 191 192def files (d ): 193return sorted (p .name for p in Path (d ).iterdir ()) 194 195 196class ParallelDownload (unittest .TestCase ): 197def test_a_big_file_comes_over_several_connections (self ): 198with small_pieces (),Server (redirect = True )as srv ,tempfile .TemporaryDirectory ()as d : 199code ,out = run (srv ,d ) 200self .assertIsNone (code ,out ) 201self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 202self .assertEqual (files (d ), [NAME ,NAME + ".done" ])# no .part, no piece list left behind 203self .assertIn ("sha256 " + hashlib .sha256 (DATA ).hexdigest (), (Path (d )/ (NAME + ".done" )).read_text ()) 204self .assertGreater (srv .max_active ,1 ) 205self .assertLessEqual (srv .max_active ,4 ) 206self .assertEqual (sorted (asked (srv )),list (range (41 )))# every piece once, none twice 207self .assertEqual (srv .redirects ,2 )# HEAD and the one probe: the pieces use the CDN address 208 209def test_the_redirect_is_resolved_once (self ): 210with small_pieces (),Server (redirect = True )as srv ,tempfile .TemporaryDirectory ()as d : 211code ,out = run (srv ,d ) 212self .assertIsNone (code ,out ) 213self .assertLessEqual (srv .redirects ,2 ) 214 215def test_a_small_file_is_one_stream (self ): 216with small_pieces (DL_MIN_PARALLEL = len (DATA )+ 1 ),Server ()as srv ,tempfile .TemporaryDirectory ()as d : 217code ,out = run (srv ,d ) 218self .assertIsNone (code ,out ) 219self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 220self .assertEqual (srv .max_streams ,1 )# (the one-byte probe can still be sending: not a stream) 221self .assertEqual (len (srv .gets ),1 ) 222 223def test_one_connection_variable_restores_one_stream (self ): 224with small_pieces (),Server ()as srv ,tempfile .TemporaryDirectory ()as d : 225with mock .patch .dict (os .environ , {"STRATA_DL_CONNECTIONS" :"1" }): 226code ,out = run (srv ,d ) 227self .assertIsNone (code ,out ) 228self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 229self .assertEqual (srv .max_streams ,1 )# (the one-byte probe can still be sending: not a stream) 230self .assertEqual (srv .gets , [(0 ,len (DATA )- 1 )])# one request for the whole file 231 232def test_connection_count_variable (self ): 233with small_pieces (): 234self .assertEqual (setup .dl_connections (),4 ) 235for raw ,want in (("16" ,16 ), ("0" ,1 ), ("-3" ,1 ), ("99" ,32 ), ("x" ,4 ), ("" ,4 )): 236with mock .patch .dict (os .environ , {"STRATA_DL_CONNECTIONS" :raw }): 237self .assertEqual (setup .dl_connections (),want ,raw ) 238 239 240class NoRangeSupport (unittest .TestCase ): 241def test_a_server_that_ignores_range_is_read_in_one_stream (self ): 242with small_pieces (),Server (ranges = False )as srv ,tempfile .TemporaryDirectory ()as d : 243code ,out = run (srv ,d ) 244self .assertIsNone (code ,out ) 245self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 246self .assertEqual (srv .max_streams ,1 )# (the one-byte probe can still be sending: not a stream) 247self .assertEqual (files (d ), [NAME ,NAME + ".done" ]) 248 249def test_a_server_without_any_length_is_read_in_one_stream (self ): 250with small_pieces (),Server (length = False ,ranges = False )as srv ,tempfile .TemporaryDirectory ()as d : 251code ,out = run (srv ,d ,pin = None )# no length, so nothing to check a pin against first 252self .assertIsNone (code ,out ) 253self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 254self .assertEqual (srv .max_streams ,1 )# (the one-byte probe can still be sending: not a stream) 255 256def test_a_head_without_a_length_still_gets_the_connections (self ): 257"""ModelScope's HEAD has no Content-Length (#1915): the length comes from a one-byte ranged GET, not 'unknown'.""" 258with small_pieces (),Server (length = False )as srv ,tempfile .TemporaryDirectory ()as d : 259code ,out = run (srv ,d ) 260self .assertIsNone (code ,out ) 261self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 262self .assertGreater (srv .max_active ,1 ) 263self .assertEqual (sorted (asked (srv )),list (range (41 ))) 264self .assertEqual (files (d ), [NAME ,NAME + ".done" ]) 265 266def test_range_stopping_in_the_middle_falls_back_to_the_unbroken_start (self ): 267def faults (path ,start ,end ,nth ): 268return None 269 270with small_pieces (),Server (faults = faults )as srv ,tempfile .TemporaryDirectory ()as d : 271real = setup ._fetch_run 272calls = [] 273 274def fetch (src ,st ,f ,run ): 275calls .append (run ) 276if len (calls )== 6 : 277raise setup ._NoRange ("HTTP 200" ) 278return real (src ,st ,f ,run ) 279 280with mock .patch .object (setup ,"_fetch_run" ,fetch ): 281code ,out = run (srv ,d ) 282self .assertIsNone (code ,out ) 283self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA )# the pin check passed: no gaps were kept 284self .assertEqual (files (d ), [NAME ,NAME + ".done" ]) 285 286 287class Resume (unittest .TestCase ): 288def test_a_failed_round_keeps_the_finished_pieces (self ): 289broken = {"on" :True } 290 291def faults (path ,start ,end ,nth ): 292if broken ["on" ]and start >= 20 * CHUNK : 293return ("status" ,500 ) 294return None 295 296with small_pieces (DL_ROUNDS = 1 ,DL_CHUNK_TRIES = 1 ),Server (faults = faults )as srv ,tempfile .TemporaryDirectory ()as d : 297code ,out = run (srv ,d ) 298self .assertEqual (code ,1 )# could not finish: setup stops with a message 299self .assertIn ("could not finish downloading" ,out ) 300part = Path (d )/ (NAME + ".part" ) 301side = Path (d )/ (NAME + ".part.chunks" ) 302self .assertTrue (part .exists ()and side .exists ()) 303saved = json .loads (side .read_text ()) 304done = {i for a ,b in saved ["done" ]for i in range (a ,b )} 305self .assertTrue (done and all (i < 20 for i in done ),done ) 306srv .gets .clear () 307broken ["on" ]= False 308code ,out = run (srv ,d ) 309self .assertIsNone (code ,out ) 310self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 311again = set (asked (srv )) 312self .assertFalse (again & done ,"pieces that were finished are fetched again" ) 313self .assertEqual (again | done ,set (range (41 ))) 314self .assertEqual (files (d ), [NAME ,NAME + ".done" ]) 315 316def killed_download_continues (self ,one_stream ): 317"""Kill setup.download in a subprocess once 12 pieces are on disk, then run it again: it continues and fetches none of them again. 318No timing decides this: the test server sends nothing from file offset HOLD on until the test has killed the runner (Server.hold_from), so the 319runner is always found part-way, however slow or fast the machine is. one_stream: the range probe fails in the runner, so setup reads the 320file in one stream (parallel_download returns False), whose .part is an unbroken run from the start.""" 321# The parallel path saves every finished piece, so 13 whole pieces may arrive and 12 are on disk before the kill. The one-stream path writes 322# what it reads in blocks of 8 MiB (setup.download_single), so its file must be longer than that: 8 MiB land on disk, then the server holds. 323data = BIG if one_stream else DATA 324HOLD = 9 << 20 if one_stream else 13 * CHUNK 325pin = (len (data ),hashlib .sha256 (data ).hexdigest ()) 326probe = "setup._probe_ranges = lambda *a, **k: False\n" if one_stream else "" 327runner = ( 328"import sys; sys.path[:0] = [%r, %r]\n" 329"import setup\n" 330"setup.DL_CHUNK = %d; setup.DL_MIN_PARALLEL = 0; setup.DL_SAVE_EVERY = 0.05; setup.DL_CONNECTIONS = 4\n" 331"%s" 332"pin = (%d, %r)\n" 333"setup.file_pin = lambda u: pin\n" 334"setup.download(sys.argv[1], __import__('pathlib').Path(sys.argv[2]) / %r, 'the model')\n" 335% (str (ROOT ),str (ROOT / "tools" ),CHUNK ,probe ,pin [0 ],pin [1 ],NAME )) 336with small_pieces (),Server (data = data ,hold_from = HOLD )as srv ,tempfile .TemporaryDirectory ()as d : 337self .addCleanup (srv .release .set )# never leave a handler thread waiting 338env = dict (os .environ ,STRATA_SOURCE = "huggingface" ) 339err = Path (d )/ "runner.err" 340with open (err ,"wb" )as err_file : 341proc = subprocess .Popen ([sys .executable ,"-c" ,runner ,srv .url ,d ],env = env , 342stdout = subprocess .DEVNULL ,stderr = err_file ) 343side = Path (d )/ (NAME + ".part.chunks" ) 344part = Path (d )/ (NAME + ".part" ) 345started = time .time () 346deadline = started + 60 347try : 348while time .time ()< deadline and proc .poll ()is None : 349try : 350if side .is_file (): 351if sum (b - a for a ,b in json .loads (side .read_text ())["done" ])>= 12 : 352break 353elif part .is_file ()and part .stat ().st_size >= 12 * CHUNK :# the one-stream fallback (below) 354break 355except (OSError ,ValueError ,KeyError ): 356pass 357threading .Event ().wait (0.02 )# (not time.sleep: small_pieces() makes that a no-op) 358finally : 359code = proc .poll () 360proc .kill () 361proc .wait () 362srv .release .set () 363state = "the runner %s after %.1f s; its stderr: %s" % ( 364"was still running" if code is None else "had already ended with exit code %s" % code ,time .time ()- started , 365err .read_text (errors = "replace" )[- 2000 :]or "(empty)" ) 366self .assertTrue (part .exists (),"the .part file is missing at the kill: " + state ) 367if side .exists (): 368saved = json .loads (side .read_text ()) 369done = {i for a ,b in saved ["done" ]for i in range (a ,b )} 370else : 371# One failed range probe makes setup read the file in one stream (parallel_download returns False): its .part is an 372# unbroken run from the start and has no piece list, which the next run reads as finished pieces (_load_pieces). 373# Seen on GitHub's Linux and macOS runners (run 42699343686); both ways must continue without fetching them again. 374done = set (range (part .stat ().st_size // CHUNK )) 375self .assertGreaterEqual (len (done ),12 ,"%d pieces at the kill; %s" % (len (done ),state )) 376srv .hold_from = None # the second run is not held 377srv .gets .clear () 378code ,out = run (srv ,d ,pin = pin ) 379self .assertIsNone (code ,out ) 380self .assertEqual ((Path (d )/ NAME ).read_bytes (),data ) 381self .assertFalse (set (asked (srv ))& done ,"pieces that were finished before the kill are fetched again" ) 382 383def test_a_killed_download_continues (self ): 384self .killed_download_continues (one_stream = False ) 385 386def test_a_killed_one_stream_download_continues (self ): 387self .killed_download_continues (one_stream = True ) 388 389def test_a_part_from_one_stream_continues_after_its_last_whole_piece (self ): 390with small_pieces (),Server ()as srv ,tempfile .TemporaryDirectory ()as d : 391have = CHUNK * 10 + 777 # an older setup's .part: bytes from the start 392 (Path (d )/ (NAME + ".part" )).write_bytes (DATA [:have ]) 393code ,out = run (srv ,d ) 394self .assertIsNone (code ,out ) 395self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 396self .assertEqual (sorted (asked (srv )),list (range (10 ,41 )))# pieces 0-9 were not asked for again 397 398def test_one_stream_continues_a_parallel_part_from_its_unbroken_start (self ): 399with small_pieces (),Server ()as srv ,tempfile .TemporaryDirectory ()as d : 400part = Path (d )/ (NAME + ".part" ) 401junk = bytearray (DATA ) 402junk [8 * CHUNK :9 * CHUNK ]= b"\0" * CHUNK # a gap behind the later pieces 403part .write_bytes (bytes (junk [:20 * CHUNK ])) 404 (Path (d )/ (NAME + ".part.chunks" )).write_text (json .dumps ( 405 {"v" :1 ,"total" :len (DATA ),"chunk" :CHUNK ,"done" : [[0 ,8 ], [9 ,20 ]]})) 406with mock .patch .dict (os .environ , {"STRATA_DL_CONNECTIONS" :"1" }): 407code ,out = run (srv ,d ) 408self .assertIsNone (code ,out ) 409self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 410self .assertEqual (srv .gets , [(8 * CHUNK ,len (DATA )- 1 )])# resumed after piece 7, the gap refetched 411self .assertEqual (files (d ), [NAME ,NAME + ".done" ]) 412 413def test_a_piece_list_of_another_file_starts_over (self ): 414with small_pieces (),Server ()as srv ,tempfile .TemporaryDirectory ()as d : 415 (Path (d )/ (NAME + ".part" )).write_bytes (b"x" * (CHUNK * 3 )) 416 (Path (d )/ (NAME + ".part.chunks" )).write_text (json .dumps ( 417 {"v" :1 ,"total" :999 ,"chunk" :CHUNK ,"done" : [[0 ,3 ]]})) 418code ,out = run (srv ,d ) 419self .assertIsNone (code ,out ) 420self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 421 422 423class Failures (unittest .TestCase ): 424def test_a_piece_that_fails_once_is_tried_again (self ): 425def faults (path ,start ,end ,nth ): 426if start == 5 * CHUNK and nth == 1 : 427return ("status" ,500 ) 428if start == 9 * CHUNK and nth == 1 : 429return ("cut" ,CHUNK // 2 )# drops half way: continues from where it was 430return None 431 432with small_pieces (),Server (faults = faults )as srv ,tempfile .TemporaryDirectory ()as d : 433code ,out = run (srv ,d ) 434self .assertIsNone (code ,out ) 435self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 436self .assertEqual (sum (1 for s ,_ in srv .gets if s == 5 * CHUNK ),2 ) 437self .assertEqual (sum (1 for s ,_ in srv .gets if s == 9 * CHUNK ),1 ) 438resumed = [s for s ,_ in srv .gets if 9 * CHUNK < s < 10 * CHUNK ] 439self .assertEqual (len (resumed ),1 )# the rest of the piece, not all of it again 440self .assertGreater (resumed [0 ],9 * CHUNK ) 441 442def test_a_signed_address_that_ran_out_is_asked_for_again (self ): 443def faults (path ,start ,end ,nth ): 444if path .startswith ("/cdn/" )and nth == 1 and start in (4 * CHUNK ,11 * CHUNK ): 445return ("status" ,403 ) 446return None 447 448with small_pieces (),Server (redirect = True ,faults = faults )as srv ,tempfile .TemporaryDirectory ()as d : 449code ,out = run (srv ,d ) 450self .assertIsNone (code ,out ) 451self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 452self .assertGreater (srv .redirects ,2 )# HEAD + first probe + a new address after the 403 453 454def test_a_pinned_hash_mismatch_keeps_the_file_as_bad_and_stops (self ): 455wrong = bytes (reversed (DATA )) 456with small_pieces (),Server ()as srv ,tempfile .TemporaryDirectory ()as d : 457code ,out = run (srv ,d ,pin = pin_of (wrong )) 458self .assertEqual (code ,1 ) 459self .assertEqual (files (d ), [NAME + ".bad" ])# no file, no .done, no .part, no piece list; the bytes are kept 460self .assertEqual ((Path (d )/ (NAME + ".bad" )).read_bytes (),DATA ) 461 462def test_a_pinned_hash_mismatch_with_the_same_size (self ): 463other = bytes ((b ^ 0x55 )for b in DATA ) 464with small_pieces (),Server (data = other )as srv ,tempfile .TemporaryDirectory ()as d : 465code ,out = run (srv ,d ) 466self .assertEqual (code ,1 ) 467self .assertIn ("does not match the pinned SHA-256" ,out ) 468self .assertIn (NAME + ".bad" ,out ) 469self .assertIn ("the server sends exactly the bytes you have" ,out )# the repair compared every block: the server's file is this one 470self .assertEqual (files (d ), [NAME + ".bad" ]) 471 472def test_a_kept_bad_file_is_taken_back_when_it_matches_the_pin_now (self ): 473"""A false mismatch (a bad read, a pin that was wrong and is fixed) costs one hash, not the download: the .bad file is the file again.""" 474wrong = bytes (reversed (DATA )) 475with small_pieces (),Server ()as srv ,tempfile .TemporaryDirectory ()as d : 476code ,_ = run (srv ,d ,pin = pin_of (wrong )) 477self .assertEqual (code ,1 ) 478srv .gets .clear () 479code ,out = run (srv ,d )# the right pin now 480self .assertIsNone (code ,out ) 481self .assertEqual (srv .gets , [],"nothing was asked of the server" ) 482self .assertEqual (files (d ), [NAME ,NAME + ".done" ]) 483self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 484 485def test_a_kept_bad_file_is_removed_by_a_good_download (self ): 486other = bytes ((b ^ 0x55 )for b in DATA ) 487with small_pieces (),Server ()as srv ,tempfile .TemporaryDirectory ()as d : 488 (Path (d )/ (NAME + ".bad" )).write_bytes (other )# kept by an earlier run; not the pinned bytes 489code ,out = run (srv ,d ) 490self .assertIsNone (code ,out ) 491self .assertEqual (files (d ), [NAME ,NAME + ".done" ]) 492self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 493 494def test_a_kept_bad_file_is_removed_when_there_is_no_room_for_the_new_copy (self ): 495other = bytes ((b ^ 0x55 )for b in DATA ) 496usage = type ("U" , (), {"free" :1000 ,"total" :10 ** 6 ,"used" :0 })() 497seen = [] 498 499def faults (path ,start ,end ,nth ): 500seen .append (files (self .d )) 501return None 502 503with small_pieces (),Server (faults = faults )as srv ,tempfile .TemporaryDirectory ()as d ,mock .patch .object (setup .shutil ,"disk_usage" ,lambda p :usage ): 504self .d = d 505 (Path (d )/ (NAME + ".bad" )).write_bytes (other ) 506code ,out = run (srv ,d ) 507self .assertIsNone (code ,out ) 508self .assertTrue (seen and NAME + ".bad" not in seen [0 ],seen [:1 ])# gone before the first piece came down 509self .assertEqual (files (d ), [NAME ,NAME + ".done" ]) 510 511def test_a_kept_bad_file_stays_while_there_is_room (self ): 512other = bytes ((b ^ 0x55 )for b in DATA ) 513seen = [] 514 515def faults (path ,start ,end ,nth ): 516seen .append (files (self .d )) 517return None 518 519with small_pieces (),Server (faults = faults )as srv ,tempfile .TemporaryDirectory ()as d : 520self .d = d 521 (Path (d )/ (NAME + ".bad" )).write_bytes (other ) 522code ,out = run (srv ,d ) 523self .assertIsNone (code ,out ) 524self .assertTrue (seen and NAME + ".bad" in seen [0 ],"kept until the new copy is checked" ) 525self .assertNotIn (NAME + ".bad" ,files (d )) 526 527def test_a_full_disk_stops_with_a_message (self ): 528with small_pieces (),Server ()as srv ,tempfile .TemporaryDirectory ()as d : 529real = setup ._piece_worker 530 531def worker (src ,st ,todo ,part ): 532st .fatal = setup ._DiskError ("No space left on device" ) 533st .stop .set () 534 535with mock .patch .object (setup ,"_piece_worker" ,worker ): 536code ,out = run (srv ,d ) 537self .assertEqual (code ,1 ) 538self .assertIn ("cannot write" ,out ) 539 540def test_the_file_is_not_preallocated (self ): 541"""The app counts a .part's size as the bytes done, so it must not jump to the full size at the start.""" 542seen = [] 543 544def faults (path ,start ,end ,nth ): 545if start == 30 * CHUNK : 546p = Path (self .d )/ (NAME + ".part" ) 547seen .append (p .stat ().st_size if p .exists ()else None ) 548return None 549 550with small_pieces (DL_CONNECTIONS = 2 ),Server (faults = faults ,delay = 0.01 )as srv ,tempfile .TemporaryDirectory ()as d : 551self .d = d 552code ,out = run (srv ,d ) 553self .assertIsNone (code ,out ) 554# a preallocated file would already be the full size (len(DATA)) here; what the other connection has written ahead of piece 30 is 555# thread timing (Windows put it at 34 and 39 pieces), so the check is only that the file has not been made full size 556self .assertTrue (seen and seen [0 ]is not None and seen [0 ]< len (DATA ),seen ) 557 558 559class Progress (unittest .TestCase ): 560def test_the_progress_line_is_the_one_the_app_reads (self ): 561with small_pieces (),Server ()as srv ,tempfile .TemporaryDirectory ()as d : 562code ,out = run (srv ,d ) 563self .assertIsNone (code ,out ) 564lines = [x for x in out .replace ("\r" ,"\n" ).split ("\n" )if x .strip ()] 565bar = [x for x in lines if "GB (" in x ] 566self .assertTrue (bar ) 567for x in bar : 568self .assertRegex (x ,r"^ the model: +[\d.]+ / [\d.]+ GB \(\d+%\) +$" ) 569parsed = strata_mcp .install_progress (bar )["download" ] 570self .assertEqual (parsed ["file" ],"the model" ) 571self .assertEqual (parsed ["percent" ],100 ) 572self .assertEqual (parsed ["total_gb" ],round (len (DATA )/ 1e9 ,2 )) 573 574def test_the_format_matches_the_one_stream_path (self ): 575with small_pieces (),Server ()as srv ,tempfile .TemporaryDirectory ()as d1 ,tempfile .TemporaryDirectory ()as d2 : 576_ ,par = run (srv ,d1 ) 577with mock .patch .dict (os .environ , {"STRATA_DL_CONNECTIONS" :"1" }): 578_ ,one = run (srv ,d2 ) 579def shape (out ): 580return {re .sub (r"[\d.]+" ,"N" ,x )for x in out .replace ("\r" ,"\n" ).split ("\n" )if "GB (" in x } 581self .assertEqual (shape (par ),shape (one )) 582 583 584class SignedAddress (unittest .TestCase ): 585def test_expiry_of_a_cdn_address (self ): 586now = time .time () 587self .assertAlmostEqual (setup ._url_ttl (f"https://cdn.example/f?Expires= { int ( now ) + 600 } &Signature=x" ),600 ,delta = 3 ) 588self .assertIsNone (setup ._url_ttl ("https://cdn.example/f" )) 589self .assertIsNone (setup ._url_ttl (f"https://cdn.example/f?Expires= { int ( now ) - 5 } " ))# already out, or a wrong clock 590self .assertIsNone (setup ._url_ttl ("https://cdn.example/f?Expires=soon" )) 591stamp = time .strftime ("%Y%m%dT%H%M%SZ" ,time .gmtime (now )) 592self .assertAlmostEqual (setup ._url_ttl (f"https://cdn.example/f?X-Amz-Date= { stamp } &X-Amz-Expires=900" ),900 ,delta = 3 ) 593 594 595if __name__ == "__main__" : 596unittest .main () 597 598 599class Runs (unittest .TestCase ): 600"""One request asks for several neighbouring pieces (DL_RUN): fewer connections to open, the same piece list.""" 601 602def test_a_request_covers_several_pieces (self ): 603with small_pieces (DL_RUN = 4 ),Server ()as srv ,tempfile .TemporaryDirectory ()as d : 604code ,out = run (srv ,d ) 605self .assertIsNone (code ,out ) 606self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 607self .assertEqual (files (d ), [NAME ,NAME + ".done" ]) 608spans = [(s ,e )for s ,e in srv .gets if (s ,e )!= (0 ,0 )] 609self .assertLess (len (spans ),41 )# fewer requests than pieces 610self .assertTrue (any (e - s + 1 > CHUNK for s ,e in spans ),spans ) 611self .assertTrue (all (e - s + 1 <= 4 * CHUNK for s ,e in spans ),spans ) 612covered = sorted (i for s ,e in spans for i in range (s // CHUNK ,e // CHUNK + 1 )) 613self .assertEqual (covered ,list (range (41 )))# every piece once, none twice 614 615def test_the_last_pieces_are_asked_for_one_by_one (self ): 616st = setup ._Pieces (CHUNK * 100 ,set (),conns = 4 ) 617todo = list (range (100 )) 618self .assertEqual (setup ._take_run (st ,todo ), [0 ,1 ,2 ,3 ]) 619with mock .patch .object (setup ,"DL_RUN" ,4 ): 620self .assertEqual (setup ._take_run (st ,list (range (60 ,100 ))), [60 ,61 ,62 ,63 ]) 621self .assertEqual (setup ._take_run (st ,list (range (93 ,100 ))), [93 ])# fewer than two rounds left 622self .assertEqual (setup ._take_run (st , [5 ,9 ,10 ]), [5 ])# only neighbours go together 623 624def test_a_broken_run_continues_from_the_byte_it_reached (self ): 625cuts = [] 626 627def faults (path ,start ,end ,nth ): 628if end - start + 1 > 2 * CHUNK and not cuts : 629cuts .append (start ) 630return ("cut" ,int (2.5 * CHUNK ))# drops inside the third piece of the run 631return None 632 633with small_pieces (DL_RUN = 4 ,DL_CONNECTIONS = 2 ),Server (faults = faults )as srv ,tempfile .TemporaryDirectory ()as d : 634code ,out = run (srv ,d ) 635self .assertIsNone (code ,out ) 636self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 637self .assertEqual (len (cuts ),1 ) 638first = cuts [0 ] 639again = [s for s ,e in srv .gets if first < s < first + 4 * CHUNK ] 640self .assertEqual (len (again ),1 )# one more request: for the rest 641self .assertGreaterEqual (again [0 ],first + 2 * CHUNK )# the two whole pieces are not fetched again 642 643def test_a_connection_that_keeps_moving_is_not_given_up_on (self ): 644"""Seven breaks in a row (more than DL_CHUNK_TRIES) that each carried bytes forward do not end the request.""" 645count = [0 ] 646 647def faults (path ,start ,end ,nth ): 648if start < 4 * CHUNK and end - start + 1 > CHUNK // 2 and count [0 ]< 7 : 649count [0 ]+= 1 650return ("cut" ,CHUNK // 3 ) 651return None 652 653with small_pieces (DL_RUN = 4 ,DL_CONNECTIONS = 2 ,DL_ROUNDS = 1 ),Server (faults = faults )as srv ,tempfile .TemporaryDirectory ()as d : 654code ,out = run (srv ,d ) 655self .assertIsNone (code ,out ) 656self .assertEqual ((Path (d )/ NAME ).read_bytes (),DATA ) 657self .assertEqual (count [0 ],7 ) 658 659def test_a_request_without_progress_still_gives_up (self ): 660def faults (path ,start ,end ,nth ): 661if start >= 4 * CHUNK : 662return ("status" ,500 ) 663return None 664 665with small_pieces (DL_RUN = 4 ,DL_ROUNDS = 1 ,DL_CHUNK_TRIES = 2 ),Server (faults = faults )as srv ,tempfile .TemporaryDirectory ()as d : 666code ,out = run (srv ,d ) 667self .assertEqual (code ,1 ) 668self .assertIn ("could not finish downloading" ,out ) 669 670def test_the_default_is_many_connections_and_runs (self ): 671self .assertGreaterEqual (setup .DL_CONNECTIONS ,8 ) 672self .assertGreaterEqual (setup .DL_RUN ,2 ) 673self .assertEqual (setup .DL_CHUNK ,32 << 20 )# the piece list on disk names this size: resumes need it 674 675 676class WholeMarkNeedsThePin (unittest .TestCase ): 677"""#4088: a full-length shard with no finish mark and a pinned SHA-256 must not be marked "whole" (the approach of PR #4318, written here). 678 679A run killed between the rename of a finished .part and the end of its hash leaves exactly that state; the mark the next run wrote made done() 680true, download() skipped the file, the pinned hash was never checked and a shard damaged by that crash stayed in place.""" 681 682def setUp (self ): 683self .tmp = tempfile .TemporaryDirectory () 684self .addCleanup (self .tmp .cleanup ) 685self .folder = Path (self .tmp .name ) 686self .repo = next (r for r ,files in setup .REPO_PINS .items ()if files ) 687self .name = next (iter (setup .REPO_PINS [self .repo ])) 688self .hf = f"https://huggingface.co/ { self . repo } /resolve/main/" 689patch = mock .patch .object (setup ,"whole_shard" ,return_value = True )# the test is about the mark, not the GGUF header 690patch .start () 691self .addCleanup (patch .stop ) 692 693def test_a_pinned_shard_is_left_for_the_download_check (self ): 694shard = self .folder / self .name 695shard .write_bytes (b"x" ) 696self .assertIsNotNone (setup .file_pin (self .hf + self .name ),"the file needs a pin for this test to mean anything" ) 697setup .mark_whole_unless_pinned ([shard ],self .hf ,own = False ) 698self .assertFalse (setup .done (shard ),"no finish mark: download() hashes it and repairs it" ) 699self .assertFalse (shard .with_name (shard .name + ".done" ).exists ()) 700 701def test_a_file_without_a_pin_keeps_the_whole_mark (self ): 702shard = self .folder / "hand-copied.gguf" 703shard .write_bytes (b"x" ) 704self .assertIsNone (setup .file_pin (self .hf + shard .name )) 705setup .mark_whole_unless_pinned ([shard ],self .hf ,own = False ) 706self .assertTrue (setup .done (shard )) 707self .assertIn ("whole" ,shard .with_name (shard .name + ".done" ).read_text (encoding = "utf-8" )) 708 709def test_the_persons_own_file_keeps_the_mark (self ): 710shard = self .folder / self .name 711shard .write_bytes (b"x" ) 712setup .mark_whole_unless_pinned ([shard ],self .hf ,own = True )# --gguf-dir: not a download 713self .assertTrue (setup .done (shard )) 714 715def test_a_family_with_no_hf_folder_keeps_the_mark_and_does_not_raise (self ): 716"""The NVFP4 families have no "hf" key (they download a file list): the helper must not need one (it raised KeyError in main()).""" 717shard = self .folder / self .name 718shard .write_bytes (b"x" ) 719setup .mark_whole_unless_pinned ([shard ],None ,own = False ) 720self .assertTrue (setup .done (shard )) 721setup .mark_whole_unless_pinned ([],None ,own = False ) 722 723def test_a_marked_or_missing_file_is_not_touched (self ): 724shard = self .folder / "marked.gguf" 725shard .write_bytes (b"x" ) 726setup .mark (shard ,"sha256 abc" ) 727setup .mark_whole_unless_pinned ([shard ,self .folder / "absent.gguf" ],self .hf ,own = False ) 728self .assertEqual (shard .with_name (shard .name + ".done" ).read_text (encoding = "utf-8" ).strip (),"sha256 abc" ) 729 730def test_the_damaged_pinned_file_is_then_hashed_by_the_download (self ): 731"""The whole path: full length, no mark, wrong bytes -> not marked -> download() takes its 'stopped before the check' branch and hashes it.""" 732shard = self .folder / self .name 733shard .write_bytes (b"x" * 8 ) 734pin = (8 ,"ab" * 32 )# a pin of this file's size, so the "full length" branch is the one taken 735calls = [] 736with mock .patch .dict (setup .REPO_PINS [self .repo ], {self .name :pin }),mock .patch .object (setup ,"range_total" ,return_value = 8 ),mock .patch .object (setup ,"_urlopen" ,lambda * a ,** k :type ("R" , (), {"headers" : {"Content-Length" :"8" },"__enter__" :lambda s :s ,"__exit__" :lambda s ,* e :False ,"close" :lambda s :None })()),mock .patch .object (setup ,"verify_sha256" ,lambda * a ,** k :calls .append (a )): 737setup .mark_whole_unless_pinned ([shard ],self .hf ,own = False ) 738self .assertFalse (setup .done (shard )) 739setup .download (self .hf + self .name ,shard ) 740self .assertTrue (calls and calls [0 ][1 :3 ]== pin ,"the pinned hash was checked" )