okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1f727f4b5
main
1"""Moving the models to another folder (strata models move): same drive, another drive, stop, a failed check, disk full, resume.""" 2from __future__import annotations 3 4import hashlib 5import json 6import os 7import shutil 8import tempfile 9import unittest 10from pathlib import Path 11from unittest import mock 12 13from strata_control import models_move as mm 14 15 16def sha (data :bytes )-> str : 17return hashlib .sha256 (data ).hexdigest () 18 19 20class MoveCase (unittest .TestCase ): 21def setUp (self ): 22self .tmp = tempfile .TemporaryDirectory (prefix = "strata-move-" ) 23self .addCleanup (self .tmp .cleanup ) 24self .base = Path (self .tmp .name ) 25self .old = self .base / "old" 26self .new = self .base / "new" 27self .files = { 28"models/gyro-s/a.gguf" :b"A" * 300_000 , 29"models/gyro-s/b.gguf" :b"B" * 200_000 , 30"packs/gyro-s/dense.bin" :b"D" * 100_000 , 31"models/coder/c.gguf" :b"C" * 150_000 , 32"mtp/rt/experts.bin" :b"M" * 50_000 , 33 } 34for rel ,data in self .files .items (): 35f = self .old / rel 36f .parent .mkdir (parents = True ,exist_ok = True ) 37f .write_bytes (data ) 38# a finished download carries the pinned checksum in its mark 39 (self .old / "models/gyro-s/a.gguf.done" ).write_text (f"done sha256 { sha ( self . files [ 'models/gyro-s/a.gguf' ]) } \n" ) 40 (self .old / "notes.txt" ).write_text ("not a model file" )# Strata moves its own folders only 41self .install = self .base / "install" 42self .install .mkdir () 43self .config = self .install / "strata-gyro-s.json" 44self .config .write_text (json .dumps ({"args" : ["--native" ,str (self .old / "models/gyro-s/a.gguf" ),"--pack" ,str (self .old / "packs/gyro-s" )], 45"mtp" :str (self .old / "mtp/rt" )})) 46self .total = sum (len (v )for v in self .files .values ()) 47 48def tree (self ,root :Path )-> set [str ]: 49return {p .relative_to (root ).as_posix ()for p in root .rglob ("*" )if p .is_file ()and p .name != mm .STATE_FILE } 50 51def copy_mode (self ): 52"""Another drive: the files are copied, whatever this machine's volumes are.""" 53return mock .patch .object (mm ,"same_drive" ,return_value = False ) 54 55def break_after (self ,n ): 56"""A copy that works n times, then fails: a move cut off part way.""" 57real ,calls = mm ._copy_verified , [0 ] 58 59def flaky (* args ,** kw ): 60calls [0 ]+= 1 61if calls [0 ]> n : 62raise mm .MoveError ("io" ,"cut off" ) 63return real (* args ,** kw ) 64return mock .patch .object (mm ,"_copy_verified" ,side_effect = flaky ) 65 66def cut_off (self ,n = 1 ): 67with self .copy_mode (),self .break_after (n ): 68with self .assertRaises (mm .MoveError ): 69self .run_move () 70 71def run_move (self ,** kw ): 72events = [] 73summary = mm .move (self .old ,self .new ,on_progress = events .append ,configs = [self .config ],** kw ) 74return summary ,events 75 76 77class PlanTests (MoveCase ): 78def test_plan_numbers_and_choices (self ): 79with self .copy_mode (): 80p = mm .plan (self .old ,self .new ,free = lambda _p :10 ** 9 ) 81self .assertTrue (p ["ok" ]) 82self .assertGreaterEqual (p ["models_bytes" ],self .total ) 83self .assertGreater (p ["needed_bytes" ],p ["models_bytes" ])# the 5 % margin 84self .assertTrue (p ["choices" ]["move" ]["possible" ]) 85self .assertEqual ({m ["name" ]for m in p ["models" ]}, {"gyro-s" ,"coder" ,"mtp" }) 86 87def test_not_enough_room_switches_move_off (self ): 88with self .copy_mode (): 89p = mm .plan (self .old ,self .new ,free = lambda _p :1000 ) 90self .assertTrue (p ["ok" ]) 91self .assertFalse (p ["choices" ]["move" ]["possible" ]) 92self .assertIn ("free" ,p ["choices" ]["move" ]["reason" ]) 93self .assertTrue (p ["choices" ]["keep" ]["possible" ]and p ["choices" ]["empty" ]["possible" ]) 94 95def test_same_drive_needs_no_room (self ): 96p = mm .plan (self .old ,self .new ,free = lambda _p :0 ) 97self .assertTrue (p ["same_drive" ]) 98self .assertTrue (p ["choices" ]["move" ]["possible" ]) 99 100def test_inside_and_same_are_refused (self ): 101self .assertEqual (mm .plan (self .old ,self .old / "sub" )["issue" ]["code" ],"inside" ) 102self .assertEqual (mm .plan (self .old / "sub" ,self .old )["issue" ]["code" ],"inside" ) 103self .assertEqual (mm .plan (self .old ,self .old )["issue" ]["code" ],"same" ) 104 105def test_a_folder_that_cannot_be_written_is_refused (self ): 106with mock .patch .object (mm ,"_write_test" ,return_value = "EPERM: operation not permitted, mkdir 'x'" ): 107p = mm .plan (self .old ,self .new ) 108self .assertEqual (p ["issue" ]["code" ],"not_writable" ) 109self .assertIn ("EPERM" ,p ["issue" ]["details" ]) 110 111def test_nothing_is_changed_by_a_plan (self ): 112before = self .tree (self .old ) 113mm .plan (self .old ,self .new ) 114self .assertEqual (self .tree (self .old ),before ) 115 116 117class MoveTests (MoveCase ): 118def check_whole (self ): 119self .assertEqual ({k for k in self .tree (self .new )if not k .endswith (".done" )},set (self .files )) 120for rel ,data in self .files .items (): 121self .assertEqual ((self .new / rel ).read_bytes (),data ) 122self .assertEqual (self .tree (self .old ), {"notes.txt" })# only what is not Strata's own is left 123cfg = json .loads (self .config .read_text ()) 124self .assertEqual (Path (cfg ["args" ][1 ]),self .new / "models/gyro-s/a.gguf" ) 125self .assertEqual (Path (cfg ["mtp" ]),self .new / "mtp/rt" ) 126self .assertFalse ((self .new / mm .STATE_FILE ).exists ()) 127 128def test_same_drive_is_a_rename (self ): 129with mock .patch .object (shutil ,"copyfileobj" ,side_effect = AssertionError ("copied" )),mock .patch .object (mm ,"_copy_verified" ,side_effect = AssertionError ("copied" )): 130summary ,_events = self .run_move () 131self .assertTrue (summary ["done" ]and summary ["same_drive" ]) 132self .check_whole () 133 134def test_another_drive_copies_checks_and_removes (self ): 135with self .copy_mode (): 136summary ,events = self .run_move () 137self .assertTrue (summary ["done" ]and not summary ["same_drive" ]) 138self .assertEqual (summary ["files_moved" ],len (self .files )+ 1 )# + the .done mark 139self .check_whole () 140self .assertTrue (events and events [- 1 ]["done" ]<= self .total + 100 ) 141self .assertEqual (events [0 ]["event" ],"progress" ) 142 143def test_stop_keeps_what_moved_and_removes_the_partial_copy (self ): 144calls = {"n" :0 } 145 146def stop (): 147calls ["n" ]+= 1 148return calls ["n" ]> 6 # a few chunks into the second file or so 149with self .copy_mode (): 150summary ,_events = self .run_move (cancelled = stop ) 151self .assertTrue (summary ["stopped" ]and not summary ["done" ]) 152self .assertEqual ([p for p in self .new .rglob ("*.part" )], []) 153# every file is in exactly one place, nothing is lost 154for rel ,data in self .files .items (): 155places = [r for r in (self .old ,self .new )if (r / rel ).exists ()] 156self .assertEqual (len (places ),1 ,rel ) 157self .assertEqual ((places [0 ]/ rel ).read_bytes (),data ) 158self .assertTrue (summary ["remaining" ]) 159# a model that moved whole now points at the new folder; one that did not stays where it is 160cfg = json .loads (self .config .read_text ()) 161for value in (cfg ["args" ][1 ],cfg ["args" ][3 ],cfg ["mtp" ]): 162self .assertTrue (Path (value ).exists (),value ) 163 164def test_stop_before_anything_leaves_the_old_folder_as_it_was (self ): 165with self .copy_mode (): 166summary ,_ = self .run_move (cancelled = lambda :True ) 167self .assertTrue (summary ["stopped" ]) 168self .assertEqual (summary ["files_moved" ],0 ) 169self .assertEqual ({k for k in self .tree (self .old )if not k .endswith (".done" )},set (self .files )| {"notes.txt" }) 170self .assertFalse ((self .new / mm .STATE_FILE ).exists ()) 171 172def test_a_copy_that_does_not_match_is_never_trusted (self ): 173real = mm ._sha256_of 174calls = {"n" :0 } 175 176def lies (path ,stop ,tick = None ): 177calls ["n" ]+= 1 178return "0" * 64 if str (path ).endswith (".part" )and calls ["n" ]== 1 else real (path ,stop ,tick ) 179with self .copy_mode (),mock .patch .object (mm ,"_sha256_of" ,side_effect = lies ): 180with self .assertRaises (mm .MoveError )as caught : 181self .run_move () 182self .assertEqual (caught .exception .code ,"verify" ) 183self .assertEqual (list (self .new .rglob ("*.part" )), []) 184self .assertEqual ({k for k in self .tree (self .old )if not k .endswith (".done" )},set (self .files )| {"notes.txt" })# the original is untouched 185 186def test_a_file_that_differs_from_its_pinned_checksum_is_not_moved (self ): 187 (self .old / "models/gyro-s/a.gguf.done" ).write_text ("done sha256 " + "1" * 64 ) 188with self .copy_mode (): 189with self .assertRaises (mm .MoveError )as caught : 190self .run_move () 191self .assertEqual (caught .exception .code ,"verify" ) 192self .assertTrue ((self .old / "models/gyro-s/a.gguf" ).exists ()) 193self .assertFalse ((self .new / "models/gyro-s/a.gguf" ).exists ()) 194 195def test_disk_full_stops_at_once_and_loses_nothing (self ): 196real = mm ._copy_verified 197seen = {"n" :0 } 198 199def full (src ,dst ,size ,stop ,tick ): 200seen ["n" ]+= 1 201if seen ["n" ]== 3 : 202part = dst .with_name (dst .name + ".part" ) 203part .parent .mkdir (parents = True ,exist_ok = True ) 204part .write_bytes (b"half" ) 205try : 206raise OSError (28 ,"No space left on device" ,str (dst )) 207except OSError as e : 208mm ._quiet_remove (part ) 209raise mm .MoveError ("disk_full" ,"The drive ran out of space." ,str (e ))from e 210return real (src ,dst ,size ,stop ,tick ) 211with self .copy_mode (),mock .patch .object (mm ,"_copy_verified" ,side_effect = full ): 212with self .assertRaises (mm .MoveError )as caught : 213self .run_move () 214self .assertEqual (caught .exception .code ,"disk_full" ) 215self .assertEqual (list (self .new .rglob ("*.part" )), []) 216for rel ,data in self .files .items (): 217places = [r for r in (self .old ,self .new )if (r / rel ).exists ()] 218self .assertEqual (len (places ),1 ,rel ) 219self .assertIn ("remaining" ,caught .exception .summary ) 220 221def test_a_real_disk_full_error_is_named (self ): 222with mock .patch ("builtins.open" ,side_effect = OSError (28 ,"No space left on device" ,"x" )): 223with self .assertRaises (mm .MoveError )as caught : 224mm ._copy_verified (self .old / "models/coder/c.gguf" ,self .new / "x.gguf" ,1 ,lambda :False ,lambda n :None ) 225self .assertEqual (caught .exception .code ,"disk_full" ) 226 227def test_a_crash_leaves_a_part_and_the_next_run_finishes (self ): 228stale = self .new / "models/gyro-s/a.gguf.part" 229stale .parent .mkdir (parents = True ) 230stale .write_bytes (b"cut off" ) 231# a file that was copied and renamed, but whose original was not removed yet 232done = self .new / "models/coder/c.gguf" 233done .parent .mkdir (parents = True ) 234done .write_bytes (self .files ["models/coder/c.gguf" ]) 235with self .copy_mode (): 236summary ,_ = self .run_move () 237self .assertTrue (summary ["done" ]) 238self .check_whole () 239 240def test_an_interrupted_move_is_remembered (self ): 241self .cut_off (1 ) 242st = mm .interrupted (self .old )# the old folder is still the data folder: it holds the pointer 243self .assertEqual (st ["to" ],str (self .new )) 244self .assertEqual (st ["state" ],"failed" ) 245self .assertEqual (mm .interrupted (self .base / "elsewhere" ),None ) 246mm ._write_state (self .old ,state = "running" ,pid = os .getpid ()+ 7 ,token = None ,** {"from" :str (self .old ),"to" :str (self .new )}) 247self .assertEqual (mm .interrupted (self .old )["state" ],"running" ) 248 249def test_a_move_that_is_running_now_is_not_interrupted (self ): 250from strata_control import procs 251mm ._write_state (self .old ,state = "running" ,pid = os .getpid ()+ 7 ,token = "t" ,** {"from" :str (self .old ),"to" :str (self .new )}) 252with mock .patch .object (procs ,"start_token" ,return_value = "t" ): 253self .assertIsNone (mm .interrupted (self .old )) 254with mock .patch .object (procs ,"start_token" ,return_value = None ): 255self .assertIsNotNone (mm .interrupted (self .old )) 256 257def test_nothing_moved_leaves_nothing_to_ask_about (self ): 258self .cut_off (0 ) 259self .assertIsNone (mm .interrupted (self .old )) 260self .assertFalse ((self .new / mm .STATE_FILE ).exists ()) 261 262def test_finish_resumes_the_move (self ): 263self .cut_off (1 ) 264st = mm .interrupted (self .old ) 265with self .copy_mode (): 266summary = mm .move (Path (st ["from" ]),Path (st ["to" ]),configs = [self .config ]) 267self .assertTrue (summary ["done" ]) 268self .check_whole () 269self .assertIsNone (mm .interrupted (self .old )) 270self .assertFalse ((self .old / mm .STATE_FILE ).exists ()or (self .new / mm .STATE_FILE ).exists ()) 271 272def test_leave_keeps_the_old_folder_complete (self ): 273self .cut_off (1 ) 274 (self .new / "models/stray.gguf.part" ).write_bytes (b"x" )# not listed by the move, but a .part of ours is 275 (self .new / "models/gyro-s" ).mkdir (parents = True ,exist_ok = True ) 276 (self .new / "models/gyro-s/a.gguf.part" ).write_bytes (b"cut" ) 277theirs = self .new / "models/own/mine.gguf" # a file of the person's, not part of the move 278theirs .parent .mkdir (parents = True ) 279theirs .write_bytes (b"mine" ) 280st = mm .interrupted (self .old ) 281with self .copy_mode (): 282result = mm .leave (Path (st ["from" ]),Path (st ["to" ]),configs = [self .config ]) 283self .assertGreaterEqual (result ["restored" ]+ result ["removed" ],1 ) 284for rel ,data in self .files .items (): 285self .assertEqual ((self .old / rel ).read_bytes (),data ,rel ) 286self .assertFalse ((self .new / rel ).exists (),rel ) 287self .assertEqual (list (self .new .rglob ("*.part" )), [(self .new / "models/stray.gguf.part" )]) 288self .assertTrue (theirs .exists ()) 289self .assertIsNone (mm .interrupted (self .old )) 290self .assertFalse ((self .new / mm .STATE_FILE ).exists ()) 291cfg = json .loads (self .config .read_text ()) 292self .assertTrue (all (str (self .new )not in str (v )for v in cfg .values ())) 293self .assertIn (str (self .old / "models/gyro-s/a.gguf" ),cfg ["args" ]) 294 295def test_leave_after_a_crash_removes_the_duplicate (self ): 296self .cut_off (1 ) 297dup = self .new / "models/coder/c.gguf" # copied and renamed, original not yet removed 298dup .parent .mkdir (parents = True ,exist_ok = True ) 299dup .write_bytes (self .files ["models/coder/c.gguf" ]) 300mm .leave (self .old ,self .new ) 301self .assertFalse (dup .exists ()) 302self .assertTrue ((self .old / "models/coder/c.gguf" ).exists ()) 303 304def test_configs_are_rewritten_only_for_files_that_are_there (self ): 305self .config .write_text (json .dumps ({"args" : ["--native" ,str (self .old / "models/gone.gguf" )]})) 306with self .copy_mode (): 307self .run_move () 308self .assertEqual (json .loads (self .config .read_text ())["args" ][1 ],str (self .old / "models/gone.gguf" )) 309 310@ unittest . skipUnless ( os . environ . get ( "STRATA_TEST_OTHER_VOLUME" ), "set STRATA_TEST_OTHER_VOLUME to a folder on another volume (e.g. a subst or USB drive)" ) 311def test_a_real_second_volume (self ): 312other = Path (os .environ ["STRATA_TEST_OTHER_VOLUME" ])/ f"strata-move- { os . getpid () } " 313self .addCleanup (shutil .rmtree ,other ,True ) 314self .new = other 315summary ,_ = self .run_move () 316self .assertTrue (summary ["done" ]) 317self .check_whole () 318 319 320class CommandLineTests (MoveCase ): 321def test_json_plan_and_run (self ): 322from strata_cli import cli 323import contextlib 324import io 325out = io .StringIO () 326with contextlib .redirect_stdout (out ),self .copy_mode (): 327code = cli .main (["models" ,"move" ,str (self .new ),"--from" ,str (self .old ),"--plan" ,"--output" ,"json" ]) 328self .assertEqual (code ,0 ) 329self .assertTrue (json .loads (out .getvalue ())["plan" ]["choices" ]["move" ]["possible" ]) 330out = io .StringIO () 331with contextlib .redirect_stdout (out ),self .copy_mode (): 332code = cli .main (["models" ,"move" ,str (self .new ),"--from" ,str (self .old ),"--install-dir" ,str (self .install ),"--output" ,"jsonl" ]) 333self .assertEqual (code ,0 ,out .getvalue ()) 334lines = [json .loads (line )for line in out .getvalue ().splitlines ()if line .startswith ("{" )] 335self .assertEqual (lines [- 1 ]["event" ],"result" ) 336self .assertTrue (lines [- 1 ]["done" ]) 337self .assertTrue ((self .new / "models/coder/c.gguf" ).exists ()) 338 339def run_cli (self ,* argv ): 340from strata_cli import cli 341from strata_control import discovery 342import contextlib 343import io 344out = io .StringIO () 345with contextlib .redirect_stdout (out ),self .copy_mode (),mock .patch .object (discovery ,"data_dir" ,return_value = (self .old ,"settings" )): 346code = cli .main (["models" ,"move" ,* argv ]) 347return code ,out .getvalue () 348 349def test_status_resume_and_leave (self ): 350code ,text = self .run_cli ("--status" ,"--output" ,"json" ) 351self .assertEqual ((code ,json .loads (text )["interrupted" ]), (0 ,None )) 352self .assertEqual (self .run_cli ("--resume" ,"--output" ,"json" )[0 ],5 ) 353self .cut_off (1 ) 354code ,text = self .run_cli ("--status" ,"--output" ,"json" ) 355self .assertEqual (json .loads (text )["interrupted" ]["to" ],str (self .new )) 356self .assertIn ("--resume" ,self .run_cli ("--status" )[1 ]) 357code ,text = self .run_cli ("--leave" ,"--install-dir" ,str (self .install ),"--output" ,"json" ) 358self .assertEqual (code ,0 ,text ) 359self .assertTrue ((self .old / "models/coder/c.gguf" ).exists ()) 360self .cut_off (1 ) 361code ,text = self .run_cli ("--resume" ,"--install-dir" ,str (self .install ),"--output" ,"jsonl" ) 362self .assertEqual (code ,0 ,text ) 363self .assertTrue ([json .loads (l )for l in text .splitlines ()if l .startswith ("{" )][- 1 ]["done" ]) 364self .assertTrue ((self .new / "models/coder/c.gguf" ).exists ()) 365self .assertFalse ((self .old / "models/coder/c.gguf" ).exists ()) 366 367def test_launch_says_it_in_one_line (self ): 368from strata_cli .launch import cmd 369from strata_control import discovery 370import contextlib 371import io 372self .cut_off (1 ) 373with mock .patch .object (discovery ,"data_dir" ,return_value = (self .old ,"settings" )): 374out = io .StringIO () 375with contextlib .redirect_stdout (out ): 376cmd ._interrupted_move_notice () 377self .assertEqual (len (out .getvalue ().strip ().splitlines ()),1 ) 378self .assertIn ("models move --resume" ,out .getvalue ()) 379mm .leave (self .old ,self .new ) 380out = io .StringIO () 381with contextlib .redirect_stdout (out ): 382cmd ._interrupted_move_notice () 383self .assertEqual (out .getvalue (),"" ) 384 385def test_the_cancel_file_stops_the_run (self ): 386from strata_cli import cli 387import contextlib 388import io 389cancel = self .base / "cancel" 390cancel .write_text ("x" ) 391out = io .StringIO () 392with contextlib .redirect_stdout (out ),self .copy_mode (): 393code = cli .main (["models" ,"move" ,str (self .new ),"--from" ,str (self .old ),"--cancel-file" ,str (cancel ),"--output" ,"json" ]) 394self .assertEqual (code ,6 ) 395self .assertTrue (json .loads (out .getvalue ().splitlines ()[- 1 ])["stopped" ]) 396self .assertTrue ((self .old / "models/coder/c.gguf" ).exists ()) 397 398 399if __name__ == "__main__" : 400unittest .main ()