okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5b1728358
main
1"""0.2.2: a model download never leaves wrong bytes behind, and a file with a wrong SHA-256 is repaired, not thrown away. 2 3A user's 39.8 GB shard arrived with the wrong SHA-256 on 0.2.1 (16 connections, several pieces per request). These tests run 4setup.download() against a local HTTP server that misbehaves in each way a server, a CDN or a disk can: a 200 for a ranged 5request, a 206 for another range or another total, a body that ends early, another version of the file part-way, a changed 6ETag, a .part written from another mirror, no piece list, a full disk, a raw write that takes fewer bytes than given, and 7bytes that are wrong in the first download (the repair reads the file again and writes only the pieces that differ). 8Pieces are 64 KiB here instead of 32 MiB, so a few MiB stand for the 40 GB.""" 9 10from __future__import annotations 11 12import contextlib 13import hashlib 14import http .server 15import io 16import json 17import random 18import re 19import shutil 20import tempfile 21import threading 22import unittest 23from pathlib import Path 24from unittest import mock 25 26import setup 27from strata_control import transfer 28 29PIECE = 64 << 10 30SIZE = 40 * PIECE + 12345 # 41 pieces, the last one short 31DATA = random .Random (7 ).randbytes (SIZE ) 32SHA = hashlib .sha256 (DATA ).hexdigest () 33 34 35class Behavior : 36"""What the server does with request number n (1 = the first). `plan` returns overrides for that answer.""" 37 38def __init__ (self ,plan = None ,data = DATA ,etag = '"v1"' ): 39self .plan = plan or (lambda n ,start ,end : {}) 40self .data = data 41self .etag = etag 42self .lock = threading .Lock () 43self .count = 0 44self .served = []# (start, end) of every ranged answer 45self .once = set () 46 47def next (self ): 48with self .lock : 49self .count += 1 50return self .count 51 52 53class Handler (http .server .BaseHTTPRequestHandler ): 54protocol_version = "HTTP/1.0" # one request per connection: ending a body early is a reset 55 56def log_message (self ,* a ): 57pass 58 59def do_HEAD (self ): 60beh = self .server .beh 61self .send_response (200 ) 62self .send_header ("Content-Length" ,str (len (beh .data ))) 63self .send_header ("Accept-Ranges" ,"bytes" ) 64self .end_headers () 65 66def do_GET (self ): 67beh = self .server .beh 68n = beh .next () 69total = len (beh .data ) 70m = re .match (r"bytes=(\d+)-(\d*)" ,self .headers .get ("Range" )or "" ) 71start = int (m .group (1 ))if m else 0 72end = min (int (m .group (2 )),total - 1 )if m and m .group (2 )else total - 1 73if start >= total : 74self .send_response (416 ) 75self .end_headers () 76return 77o = beh .plan (n ,start ,end )or {} 78if o .get ("status" )== 404 or o .get ("status" )== 503 : 79self .send_response (o ["status" ]) 80self .send_header ("Content-Length" ,"0" ) 81self .end_headers () 82return 83status = o .get ("status" ,206 if m else 200 ) 84b0 ,b1 = o .get ("body" , (start ,end )) 85body = bytearray (beh .data if status == 200 else beh .data [b0 :b1 + 1 ]) 86for off in o .get ("corrupt" , ()): 87lo = 0 if status == 200 else b0 88if lo <= off < lo + len (body ): 89body [off - lo ]^= 0xFF 90self .send_response (status ) 91self .send_header ("Content-Length" ,str (o .get ("cl" ,len (body )))) 92if status == 206 : 93self .send_header ("Content-Range" ,o .get ("cr" ,f"bytes { start } - { end } / { total } " )) 94self .send_header ("ETag" ,o .get ("etag" ,beh .etag )) 95self .end_headers () 96with beh .lock : 97beh .served .append ((start ,end )) 98cut = o .get ("cut" ) 99try : 100self .wfile .write (bytes (body [:cut ]if cut is not None else body )) 101except OSError : 102pass 103 104 105class Server (http .server .ThreadingHTTPServer ): 106daemon_threads = True 107 108def handle_error (self ,request ,client_address ): 109pass 110 111 112class DownloadCase (unittest .TestCase ): 113def setUp (self ): 114self .tmp = Path (tempfile .mkdtemp (prefix = "dlint" )) 115self .addCleanup (shutil .rmtree ,self .tmp ,True ) 116patches = [mock .patch .object (setup ,"DL_CHUNK" ,PIECE ),mock .patch .object (setup ,"DL_MIN_PARALLEL" ,PIECE * 4 ), 117mock .patch .object (setup ,"DL_BACKOFF" ,0.0 ),mock .patch .object (setup ,"DL_SAVE_EVERY" ,0.0 ), 118mock .patch .object (setup ,"DL_ROUNDS" ,3 ),mock .patch .object (setup .time ,"sleep" ,lambda s :None ), 119mock .patch .object (setup ,"file_pin" ,lambda url : (SIZE ,SHA )), 120mock .patch .dict ("os.environ" , {"STRATA_DL_CONNECTIONS" :"4" ,"STRATA_SOURCE" :"huggingface" })] 121for p in patches : 122p .start () 123self .addCleanup (p .stop ) 124self .dst = self .tmp / "model.gguf" 125self .part = self .tmp / "model.gguf.part" 126 127def serve (self ,beh ): 128srv = Server (("127.0.0.1" ,0 ),Handler ) 129srv .beh = beh 130threading .Thread (target = srv .serve_forever ,daemon = True ).start () 131self .addCleanup (srv .server_close ) 132self .addCleanup (srv .shutdown ) 133self .beh = beh 134return f"http://127.0.0.1: { srv . server_address [ 1 ] } /m/model.gguf" 135 136def run_download (self ,url ,expect_exit = False ): 137buf = io .StringIO () 138with contextlib .redirect_stdout (buf ): 139if expect_exit : 140with self .assertRaises (SystemExit ): 141setup .download (url ,self .dst ) 142else : 143setup .download (url ,self .dst ) 144self .out = buf .getvalue () 145return self .out 146 147def assertGood (self ): 148self .assertTrue (self .dst .is_file (),self .out ) 149self .assertEqual (hashlib .sha256 (self .dst .read_bytes ()).hexdigest (),SHA ) 150self .assertFalse (self .part .exists ()) 151self .assertFalse (self .tmp .joinpath ("model.gguf.part.chunks" ).exists ()) 152 153 154class Misbehaving (DownloadCase ): 155def test_clean_download (self ): 156self .run_download (self .serve (Behavior ())) 157self .assertGood () 158 159def test_ranged_requests_answered_with_200_use_one_stream (self ): 160self .run_download (self .serve (Behavior (lambda n ,s ,e : {"status" :200 }))) 161self .assertGood () 162 163def test_ranges_stop_being_honoured_part_way (self ): 164# the probe and the first pieces are right; later requests get the whole file with a 200 165self .run_download (self .serve (Behavior (lambda n ,s ,e : {"status" :200 }if n > 6 else {}))) 166self .assertGood () 167 168def test_206_for_another_range_is_not_written (self ): 169# Content-Range names a range that starts later than the one asked for, from the 5th request on 170self .run_download (self .serve (Behavior (lambda n ,s ,e : {"cr" :f"bytes { s + 7 } - { e } / { SIZE } " ,"body" : (s + 7 ,e )} 171if n > 4 and s > 0 else {}))) 172self .assertGood () 173 174def test_206_with_another_total_is_not_written (self ): 175self .run_download (self .serve (Behavior (lambda n ,s ,e : {"cr" :f"bytes { s } - { e } / { SIZE + 1 } " }if n > 4 else {}))) 176self .assertGood () 177 178def test_206_with_a_longer_body_than_asked (self ): 179# Content-Length does not fit the range: tried again, then right 180self .run_download (self .serve (Behavior (lambda n ,s ,e : {"cl" :e - s + 5 }if n in (4 ,5 ,9 )else {}))) 181self .assertGood () 182 183def test_connection_reset_in_the_middle_of_pieces (self ): 184# every 3rd answer ends after a random part of its body; the piece it broke in is written again from its start 185rnd = random .Random (3 ) 186self .run_download (self .serve (Behavior (lambda n ,s ,e : {"cut" :rnd .randrange (1 ,max (2 ,e - s ))}if n % 3 == 0 else {}))) 187self .assertGood () 188 189def test_an_answer_cut_after_a_whole_number_of_blocks_still_ends_in_the_right_bytes (self ): 190self .run_download (self .serve (Behavior (lambda n ,s ,e : {"cut" :PIECE + 17 }if n in (3 ,4 ,5 ,6 )else {}))) 191self .assertGood () 192 193def test_one_answer_from_another_version_is_asked_again (self ): 194self .run_download (self .serve (Behavior (lambda n ,s ,e : {"etag" :'"v2"' }if n in (4 ,7 )else {}))) 195self .assertGood () 196 197def test_another_version_for_good_stops_and_leaves_no_file (self ): 198out = self .run_download (self .serve (Behavior (lambda n ,s ,e : {"etag" :'"v2"' }if n > 3 else {})),expect_exit = True ) 199self .assertFalse (self .dst .exists ()) 200 201def test_the_file_changing_between_resolves_is_noticed (self ): 202src = setup ._Source ("http://x/y" ,SIZE ) 203src .etag = "aaa" 204 205class R : 206status = 206 207headers = {"Content-Range" :f"bytes 0-0/ { SIZE } " ,"ETag" :'"bbb"' } 208 209def __enter__ (self ): 210return self 211 212def __exit__ (self ,* a ): 213return False 214 215def read (self ,n ): 216return b"x" 217 218def geturl (self ): 219return "http://x/y" 220 221with mock .patch .object (setup ,"_urlopen" ,lambda * a ,** k :R ()): 222with self .assertRaises (setup ._Changed ): 223src .resolve () 224 225def test_server_error_part_way_keeps_pieces_and_a_second_run_finishes (self ): 226url = self .serve (Behavior (lambda n ,s ,e : {"status" :503 }if n > 12 else {})) 227self .run_download (url ,expect_exit = True ) 228self .assertTrue (self .part .exists ()) 229self .assertTrue (self .tmp .joinpath ("model.gguf.part.chunks" ).exists ()) 230first_run = len (self .beh .served ) 231self .beh .plan = lambda n ,s ,e : {}# the same address, now answering 232self .beh .served .clear () 233self .run_download (url ) 234self .assertGood () 235fetched = sum (e - s + 1 for s ,e in self .beh .served if e > s )# without the one-byte probes 236self .assertLess (fetched ,SIZE ,"the second run took the whole file again instead of resuming" ) 237self .assertGreater (first_run ,1 ) 238 239def test_two_interrupted_runs_then_a_good_one (self ): 240url = self .serve (Behavior ()) 241for limit in (6 ,6 ): 242self .beh .count = 0 243self .beh .plan = lambda n ,s ,e ,limit = limit : {"status" :503 }if n > limit else {} 244self .run_download (url ,expect_exit = True ) 245self .beh .plan = lambda n ,s ,e : {} 246self .run_download (url ) 247self .assertGood () 248 249def test_a_part_written_from_another_mirror_is_dropped (self ): 250url = self .serve (Behavior ()) 251self .part .write_bytes (b"\xaa" * (PIECE * 10 )) 252self .tmp .joinpath ("model.gguf.part.chunks" ).write_text ( 253json .dumps ({"v" :1 ,"total" :SIZE ,"chunk" :PIECE ,"done" : [[0 ,10 ]]}),encoding = "utf-8" ) 254self .tmp .joinpath ("model.gguf.part.src" ).write_text ( 255json .dumps ({"url" :"https://www.modelscope.cn/models/x/resolve/master/model.gguf" ,"etag" :None }),encoding = "utf-8" ) 256self .run_download (url ) 257self .assertGood ()# the 0xaa pieces were not trusted 258 259def test_a_part_of_another_version_is_dropped (self ): 260url = self .serve (Behavior ()) 261self .part .write_bytes (b"\xaa" * (PIECE * 10 )) 262self .tmp .joinpath ("model.gguf.part.chunks" ).write_text ( 263json .dumps ({"v" :1 ,"total" :SIZE ,"chunk" :PIECE ,"done" : [[0 ,10 ]]}),encoding = "utf-8" ) 264self .tmp .joinpath ("model.gguf.part.src" ).write_text (json .dumps ({"url" :url ,"etag" :'"old"' }),encoding = "utf-8" ) 265self .run_download (url ) 266self .assertGood () 267 268def test_without_a_writable_piece_list_the_file_is_not_written_in_parts (self ): 269url = self .serve (Behavior ()) 270with mock .patch .object (setup ,"_save_pieces" ,return_value = False ): 271self .run_download (url ) 272self .assertGood () 273 274def test_a_stale_piece_list_never_names_bytes_the_part_lacks (self ): 275self .part .write_bytes (b"\x00" * (PIECE * 3 )) 276self .tmp .joinpath ("model.gguf.part.chunks" ).write_text ( 277json .dumps ({"v" :1 ,"total" :SIZE ,"chunk" :PIECE ,"done" : [[0 ,30 ]]}),encoding = "utf-8" ) 278self .assertEqual (setup ._load_pieces (self .part ,SIZE ), {0 ,1 ,2 }) 279 280def test_full_disk_stops_with_a_plain_message_and_keeps_the_part (self ): 281url = self .serve (Behavior ()) 282 283def full (f ,pos ,data ): 284raise OSError (28 ,"No space left on device" ) 285 286with mock .patch .object (setup ,"_write_all" ,full ): 287out = self .run_download (url ,expect_exit = True ) 288self .assertIn ("cannot write" ,out ) 289self .assertIn ("free some disk space" ,out ) 290self .assertFalse (self .dst .exists ()) 291 292def test_a_raw_write_that_takes_fewer_bytes_is_finished (self ): 293class Slow : 294def __init__ (self ): 295self .buf = bytearray (100 ) 296self .pos = 0 297 298def seek (self ,p ): 299self .pos = p 300 301def write (self ,v ): 302n = min (7 ,len (v )) 303self .buf [self .pos :self .pos + n ]= bytes (v [:n ]) 304self .pos += n 305return n 306 307f = Slow () 308setup ._write_all (f ,10 ,bytes (range (60 ))) 309self .assertEqual (bytes (f .buf [10 :70 ]),bytes (range (60 ))) 310 311def test_a_raw_write_that_takes_nothing_is_an_error (self ): 312class Zero : 313def seek (self ,p ): 314pass 315 316def write (self ,v ): 317return 0 318 319with self .assertRaises (OSError ): 320setup ._write_all (Zero (),0 ,b"abc" ) 321 322def test_single_stream_resume_ignores_a_206_from_the_wrong_offset (self ): 323url = self .serve (Behavior (lambda n ,s ,e : {"cr" :f"bytes { s + 5 } - { e } / { SIZE } " ,"body" : (s + 5 ,e )}if s > 0 else {})) 324self .part .write_bytes (DATA [:PIECE * 3 ]) 325with mock .patch .dict ("os.environ" , {"STRATA_DL_CONNECTIONS" :"1" }): 326self .run_download (url ) 327self .assertGood () 328 329def test_single_stream_resume_ignores_a_200 (self ): 330url = self .serve (Behavior (lambda n ,s ,e : {"status" :200 })) 331self .part .write_bytes (DATA [:PIECE * 3 ]) 332with mock .patch .dict ("os.environ" , {"STRATA_DL_CONNECTIONS" :"1" }): 333self .run_download (url ) 334self .assertGood () 335 336def test_finished_file_without_a_mark_is_checked_not_marked (self ): 337self .dst .write_bytes (DATA [:- 1 ]+ b"\x00" ) 338url = self .serve (Behavior ()) 339self .run_download (url ) 340self .assertIn ("Some parts of model.gguf were damaged" ,self .out ) 341self .assertGood () 342self .assertTrue (self .tmp .joinpath ("model.gguf.done" ).exists ()) 343 344 345class Repair (DownloadCase ): 346def test_wrong_bytes_in_two_pieces_are_found_and_only_those_rewritten (self ): 347bad = [5 * PIECE + 100 ,30 * PIECE + 7 ] 348seen = set () 349 350def plan (n ,s ,e ): 351hit = [o for o in bad if s <= o <= e and o not in seen ] 352seen .update (hit ) 353return {"corrupt" :hit }if hit else {} 354 355out = self .run_download (self .serve (Behavior (plan ))) 356self .assertGood () 357self .assertIn ("Some parts of model.gguf were damaged; downloading only those parts again" ,out ) 358self .assertIn ("2 of 41 parts were different" ,out ) 359self .assertTrue (self .tmp .joinpath ("model.gguf.done" ).exists ()) 360 361def test_one_flipped_byte_in_the_last_short_piece (self ): 362bad = [SIZE - 3 ] 363seen = set () 364 365def plan (n ,s ,e ): 366hit = [o for o in bad if s <= o <= e and o not in seen ] 367seen .update (hit ) 368return {"corrupt" :hit }if hit else {} 369 370out = self .run_download (self .serve (Behavior (plan ))) 371self .assertGood () 372self .assertIn ("1 of 41 parts were different" ,out ) 373 374def test_a_repair_that_loses_the_connection_part_way_still_ends_right (self ): 375bad = [3 * PIECE + 1 ] 376seen = set () 377 378def plan (n ,s ,e ): 379hit = [o for o in bad if s <= o <= e and o not in seen ] 380seen .update (hit ) 381o = {"corrupt" :hit }if hit else {} 382if seen and n % 4 == 0 : 383o ["cut" ]= 5000 384return o 385 386self .run_download (self .serve (Behavior (plan ))) 387self .assertGood () 388 389def test_a_server_that_keeps_serving_the_wrong_file_ends_with_the_file_kept_as_bad (self ): 390wrong = bytearray (DATA ) 391wrong [1000 ]^= 0xFF 392url = self .serve (Behavior (data = bytes (wrong ))) 393out = self .run_download (url ,expect_exit = True ) 394self .assertIn ("does not match the pinned SHA-256" ,out ) 395self .assertFalse (self .dst .exists ()) 396self .assertTrue (self .dst .with_name (self .dst .name + ".bad" ).is_file ())# kept, not deleted (f-0216-dlsha) 397self .assertFalse (self .tmp .joinpath ("model.gguf.done" ).exists ()) 398 399def test_the_repair_is_off_for_a_file_the_person_owns (self ): 400self .dst .write_bytes (b"x" * SIZE ) 401called = [] 402with contextlib .redirect_stdout (io .StringIO ()): 403with self .assertRaises (SystemExit ): 404setup .verify_sha256 (self .dst ,SIZE ,SHA ,own = True ,repair = lambda :called .append (1 )) 405self .assertEqual (called , []) 406self .assertTrue (self .dst .exists ()) 407 408 409class UpdateTransfer (unittest .TestCase ): 410"""strata_control/transfer.py (update archives): a resumed answer is appended only when it starts at the byte asked for.""" 411 412def setUp (self ): 413self .tmp = Path (tempfile .mkdtemp (prefix = "dlint" )) 414self .addCleanup (shutil .rmtree ,self .tmp ,True ) 415 416def test_resume_check (self ): 417class R : 418def __init__ (self ,status ,cr ): 419self .status = status 420self .headers = {"Content-Range" :cr }if cr else {} 421 422self .assertTrue (transfer ._resumes_at (R (206 ,"bytes 100-999/1000" ),100 ,1000 )) 423self .assertFalse (transfer ._resumes_at (R (206 ,"bytes 0-999/1000" ),100 ,1000 )) 424self .assertFalse (transfer ._resumes_at (R (206 ,"bytes 100-999/2000" ),100 ,1000 )) 425self .assertFalse (transfer ._resumes_at (R (206 ,"" ),100 ,1000 )) 426self .assertFalse (transfer ._resumes_at (R (200 ,"bytes 100-999/1000" ),100 ,1000 )) 427 428def test_a_206_from_the_wrong_offset_restarts_the_file (self ): 429data = DATA [:200000 ] 430beh = Behavior (lambda n ,s ,e : {"cr" :f"bytes { s + 9 } - { e } / { len ( data ) } " ,"body" : (s + 9 ,e )}if s > 0 else {},data = data ) 431srv = Server (("127.0.0.1" ,0 ),Handler ) 432srv .beh = beh 433threading .Thread (target = srv .serve_forever ,daemon = True ).start () 434self .addCleanup (srv .server_close ) 435self .addCleanup (srv .shutdown ) 436part = self .tmp / "a.part" 437part .write_bytes (data [:50000 ]) 438got = transfer .download (f"http://127.0.0.1: { srv . server_address [ 1 ] } /a" ,part ,size = len (data ), 439sha256 = hashlib .sha256 (data ).hexdigest ()) 440self .assertEqual (got .read_bytes (),data ) 441 442 443if __name__ == "__main__" : 444unittest .main ()