okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
40df1f76f
main
1"""The component updater end to end against a LOCAL feed: a folder of signed archives served by a loopback HTTP server, stub 2engines behind real schema-2 packages, the real start path for the test start. 3 4Proves: an update downloads (with resume), verifies signature and every hash, installs side by side, test-starts the new 5engine from a staging folder through the owner runtime, and only then switches; a failing test start leaves the old engine 6working; the previous version is kept and can be returned to; saved presets are marked, not touched; models are never 7fetched; nothing runs while an engine serves; and a start/serve process (STRATA_NO_ACQUIRE) cannot reach any of it.""" 8 9import hashlib 10import json 11import os 12import shutil 13import sys 14import tempfile 15import unittest 16from pathlib import Path 17from unittest import mock 18 19from strata_control import acquisition ,engine_component as ec ,feed as feedmod ,preset_marks ,signing ,updater 20from strata_control .targets import host_platform 21from tests .terminal import update_fixture as fx 22 23PLATFORM = host_platform () 24WINDOWS = os .name == "nt" 25 26 27class UpdaterCase (unittest .TestCase ): 28def setUp (self ): 29self .temp = tempfile .TemporaryDirectory (prefix = "strata-updater-" ) 30self .addCleanup (self .temp .cleanup ) 31self .root = Path (self .temp .name ) 32self .components = self .root / "components" 33self .state_base = self .root / "state" 34self .release = self .root / "release" 35self .release .mkdir () 36for name in ("STRATA_NO_ACQUIRE" ,"STRATA_API_KEY" ,"STRATA_REQUIRE_SIGNED_COMPONENTS" ,"STRATA_UPDATE_TRUSTED_KEYS" ): 37patch = mock .patch .dict (os .environ ) 38patch .start () 39self .addCleanup (patch .stop ) 40os .environ .pop (name ,None ) 41env = mock .patch .dict (os .environ , { 42"STRATA_PROFILE_DIR" :str (self .root / "profiles" ),"STRATA_RUNTIME_DIR" :str (self .root / "runtime" ), 43"STRATA_COMPONENTS_DIR" :str (self .components ),"STRATA_ENGINE_BACKEND" :"cuda" , 44"FAKE_ENGINE_MARK" :str (self .root / "ran.txt" )}) 45env .start () 46self .addCleanup (env .stop ) 47for target ,value in ((ec ,"cuda_archs_present" ), (ec ,"nvidia_driver_version" )): 48patch = mock .patch .object (target ,value ,return_value = ["sm_86" ]if value == "cuda_archs_present" else "610.47" ) 49patch .start () 50self .addCleanup (patch .stop ) 51ec .register_signature_verifier (None )# a verifier an earlier test file left behind (it holds the shipped keys only) must not decide here 52self .addCleanup (ec .register_signature_verifier ,None ) 53# the tests sign with throwaway keys that they hand over explicitly: the release key shipped in update_keys.json is not in play here 54# (ReleaseKeys below checks the shipped file itself) 55patch = mock .patch .object (signing ,"BUILTIN_KEYS" ,self .root / "no-shipped-keys.json" ) 56patch .start () 57self .addCleanup (patch .stop ) 58self .key = fx .make_key () 59self .trusted = fx .trusted_of (self .key ) 60# the engine a test start runs is a child process: it reads the shipped release key too, so the test key is passed the way a 61# tester build passes its key 62self .test_keys = self .root / "test-trust.json" 63self .test_keys .write_text (json .dumps ({"keys" : [signing .public_part (self .key )]})) 64patch = mock .patch .dict (os .environ , {"STRATA_UPDATE_TRUSTED_KEYS" :str (self .test_keys )}) 65patch .start () 66self .addCleanup (patch .stop ) 67self .hardware = {"platform" :PLATFORM ,"backend" :"cuda" ,"runtime" :None ,"nvidia_driver" :"610.47" , 68"cuda_archs" : ["sm_86" ],"gfx" : []} 69self .models = self .root / "models" 70self .models .mkdir () 71 (self .models / "model.gguf" ).write_bytes (b"GGUF" + os .urandom (2048 )) 72self .model_digest = hashlib .sha256 ((self .models / "model.gguf" ).read_bytes ()).hexdigest () 73self .preset = self .state_base / "tuning" / "presets" / "iq3-128k.json" 74self .preset .parent .mkdir (parents = True ) 75self .preset .write_text ('{"name": "IQ3_S 128K full speed", "settings": {"expert_cache": 1500}}\n' ) 76self .preset_bytes = self .preset .read_bytes () 77self ._run_config () 78self .server = fx .FeedServer (self .release ) 79self .server .__enter__ () 80self .addCleanup (self .server .__exit__ ) 81self .sequence = 0 82self .addCleanup (self ._stop_runtime ) 83 84def _stop_runtime (self ): 85from strata_control import runtime 86try : 87if runtime ._read_state ("updtest" )is not None : 88runtime .stop ("updtest" ,timeout = 10 ) 89except Exception :# noqa: BLE001 90pass 91 92def _run_config (self ): 93from tools .strata_tokenizer import BYTE_TO_UNICODE 94tokenizer = self .root / "tokenizer" 95tokenizer .mkdir () 96tokens = [BYTE_TO_UNICODE [i ]for i in range (256 )]+ ["ab" ,"<|im_start|>" ,"<|im_end|>" ,"<|endoftext|>" ] 97 (tokenizer / "vocab.json" ).write_text (json .dumps ({token :i for i ,token in enumerate (tokens )})) 98 (tokenizer / "merges.txt" ).write_text ("a b" ) 99 (tokenizer / "token_type.json" ).write_text (json .dumps ([0 ]* 257 + [3 ,3 ,3 ])) 100self .config = self .root / "run.json" 101self .config .write_text (json .dumps ({"exe" :"/some/old/engine" ,"backend" :"cuda" ,"tokenizer" :str (tokenizer ),"args" : [], 102"cwd" :str (self .root ),"model_name" :"fake" ,"host" :"127.0.0.1" ,"port" :0 })) 103 104# ------------------------------------------------------------------ helpers 105 106def install_current (self ,version = "0.1.45" ,** kwargs ): 107folder = fx .build_package (self .root / f"inst- { version } " ,version ,** kwargs ) 108target = self .components / "engine" / folder .name 109target .parent .mkdir (parents = True ,exist_ok = True ) 110shutil .copytree (folder ,target ) 111return target 112 113def publish (self ,* versions ,sequence = None ,key = None ,** options ): 114"""Sign + archive each (version, engine_source[, kwargs]) and write a signed feed. Returns the package folders.""" 115shutil .rmtree (self .release ,ignore_errors = True ) 116self .release .mkdir () 117out = self .release / "engine" 118out .mkdir () 119key = key or self .key 120self .sequence = sequence or self .sequence + 1 121folders = [] 122for item in versions : 123version ,source ,extra = (item + ({},))[:3 ]if len (item )== 2 else item 124folder = fx .build_package (self .root / f"pub- { self . sequence } - { version } " ,version ,engine_source = source ,key = extra .pop ("sign_with" ,key ),** extra ) 125folders .append (folder ) 126from feed_tool import pack_engine 127pack_engine (folder ,out ) 128from feed_tool import build_feed 129build_feed (self .release ,key = key ,sequence = self .sequence ,engine_dir = out ,** options ) 130return folders 131 132def ctx (self ,** over ): 133values = dict (components = self .components ,source = self .server .url + "/strata-feed.json" ,trusted = self .trusted , 134hardware = self .hardware ,run_config = str (self .config ),state_base = self .state_base ,poll = 0.05 , 135test_timeout = 60 ,serving = lambda : [],environ = dict (os .environ )) 136values .update (over ) 137events = values .pop ("events" ,None ) 138context = updater .Context (** values ) 139if events is not None : 140context .emit = events .append 141return context 142 143def engine_folders (self ): 144folder = self .components / "engine" 145return sorted (p .name for p in folder .iterdir ()if p .is_dir ())if folder .exists ()else [] 146 147def resolved (self ): 148return ec .resolve (self .components ,backend = "cuda" ).version 149 150def assert_user_data_untouched (self ): 151self .assertEqual (self .preset .read_bytes (),self .preset_bytes ,"a saved preset must not change" ) 152self .assertEqual (hashlib .sha256 ((self .models / "model.gguf" ).read_bytes ()).hexdigest (),self .model_digest ) 153 154def archive_requests (self ): 155return [r for r in self .server .requests if r [1 ].endswith ((".tar.gz" ,".zip" ))] 156 157 158class EngineUpdate (UpdaterCase ): 159def test_check_reads_only_the_feed (self ): 160self .install_current () 161self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 162report = updater .check (self .ctx ()) 163self .assertEqual (report ["engine" ]["status" ],"available" ) 164self .assertEqual ((report ["engine" ]["installed" ]["version" ],report ["engine" ]["offered" ]["version" ]), ("0.1.45" ,"0.1.46" )) 165self .assertEqual ([r [1 ]for r in self .server .requests ], ["/strata-feed.json" ,"/strata-feed.json.sig" ]) 166self .assertEqual (self .engine_folders (), [f"0.1.45- { PLATFORM } -cuda-cuda13" ]) 167 168def test_update_downloads_verifies_test_starts_then_switches (self ): 169old = self .install_current () 170self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 171events = [] 172out = updater .run_update (self .ctx (events = events ),control = False ) 173result = out ["results" ][0 ] 174self .assertEqual ((out ["exit_code" ],result ["status" ],result ["changed" ]), (0 ,"updated" ,True ),out ) 175self .assertEqual (result ["test_start" ]["mode" ],"full" ) 176self .assertEqual (self .resolved (),"0.1.46" ) 177self .assertEqual (sorted (self .engine_folders ()), [f"0.1.45- { PLATFORM } -cuda-cuda13" ,f"0.1.46- { PLATFORM } -cuda-cuda13" ], 178"the previous version stays for a manual rollback" ) 179# the test start ran the staged copy, not a file in the live folder 180ran = (self .root / "ran.txt" ).read_text ().splitlines ()[0 ] 181self .assertIn (os .sep + ".s" + os .sep ,ran ) 182phases = [e .get ("phase" )for e in events if e .get ("event" )== "phase" ] 183phases = [p for i ,p in enumerate (phases )if i == 0 or p != "test" or phases [i - 1 ]!= "test" ]# progress lines of the test start repeat it 184self .assertEqual (phases , ["feed" ,"download" ,"verify" ,"verify" ,"test" ,"switch" ,"done" ]) 185progress = [e for e in events if e .get ("event" )== "progress" ] 186self .assertTrue (progress and progress [- 1 ]["percent" ]== 100 and progress [- 1 ]["done" ]== progress [- 1 ]["total" ]) 187self .assertEqual (sorted (p .name for p in (self .components / ".s" ).iterdir ()), [],"staging is cleaned" ) 188self .assertEqual (list ((self .components / ".updates" / "partial" ).iterdir ()), [],"the archive is removed after the switch" ) 189state = json .loads ((self .components / ".updates" / "state.json" ).read_text ()) 190self .assertEqual (state ["engine" ]["previous" ],old .name ) 191self .assertEqual (state ["feed" ]["sequence" ],self .sequence ) 192# presets are marked for the short re-check and kept as they were 193marks = preset_marks .pending (self .state_base ) 194self .assertEqual (len (marks ),1 ) 195self .assertEqual ((marks [0 ]["from" ]["version" ],marks [0 ]["to" ]["version" ]), ("0.1.45" ,"0.1.46" )) 196self .assert_user_data_untouched () 197# nothing but the feed and the engine archive was requested: no model, no app 198self .assertEqual ({r [1 ]for r in self .server .requests }, {"/strata-feed.json" ,"/strata-feed.json.sig" ,* {r [1 ]for r in self .archive_requests ()}}) 199self .assertEqual (len (self .archive_requests ()),1 ) 200# a second update with nothing newer changes nothing and downloads nothing 201again = updater .run_update (self .ctx (),control = False ) 202self .assertEqual (again ["results" ][0 ]["status" ],"current" ) 203self .assertEqual (len (self .archive_requests ()),1 ) 204 205def test_updates_keep_every_older_engine_until_the_person_deletes_one (self ): 206self .install_current () 207self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 208updater .run_update (self .ctx (),control = False ) 209self .publish (("0.1.47" ,fx .GOOD_ENGINE )) 210out = updater .run_update (self .ctx (),control = False ) 211self .assertEqual (out ["results" ][0 ]["status" ],"updated" ) 212self .assertEqual (self .engine_folders (), [f"0.1.45- { PLATFORM } -cuda-cuda13" ,f"0.1.46- { PLATFORM } -cuda-cuda13" ,f"0.1.47- { PLATFORM } -cuda-cuda13" ]) 213self .assertEqual (out ["results" ][0 ]["removed" ], []) 214self .assertEqual (self .resolved (),"0.1.47" ) 215 216def test_a_failing_test_start_keeps_the_old_engine (self ): 217self .install_current () 218self .publish (("0.1.47" ,fx .BAD_ENGINE )) 219out = updater .run_update (self .ctx (),control = False ) 220result = out ["results" ][0 ] 221self .assertEqual ((out ["exit_code" ],result ["status" ]), (6 ,"failed" ),out ) 222self .assertIn ("did not start correctly on this computer" ,result ["error" ]) 223self .assertIn ("unchanged" ,result ["error" ]) 224self .assertNotIn ("server_exited" ,result ["error" ],"the engine's own words stay out of the sentence" ) 225self .assertIn ("strata update --force" ,result ["error" ]) 226self .assertEqual (self .resolved (),"0.1.45" ) 227self .assertEqual (self .engine_folders (), [f"0.1.45- { PLATFORM } -cuda-cuda13" ],"the failed engine was never put in the live folder" ) 228self .assertEqual (sorted (p .name for p in (self .components / ".s" ).iterdir ()), []) 229self .assertEqual (preset_marks .pending (self .state_base ), []) 230self .assert_user_data_untouched () 231# it is not offered again until forced, and the archive is not downloaded twice 232again = updater .run_update (self .ctx (),control = False ) 233self .assertEqual (again ["results" ][0 ]["status" ],"failed-before" ,again ) 234self .assertIn ("--force" ,again ["results" ][0 ]["note" ]) 235forced = updater .run_update (self .ctx (force = True ),control = False ) 236self .assertEqual (forced ["results" ][0 ]["status" ],"failed" ) 237self .assertEqual (len (self .archive_requests ()),1 ,"the verified archive was kept and reused" ) 238# a fixed build of the same version is a different manifest and is tried 239self .publish (("0.1.47" ,fx .GOOD_ENGINE )) 240fixed = updater .run_update (self .ctx (),control = False ) 241self .assertEqual (fixed ["results" ][0 ]["status" ],"updated" ,fixed ) 242self .assertEqual (self .resolved (),"0.1.47" ) 243 244def test_an_interrupted_download_resumes (self ): 245self .install_current () 246self .publish (("0.1.46" ,fx .GOOD_ENGINE , {"padding" :3_000_000 })) 247self .server .cut [".tar.gz" ]= 700_000 248first = updater .run_update (self .ctx (),control = False )# the connection broke part-way: the same run continues from the byte it reached 249self .assertEqual ((first ["exit_code" ],first ["results" ][0 ]["status" ]), (0 ,"updated" ),first ) 250ranges = [r [2 ]for r in self .archive_requests ()] 251self .assertEqual (ranges , [None ,"bytes=700000-" ],"exactly one more request, from the byte the cut reached: no byte twice (the SHA-256 is checked by the update)" ) 252self .assertEqual (self .resolved (),"0.1.46" ) 253 254def test_a_download_that_is_not_the_signed_hash_is_refused (self ): 255self .install_current () 256self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 257archive = next ((self .release / "engine" ).glob ("*.tar.gz" )) 258data = bytearray (archive .read_bytes ()) 259data [len (data )// 2 ]^= 0x55 # same size, one byte different 260archive .write_bytes (bytes (data )) 261out = updater .run_update (self .ctx (),control = False ) 262result = out ["results" ][0 ] 263self .assertEqual ((out ["exit_code" ],result ["status" ]), (5 ,"failed" )) 264self .assertIn ("SHA-256 in the signed feed" ,result ["error" ]) 265self .assertEqual (list ((self .components / ".updates" / "partial" ).iterdir ()), [],"bytes that fail the hash are deleted" ) 266self .assertEqual (self .resolved (),"0.1.45" ) 267self .assertFalse ((self .root / "ran.txt" ).exists (),"a package that failed its hash must never run" ) 268 269def test_a_package_the_feed_did_not_describe_is_refused (self ): 270self .install_current () 271self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 272entry = next ((self .release / "engine" ).glob ("*.entry.json" )) 273data = json .loads (entry .read_text ()) 274data ["manifest_sha256" ]= "c" * 64 275entry .write_text (json .dumps (data )) 276from feed_tool import build_feed 277build_feed (self .release ,key = self .key ,sequence = self .sequence + 1 ,engine_dir = self .release / "engine" ) 278out = updater .run_update (self .ctx (),control = False ) 279self .assertEqual (out ["exit_code" ],5 ) 280self .assertIn ("manifest is not the one the signed feed names" ,out ["results" ][0 ]["error" ]) 281self .assertEqual (self .resolved (),"0.1.45" ) 282self .assertFalse ((self .root / "ran.txt" ).exists ()) 283 284def test_unsigned_and_wrongly_signed_packages_are_refused (self ): 285self .install_current () 286other = fx .make_key () 287for label ,kind in (("not signed" ,None ), ("trust" ,other )): 288with self .subTest (label = label ): 289shutil .rmtree (self .release ,ignore_errors = True ) 290self .release .mkdir () 291self .sequence += 1 292folder = fx .build_package (self .root / f"x- { self . sequence } " ,"0.1.46" ,key = kind ) 293from feed_tool import build_feed ,pack_engine 294 (self .release / "engine" ).mkdir () 295pack_engine (folder ,self .release / "engine" ) 296build_feed (self .release ,key = self .key ,sequence = self .sequence ,engine_dir = self .release / "engine" ) 297out = updater .run_update (self .ctx (),control = False ) 298self .assertEqual (out ["exit_code" ],5 ,out ) 299self .assertIn (label ,out ["results" ][0 ]["error" ]) 300self .assertEqual (self .resolved (),"0.1.45" ) 301self .assertFalse ((self .root / "ran.txt" ).exists ()) 302 303def test_a_downgrade_is_never_installed (self ): 304self .install_current ("0.1.45" ) 305self .publish (("0.1.44" ,fx .GOOD_ENGINE )) 306out = updater .run_update (self .ctx (),control = False ) 307result = out ["results" ][0 ] 308self .assertEqual ((result ["status" ],result ["changed" ]), ("current" ,False )) 309self .assertIn ("never downgrades" ,updater .check (self .ctx ())["engine" ]["note" ]) 310self .assertEqual (self .archive_requests (), []) 311self .assertEqual (self .resolved (),"0.1.45" ) 312 313def test_a_replayed_older_feed_is_refused (self ): 314self .install_current () 315self .publish (("0.1.46" ,fx .GOOD_ENGINE ),sequence = 7 ) 316self .assertEqual (updater .run_update (self .ctx (),control = False )["results" ][0 ]["status" ],"updated" ) 317self .publish (("0.1.46" ,fx .GOOD_ENGINE ),sequence = 3 ) 318with self .assertRaises (feedmod .FeedDowngrade ): 319updater .run_update (self .ctx (),control = False ) 320with self .assertRaises (feedmod .FeedDowngrade ): 321updater .check (self .ctx ()) 322 323def test_nothing_is_replaced_while_an_engine_serves (self ): 324self .install_current () 325self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 326with self .assertRaises (updater .Busy )as caught :# refused up front: nothing is downloaded, staged or test-started 327updater .run_update (self .ctx (serving = lambda : [{"profile" :"app-1" ,"state" :"ready" }]),control = False ) 328self .assertEqual (caught .exception .exit_code ,7 ) 329self .assertIn ("app-1 is serving" ,str (caught .exception )) 330self .assertEqual (self .resolved (),"0.1.45" ) 331self .assertFalse ((self .root / "ran.txt" ).exists (),"no test start while another engine serves" ) 332self .assertEqual (self .archive_requests (), [],"no download beside a loaded model" ) 333done = updater .run_update (self .ctx (),control = False ) 334self .assertEqual (done ["results" ][0 ]["status" ],"updated" ) 335self .assertEqual (len (self .archive_requests ()),1 ) 336 337def test_a_model_that_starts_during_the_download_stops_the_update_and_the_archive_is_kept (self ): 338self .install_current () 339self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 340answers = [[], [{"profile" :"app-1" ,"state" :"ready" }], [{"profile" :"app-1" ,"state" :"ready" }]] 341out = updater .run_update (self .ctx (serving = lambda :answers .pop (0 )if len (answers )> 1 else answers [0 ]),control = False ) 342self .assertEqual ((out ["exit_code" ],out ["results" ][0 ]["status" ]), (7 ,"failed" )) 343self .assertEqual (self .resolved (),"0.1.45" ) 344done = updater .run_update (self .ctx (),control = False ) 345self .assertEqual (done ["results" ][0 ]["status" ],"updated" ) 346self .assertEqual (len (self .archive_requests ()),1 ,"the verified archive was reused" ) 347 348def test_waiting_for_the_engine_to_stop (self ): 349self .install_current () 350self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 351answers = [[{"profile" :"app-1" }], [{"profile" :"app-1" }], [], []] 352events = [] 353out = updater .run_update (self .ctx (serving = lambda :answers .pop (0 )if answers else [],wait = 30 ,events = events ),control = False ) 354self .assertEqual (out ["results" ][0 ]["status" ],"updated" ,out ) 355self .assertTrue (any (e .get ("event" )== "waiting" for e in events )) 356 357def test_manual_rollback_returns_to_the_previous_engine_and_is_not_undone_by_the_next_update (self ): 358self .install_current () 359self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 360updater .run_update (self .ctx (),control = False ) 361out = updater .rollback_engine (self .ctx ()) 362self .assertEqual ((out ["status" ],out ["from" ],out ["to" ]), ("rolled-back" ,"0.1.46" ,"0.1.45" )) 363self .assertEqual (self .resolved (),"0.1.45" ) 364self .assertEqual (ec .status (self .components ,backend = "cuda" )["pinned" ],f"0.1.45- { PLATFORM } -cuda-cuda13" ) 365self .assertEqual (preset_marks .pending (self .state_base ), [],"back on the engine the presets were measured on: nothing owed" ) 366self .assertEqual (self .resolved (),"0.1.45" ) 367# the update still offers the version that was rolled back from; it is already here, so nothing is downloaded and it becomes the engine in use 368archives = len (self .archive_requests ()) 369again = updater .run_update (self .ctx (),control = False ) 370self .assertEqual (again ["results" ][0 ]["status" ],"updated" ,again ) 371self .assertTrue (again ["results" ][0 ]["from_disk" ]) 372self .assertEqual (len (self .archive_requests ()),archives ,"no engine archive was requested" ) 373self .assertEqual (self .resolved (),"0.1.46" ) 374self .assertIsNone (ec .pinned_folder (self .components ),"an update clears the pin: the newest is the engine in use again" ) 375self .assert_user_data_untouched () 376 377def test_rollback_without_a_previous_engine_says_so (self ): 378self .install_current () 379with self .assertRaisesRegex (updater .UpdateError ,"no previous engine" ): 380updater .rollback_engine (self .ctx ()) 381 382def test_first_run_installs_the_engine_for_this_pc_without_a_model (self ): 383self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 384with mock .patch .object (updater ,"discover_run_config" ,return_value = None ):# whatever this machine has installed 385out = updater .run_update (self .ctx (run_config = None ),control = False ) 386result = out ["results" ][0 ] 387self .assertEqual ((out ["exit_code" ],result ["status" ]), (0 ,"updated" ),out ) 388self .assertEqual (result ["test_start" ]["mode" ],"binary-only" ) 389self .assertEqual (self .resolved (),"0.1.46" ) 390self .assertEqual (preset_marks .pending (self .state_base ), [],"no earlier engine, so nothing to re-check" ) 391 392def test_a_broken_installed_engine_is_replaced_by_a_good_one (self ): 393folder = self .install_current ("0.1.46" ) 394library = next (p for p in folder .iterdir ()if p .name .startswith (("cudart" ,"libcudart" ))) 395body = bytearray (library .read_bytes ()) 396body [5 ]^= 0xFF 397library .write_bytes (bytes (body )) 398self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 399self .assertEqual (updater .check (self .ctx ())["engine" ]["status" ],"install" ) 400out = updater .run_update (self .ctx (),control = False ) 401self .assertEqual (out ["results" ][0 ]["status" ],"updated" ,out ) 402self .assertEqual (self .resolved (),"0.1.46" ) 403 404def test_the_package_for_another_gpu_is_not_offered (self ): 405self .publish (("0.1.46" ,fx .GOOD_ENGINE , {"archs" : ("sm_90" ,)})) 406out = updater .run_update (self .ctx (hardware = {** self .hardware ,"cuda_archs" : ["sm_61" ]}),control = False ) 407self .assertEqual (out ["results" ][0 ]["status" ],"none-for-this-pc" ) 408self .assertIn ("sm_61" ," " .join (out ["results" ][0 ]["reasons" ])) 409self .assertEqual (self .archive_requests (), []) 410 411def test_a_process_that_forbids_acquiring_cannot_update (self ): 412self .install_current () 413self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 414with mock .patch .dict (os .environ , {"STRATA_NO_ACQUIRE" :"1" }): 415with self .assertRaises (acquisition .AcquisitionRefused ): 416updater .run_update (self .ctx (),control = False ) 417with self .assertRaises (acquisition .AcquisitionRefused ): 418updater .check (self .ctx ()) 419self .assertEqual (self .server .requests , [],"not even the feed is read where acquiring is forbidden" ) 420 421def test_a_started_engine_check_does_not_import_the_updater (self ): 422"""The start path (engine_component, runtime) must not reach the update machinery or the network code.""" 423import subprocess 424code = ("import sys; import strata_control.engine_component, strata_control.runtime, strata_control.acquisition; " 425"import strata_cli.cli as c; c.parser(); " 426"print(sorted(m for m in sys.modules if m in ('strata_control.updater','strata_control.transfer','strata_control.feed')))" ) 427done = subprocess .run ([sys .executable ,"-c" ,code ],capture_output = True ,text = True ,cwd = str (fx .ROOT )) 428self .assertEqual (done .returncode ,0 ,done .stderr ) 429self .assertEqual (done .stdout .strip (),"[]" ) 430 431 432class StartPathSignature (UpdaterCase ): 433"""A start verifies a signed package with the keys this build trusts, without anything registering a verifier first.""" 434 435def setUp (self ): 436super ().setUp () 437self .pub = self .root / "feed-key.pub.json" 438self .pub .write_text (json .dumps ({"keys" : [signing .public_part (self .key )]})) 439patch = mock .patch .dict (os .environ , {"STRATA_UPDATE_TRUSTED_KEYS" :str (self .pub )}) 440patch .start () 441self .addCleanup (patch .stop ) 442ec .register_signature_verifier (None ) 443 444def test_signed_packages_verify_and_a_forged_signature_is_refused_on_every_start (self ): 445folder = fx .build_package (self .root / "signed" ,"0.1.46" ,key = self .key ) 446target = self .components / "engine" / folder .name 447target .parent .mkdir (parents = True ) 448shutil .copytree (folder ,target ) 449self .assertEqual (ec .verify_signature (ec .read_manifest (target )),"verified" ) 450manifest = json .loads ((target / ec .MANIFEST ).read_text ()) 451manifest ["notes" ]= "changed after signing" 452 (target / ec .MANIFEST ).write_text (json .dumps (manifest )) 453ec .register_signature_verifier (None ) 454with self .assertRaises (ec .EngineMissing )as caught : 455ec .resolve (self .components ,backend = "cuda" ) 456self .assertIn ("signature" ,str (caught .exception )) 457 458def test_without_trusted_keys_a_signed_package_is_unverified_and_required_signing_refuses_it (self ): 459folder = fx .build_package (self .root / "signed" ,"0.1.46" ,key = self .key ) 460with mock .patch .dict (os .environ , {"STRATA_UPDATE_TRUSTED_KEYS" :"" }): 461ec .register_signature_verifier (None ) 462self .assertEqual (ec .verify_signature (ec .read_manifest (folder )),"unverified" ) 463with self .assertRaises (ec .IntegrityProblem ): 464ec .verify_signature (ec .read_manifest (folder ), {ec .ENV_REQUIRE_SIGNED :"1" }) 465 466 467class LightTestStart (unittest .TestCase ): 468def test_the_test_start_drops_the_big_context_and_the_picture_reader (self ):# #3842 469args = ["--serve" ,"--pack" ,"p" ,"--max-context" ,"262144" ,"--kv" ,"int8" ,"--kv-resident" ,"32768" ,"--vision" , 470"--vision-tokens" ,"768" ,"--spec" ,"4" ] 471self .assertEqual (updater .light_test_args (args ), ["--serve" ,"--pack" ,"p" ,"--max-context" ,"4096" ,"--kv" ,"int8" ,"--spec" ,"4" ]) 472self .assertEqual (updater .light_test_args (["--max-context" ,"2048" ,"--vision" ,"cpu" ,"--mtp" ,"x" ]), 473 ["--max-context" ,"2048" ,"--mtp" ,"x" ]) 474self .assertEqual (updater .light_test_args (["--vision" ]), []) 475self .assertEqual (updater .light_test_args (["--max-context" ,"abc" ]), ["--max-context" ,"abc" ]) 476 477 478class LazyModel (UpdaterCase ): 479"""A server that is "ready" with its model unloaded has not generated anything yet; the test start forces the load and the probe.""" 480 481def run_default (self ,started ,verified ,tail = None ): 482from strata_control import runtime 483self .install_current () 484folder = fx .build_package (self .root / "lazy" ,"0.1.46" ,key = self .key ) 485stage = self .root / "stage" 486 (stage / "engine" ).mkdir (parents = True ) 487shutil .copytree (folder ,stage / "engine" / folder .name ) 488component = ec .read_manifest (stage / "engine" / folder .name ) 489with mock .patch .object (runtime ,"start" ,return_value = started ),mock .patch .object (runtime ,"verify" ,return_value = verified )as verify ,mock .patch .object (runtime ,"stop" ,return_value = {}): 490with mock .patch .object (updater ,"_log_tail" ,return_value = tail or "" ): 491result = updater .default_test_start (stage ,component ,self .ctx ()) 492return result ,verify 493 494def test_an_unloaded_ready_server_is_made_to_answer_before_the_engine_passes (self ): 495result ,verify = self .run_default ({"ok" :True ,"state" :"ready" ,"generation_ready" :False }, 496 {"ok" :True ,"state" :"ready" ,"generation_ready" :True }) 497self .assertEqual (result ["generation_ready" ],True ) 498self .assertEqual (verify .call_args .kwargs ["load" ],True ) 499 500def test_an_engine_that_cannot_answer_does_not_pass (self ): 501with self .assertRaisesRegex (updater .TestStartFailed ,"before it answered a test question" ): 502self .run_default ({"ok" :True ,"state" :"ready" ,"generation_ready" :False }, {"ok" :False ,"state" :"failed" ,"error" :"probe_generation_no_tokens" }) 503def expired (self ,phase ,words ,busy ): 504# #3683: the engine log always mentions VRAM, so a wait that expired used to be blamed on a busy graphics card 505tail = " | strata serve: 358 MiB of VRAM free with everything loaded" 506with self .assertRaises (updater .TestStartFailed )as raised : 507self .run_default ({"ok" :False ,"state" :"starting" ,"error" :"startup_wait_expired" ,"phase" :phase }, {},tail = tail ) 508text = str (raised .exception ) 509self .assertIn (words ,text ) 510self .assertEqual (raised .exception .busy ,busy ) 511self .assertNotIn ("graphics card or memory looks busy" ,text ) 512self .assertNotIn ("358 MiB" ,text ) 513self .assertIn ("test-start-" ,text )# where the kept log is 514 515def test_an_expired_start_with_the_model_loaded_says_it_did_not_answer (self ): 516self .expired ("verifying_generation" ,"did not answer one token" ,False ) 517 518def test_an_expired_start_with_an_unmatched_ready_file_says_so (self ): 519self .expired ("ready_file_not_matched" ,"could not match it to the engine process" ,False ) 520 521def test_an_expired_start_that_was_still_loading_says_so (self ): 522self .expired ("loading" ,"still loading the model" ,True ) 523 524def test_the_test_start_shows_progress_while_it_waits (self ): 525self .install_current () 526folder = fx .build_package (self .root / "lazy" ,"0.1.46" ,key = self .key ) 527stage = self .root / "stage" 528 (stage / "engine" ).mkdir (parents = True ) 529shutil .copytree (folder ,stage / "engine" / folder .name ) 530component = ec .read_manifest (stage / "engine" / folder .name ) 531events = [] 532ctx = self .ctx () 533ctx .emit = events .append 534 535def fake_start (name ,** kw ): 536for status in ({"state" :"starting" ,"phase" :"loading" }, {"state" :"starting" ,"phase" :"loading" }, 537 {"state" :"starting" ,"phase" :"verifying_generation" }, {"state" :"ready" }): 538kw ["on_status" ](status ) 539return {"ok" :True ,"state" :"ready" ,"generation_ready" :True } 540 541from strata_control import runtime 542with mock .patch .object (runtime ,"start" ,side_effect = fake_start ),mock .patch .object (runtime ,"stop" ,return_value = {}): 543updater .default_test_start (stage ,component ,ctx ) 544lines = [e ["message" ]for e in events if e .get ("phase" )== "test" ] 545self .assertEqual (len (lines ),2 )# one per phase change, not one per poll 546self .assertIn ("loading the model" ,lines [0 ]) 547self .assertIn ("answer one token" ,lines [1 ]) 548 549 550class OtherComponents (UpdaterCase ): 551def build_with_app (self ,version = "0.2.0" ,tamper = False ): 552public ,secret = fx .minisign_pair () 553installer = os .urandom (5000 ) 554 (self .release / "app" ).mkdir (parents = True ,exist_ok = True ) 555 (self .release / "app" / "Strata_setup.bin" ).write_bytes (installer ) 556sig = fx .minisign_sign (installer + (b"x" if tamper else b"" ),secret ) 557app = {"version" :version ,"notes" :"Faster starts." ,"pub_date" :"2026-10-15T00:00:00Z" , 558"platforms" : {feedmod .TAURI_TARGETS [PLATFORM ]: {"url" :"app/Strata_setup.bin" ,"signature" :sig , 559"sha256" :hashlib .sha256 (installer ).hexdigest (),"size" :len (installer )}}} 560 (self .root / "tauri.json" ).write_text (json .dumps (app )) 561from feed_tool import build_feed 562 (self .release / "engine" ).mkdir (exist_ok = True ) 563build_feed (self .release ,key = self .key ,sequence = self .sequence + 1 ,app_json = self .root / "tauri.json" ) 564self .sequence += 1 565return public ,installer 566 567def test_the_app_installer_is_downloaded_and_its_signature_checked (self ): 568public ,installer = self .build_with_app () 569ctx = self .ctx (app_version = "0.1.0" ,environ = {** os .environ ,"STRATA_APP_UPDATE_PUBKEY" :public }) 570report = updater .check (ctx ) 571self .assertEqual ((report ["app" ]["status" ],report ["app" ]["offered" ]), ("available" ,"0.2.0" )) 572out = updater .run_update (ctx ,engine = False ,control = False ,app = True ) 573result = out ["results" ][0 ] 574self .assertEqual ((out ["exit_code" ],result ["status" ]), (0 ,"downloaded" ),out ) 575self .assertEqual (Path (result ["path" ]).read_bytes (),installer ) 576self .assertEqual ((self .release / "app" / "latest.json" ).exists (),True ,"the Tauri updater's file is written beside the feed" ) 577self .assertEqual (self .engine_folders (), [],"an app-only update downloads 0 engine bytes" ) 578self .assertEqual (self .archive_requests (), []) 579self .assertTrue (all (r [1 ].startswith (("/strata-feed" ,"/app/" ))for r in self .server .requests )) 580 581def test_an_installer_with_a_bad_signature_is_deleted (self ): 582public ,_ = self .build_with_app (tamper = True ) 583ctx = self .ctx (app_version = "0.1.0" ,environ = {** os .environ ,"STRATA_APP_UPDATE_PUBKEY" :public }) 584out = updater .run_update (ctx ,engine = False ,control = False ,app = True ) 585self .assertEqual (out ["exit_code" ],5 ) 586self .assertIn ("signature" ,out ["results" ][0 ]["error" ]) 587self .assertFalse ((self .components / ".updates" / "app" ).exists ()and any ((self .components / ".updates" / "app" ).iterdir ())) 588 589def test_no_app_key_no_app_download (self ): 590self .build_with_app () 591ctx = self .ctx (app_version = "0.1.0" ,environ = {k :v for k ,v in os .environ .items ()if k != "STRATA_APP_UPDATE_PUBKEY" }) 592with mock .patch .object (updater ,"app_public_key" ,return_value = None ): 593out = updater .run_update (ctx ,engine = False ,control = False ,app = True ) 594self .assertEqual (out ["exit_code" ],5 ) 595self .assertEqual ([r for r in self .server .requests if r [1 ].startswith ("/app/" )], []) 596 597def test_control_is_staged_run_once_and_pointed_at (self ): 598bundle = self .root / "control-bundle" 599 (bundle / "strata_control" ).mkdir (parents = True ) 600 (bundle / "strata.py" ).write_text ("print('strata 0.1.46 (python stub)')\n" ) 601 (bundle / "strata_control" / "__init__.py" ).write_text ("" ) 602from feed_tool import build_feed ,pack_control 603 (self .release / "control" ).mkdir () 604pack_control (bundle ,self .release / "control" ,version = "0.1.46" ,platform = PLATFORM ) 605build_feed (self .release ,key = self .key ,sequence = 1 ,control_dir = self .release / "control" ) 606out = updater .run_update (self .ctx (),engine = False ,control = True ) 607self .assertEqual (out ["results" ][0 ]["status" ],"updated" ,out ) 608active = updater .active_control (self .components ) 609self .assertEqual (active ["version" ],"0.1.46" ) 610self .assertTrue ((self .components / "control" / "0.1.46" / "strata.py" ).is_file ()) 611again = updater .run_update (self .ctx (),engine = False ,control = True ) 612self .assertEqual (again ["results" ][0 ]["status" ],"current" ) 613 614def test_a_control_that_cannot_run_is_not_switched_to (self ): 615bundle = self .root / "control-bad" 616bundle .mkdir () 617 (bundle / "strata.py" ).write_text ("import sys; sys.exit(9)\n" ) 618from feed_tool import build_feed ,pack_control 619 (self .release / "control" ).mkdir () 620pack_control (bundle ,self .release / "control" ,version = "0.1.46" ,platform = PLATFORM ) 621build_feed (self .release ,key = self .key ,sequence = 1 ,control_dir = self .release / "control" ) 622out = updater .run_update (self .ctx (),engine = False ,control = True ) 623self .assertEqual ((out ["exit_code" ],out ["results" ][0 ]["status" ]), (6 ,"failed" )) 624self .assertIsNone (updater .active_control (self .components )) 625self .assertFalse ((self .components / "control" / "0.1.46" ).exists ()) 626 627@ unittest . skipIf ( WINDOWS , "symbolic links need no privilege only on POSIX" ) 628def test_a_control_bundle_may_link_inside_itself_and_nowhere_else (self ): 629bundle = self .root / "control-links" 630 (bundle / "python" / "lib" ).mkdir (parents = True ) 631 (bundle / "strata.py" ).write_text ("print('strata 0.1.46 (stub)')\n" ) 632 (bundle / "python" / "lib" / "libpython3.12.so" ).write_bytes (b"lib" ) 633os .symlink ("libpython3.12.so" ,bundle / "python" / "lib" / "libpython3.so" ) 634from feed_tool import build_feed ,pack_control 635 (self .release / "control" ).mkdir () 636entry = pack_control (bundle ,self .release / "control" ,version = "0.1.46" ,platform = PLATFORM ) 637build_feed (self .release ,key = self .key ,sequence = 1 ,control_dir = self .release / "control" ) 638out = updater .run_update (self .ctx (),engine = False ,control = True ) 639self .assertEqual (out ["results" ][0 ]["status" ],"updated" ,out ) 640link = self .components / "control" / "0.1.46" / "python" / "lib" / "libpython3.so" 641self .assertTrue (link .is_symlink ()and os .readlink (link )== "libpython3.12.so" ) 642self .assertEqual (link .read_bytes (),b"lib" ) 643 644@ unittest . skipIf ( WINDOWS , "symbolic links need no privilege only on POSIX" ) 645def test_a_control_archive_with_a_link_out_of_the_package_is_refused (self ): 646import tarfile 647from feed_tool import build_feed 648 (self .release / "control" ).mkdir () 649archive = self .release / "control" / "evil.tar.gz" 650good = self .root / "strata.py" 651good .write_text ("print('strata 0.1.46')\n" ) 652for target in ("/etc/passwd" ,"../../outside" ,"a/../../../outside" ): 653with self .subTest (target = target ): 654with tarfile .open (archive ,"w:gz" )as tar : 655tar .add (good ,arcname = "strata.py" ) 656info = tarfile .TarInfo ("python/evil" ) 657info .type ,info .linkname = tarfile .SYMTYPE ,target 658tar .addfile (info ) 659data = archive .read_bytes () 660 (self .release / "control" / "evil.entry.json" ).write_text (json .dumps ({ 661"version" :"0.1.46" ,"platform" :PLATFORM ,"format" :"tar.gz" ,"url" :"control/evil.tar.gz" ,"size" :len (data ), 662"sha256" :hashlib .sha256 (data ).hexdigest (),"installed_bytes" :100 ,"entry" :"strata.py" })) 663build_feed (self .release ,key = self .key ,sequence = self .sequence + 1 ,control_dir = self .release / "control" ) 664self .sequence += 1 665out = updater .run_update (self .ctx (),engine = False ,control = True ) 666self .assertEqual (out ["exit_code" ],5 ,out ) 667self .assertRegex (out ["results" ][0 ]["error" ],"symbolic link" ) 668self .assertIsNone (updater .active_control (self .components )) 669 670 671class Cli (UpdaterCase ): 672"""`strata update`, `strata components update|rollback` against a feed in a folder, with the test key file the way the 673owner's local setup uses it (STRATA_UPDATE_TRUSTED_KEYS).""" 674 675def setUp (self ): 676super ().setUp () 677self .pub = self .root / "feed-key.pub.json" 678self .pub .write_text (json .dumps ({"keys" : [signing .public_part (self .key )]})) 679patch = mock .patch .dict (os .environ , {"STRATA_UPDATE_TRUSTED_KEYS" :str (self .pub )}) 680patch .start () 681self .addCleanup (patch .stop ) 682patch = mock .patch .object (updater ,"detect_hardware" ,return_value = dict (self .hardware )) 683patch .start () 684self .addCleanup (patch .stop ) 685patch = mock .patch .object (updater ,"serving_now" ,return_value = []) 686patch .start () 687self .addCleanup (patch .stop ) 688 689def cli (self ,* args ): 690import io 691from contextlib import redirect_stderr ,redirect_stdout 692from strata_cli .cli import main 693out ,err = io .StringIO (),io .StringIO () 694with redirect_stdout (out ),redirect_stderr (err ): 695code = main (list (args )) 696return code ,out .getvalue (),err .getvalue () 697 698def common (self ): 699return ["--feed" ,str (self .release ),"--components-dir" ,str (self .components ),"--model-config" ,str (self .config )] 700 701def test_cached_update_notice_is_dropped_when_versions_change (self ): 702self .install_current () 703self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 704self .assertEqual (self .cli ("update" ,"--check" ,* self .common ())[0 ],0 ) 705notice = "update available (engine 0.1.46): run `strata update`" 706self .assertEqual (ec .cached_notice (self .components ),notice ) 707state_file = self .components / ec .UPDATE_STATE 708saved = json .loads (state_file .read_text (encoding = "utf-8" )) 709self .assertEqual (saved ["last_check" ]["engine_installed" ],"0.1.45" ) 710# a new app brings a new Control: the old result is not shown again 711with mock .patch .object (ec ,"runtime_version" ,return_value = "9.9.9" ): 712self .assertIsNone (ec .cached_notice (self .components )) 713# the installed engine changed since the check (an update from elsewhere, a rollback) 714with mock .patch .object (ec ,"newest_installed_version" ,return_value = "0.1.44" ): 715self .assertIsNone (ec .cached_notice (self .components )) 716# an old file without the recorded versions: still never offers an engine that is not newer 717saved ["last_check" ]= {"at" :"x" ,"engine" :"0.1.45" ,"app" :None } 718state_file .write_text (json .dumps (saved ),encoding = "utf-8" ) 719self .assertIsNone (ec .cached_notice (self .components )) 720saved ["last_check" ]= {"at" :"x" ,"engine" :"0.1.46" ,"app" :None } 721state_file .write_text (json .dumps (saved ),encoding = "utf-8" ) 722self .assertEqual (ec .cached_notice (self .components ),notice ) 723 724def test_check_update_and_rollback_from_the_terminal (self ): 725self .install_current () 726self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 727code ,text ,_ = self .cli ("update" ,"--check" ,* self .common ()) 728self .assertEqual (code ,0 ) 729self .assertIn ("update available: 0.1.45 -> 0.1.46" ,text ) 730self .assertEqual (ec .cached_notice (self .components ),"update available (engine 0.1.46): run `strata update`" ) 731code ,listing ,_ = self .cli ("components" ,"engine" ,"--components-dir" ,str (self .components )) 732self .assertIn ("update available (engine 0.1.46): run `strata update`" ,listing ) 733code ,text ,_ = self .cli ("update" ,"--check" ,"--json" ,* self .common ()) 734self .assertEqual ((code ,json .loads (text )["engine" ]["status" ]), (0 ,"available" )) 735code ,text ,_ = self .cli ("update" ,* self .common ()) 736self .assertEqual (code ,0 ,text ) 737self .assertIn ("0.1.45 -> 0.1.46 updated (tested: started, answered one token, stopped)" ,text ) 738self .assertIn ("Saved tuning presets: marked for the short re-check (nothing was deleted)." ,text ) 739self .assertIn ("strata components rollback" ,text ) 740self .assertEqual (self .resolved (),"0.1.46" ) 741self .assertIsNone (ec .cached_notice (self .components )) 742code ,text ,_ = self .cli ("update" ,* self .common ()) 743self .assertEqual (code ,0 ) 744self .assertIn ("up to date" ,text ) 745code ,text ,_ = self .cli ("components" ,"rollback" ,* self .common ()) 746self .assertEqual (code ,0 ,text ) 747self .assertIn ("Engine rolled back: 0.1.46 -> 0.1.45" ,text ) 748self .assertEqual (self .resolved (),"0.1.45" ) 749code ,out ,_ = self .cli ("components" ,"rollback" ,"--json" ,* self .common ()) 750self .assertEqual (code ,0 ) 751self .assertEqual (json .loads (out )["to" ],"0.1.46" ,"rolling back twice goes forward again" ) 752self .assertEqual (json .loads (out )["status" ],"rolled-forward" ,"and it says so" ) 753self .assertEqual (updater .State (self .components ).section ("engine" ).get ("skipped" )or [], [],"the newer engine is no longer one that was left" ) 754code ,text ,_ = self .cli ("components" ,"rollback" ,* self .common ())# back to 0.1.45 once more 755self .assertIn ("Engine rolled back: 0.1.46 -> 0.1.45" ,text ) 756code ,text ,_ = self .cli ("update" ,"--check" ,* self .common ()) 757self .assertIn ("update available: 0.1.45 -> 0.1.46 (already installed; the update switches to it, nothing to download)" ,text ) 758code ,text ,_ = self .cli ("components" ,"rollback" ,* self .common ()) 759self .assertIn ("Engine moved to the newer version: 0.1.45 -> 0.1.46" ,text ) 760self .assertNotIn ("rolled back" ,text ) 761 762def test_a_first_install_does_not_claim_a_previous_engine_is_kept (self ): 763self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 764code ,text ,_ = self .cli ("update" ,* self .common ()) 765self .assertEqual (code ,0 ,text ) 766self .assertNotIn ("previous engine version is kept" ,text ) 767 768def test_a_failed_test_start_exits_6_and_says_the_old_engine_is_unchanged (self ): 769self .install_current () 770self .publish (("0.1.47" ,fx .BAD_ENGINE )) 771code ,text ,err = self .cli ("update" ,* self .common ()) 772self .assertEqual (code ,6 ,text + err ) 773self .assertIn ("NOT changed" ,text ) 774self .assertIn ("unchanged" ,text ) 775self .assertEqual (self .resolved (),"0.1.45" ) 776 777def test_jsonl_streams_progress_and_ends_with_the_result (self ): 778self .install_current () 779self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 780code ,text ,_ = self .cli ("update" ,"--output" ,"jsonl" ,* self .common ()) 781records = [json .loads (line )for line in text .splitlines ()] 782self .assertEqual (code ,0 ) 783self .assertTrue (any (r .get ("event" )== "progress" and r ["percent" ]== 100 for r in records )) 784self .assertTrue (records [- 1 ]["ok" ]and records [- 1 ]["results" ][0 ]["status" ]== "updated" ) 785 786def test_an_untrusted_or_forbidden_update_is_exit_5_and_fetches_nothing (self ): 787self .install_current () 788self .publish (("0.1.46" ,fx .GOOD_ENGINE )) 789with mock .patch .dict (os .environ , {"STRATA_UPDATE_TRUSTED_KEYS" :"" }): 790code ,_ ,err = self .cli ("update" ,* self .common ()) 791self .assertEqual (code ,5 ) 792self .assertIn ("trusts no update key" ,err ) 793wrong = self .root / "wrong.json" 794wrong .write_text (json .dumps ({"keys" : [signing .public_part (fx .make_key ())]})) 795with mock .patch .dict (os .environ , {"STRATA_UPDATE_TRUSTED_KEYS" :str (wrong )}): 796code ,_ ,err = self .cli ("update" ,* self .common ()) 797self .assertEqual (code ,5 ) 798self .assertIn ("does not trust" ,err ) 799with mock .patch .dict (os .environ , {"STRATA_NO_ACQUIRE" :"1" }): 800code ,_ ,err = self .cli ("update" ,* self .common ()) 801self .assertEqual (code ,5 ) 802self .assertIn ("STRATA_NO_ACQUIRE" ,err ) 803self .assertEqual (self .resolved (),"0.1.45" ) 804self .assertEqual (self .archive_requests (), []) 805 806 807class AnotherCardFamilyNote (unittest .TestCase ): 808"""A feed whose only HIP engine is built for another AMD card family says so in one plain line.""" 809 810def test_the_note_names_both_families_and_the_build_to_ask_for (self ): 811import tempfile 812from types import SimpleNamespace 813pkg = SimpleNamespace (label = "0.1.45.1 linux-x86_64-hip-rx7900" ,platform = "linux-x86_64" ,backend = "hip" ,min_runtime = None , 814archs = ("gfx1100" ,"gfx1101" ,"gfx1102" ),min_driver = {}) 815hardware = {"platform" :"linux-x86_64" ,"backend" :"hip" ,"runtime" :None ,"gfx" : ["gfx1201" ],"cuda_archs" : [],"nvidia_driver" :None } 816with tempfile .TemporaryDirectory ()as d : 817ctx = SimpleNamespace (components = Path (d ),hardware = hardware ) 818report ,offered = updater ._choose_engine (SimpleNamespace (engine = [pkg ]),ctx ,SimpleNamespace (section = lambda name : {})) 819self .assertIsNone (offered ) 820self .assertEqual (report ["status" ],"none-for-this-pc" ) 821self .assertEqual (report ["note" ],"This build of Strata is for AMD RX 7000 cards. This computer has an AMD RX 9000 card (gfx1201). Ask for the RX 9000 build." ) 822 823 824class FailedStartRecords (LazyModel ): 825"""#3654: a failed test start used to leave only the last 64 KiB of the engine log, because the sandbox that held the host, child and 826ready records was deleted at once. The records are kept (without tokens or keys) next to the log.""" 827 828def failing_start (self ): 829def start (name ,** kw ): 830runtime_dir = Path (os .environ ["STRATA_RUNTIME_DIR" ])# the sandbox's, set by default_test_start 831runtime_dir .mkdir (parents = True ,exist_ok = True ) 832 (runtime_dir / f" { name } .json" ).write_text (json .dumps ({"pid" :4321 ,"token" :"a1b2c3d4" * 8 ,"state" :"starting" }),encoding = "utf-8" ) 833 (runtime_dir / f" { name } - { 'a1b2c3d4' * 8 } .child.json" ).write_text (json .dumps ({"host_token" :"a1b2c3d4" * 8 ,"child_pid" :111 }),encoding = "utf-8" ) 834 (runtime_dir / f" { name } -9f.ready.json" ).write_text (json .dumps ({"pid" :222 ,"api_key" :"sekret-key" }),encoding = "utf-8" ) 835 (runtime_dir / f" { name } .server.log" ).write_text ("server: model loaded\nserver: pid 222\n" ,encoding = "utf-8" ) 836 (runtime_dir / f" { name } .host.log" ).write_text ("" ,encoding = "utf-8" ) 837return {"ok" :False ,"state" :"starting" ,"error" :"startup_wait_expired" ,"phase" :"ready_file_not_matched" } 838return start 839 840def test_the_runtime_records_of_a_failed_start_are_kept_without_tokens_or_keys (self ): 841from strata_control import runtime 842self .install_current () 843folder = fx .build_package (self .root / "lazy" ,"0.1.46" ,key = self .key ) 844stage = self .root / "stage" 845 (stage / "engine" ).mkdir (parents = True ) 846shutil .copytree (folder ,stage / "engine" / folder .name ) 847component = ec .read_manifest (stage / "engine" / folder .name ) 848self .config .write_text (json .dumps ({** json .loads (self .config .read_text ()),"api_key" :"sekret-key" }),encoding = "utf-8" ) 849with mock .patch .object (runtime ,"start" ,side_effect = self .failing_start ()),mock .patch .object (runtime ,"stop" ,return_value = {}): 850with self .assertRaises (updater .TestStartFailed ): 851updater .default_test_start (stage ,component ,self .ctx ()) 852kept = updater .updates_dir (self .components )/ "logs" / f"test-start- { component . version } -failed" 853names = sorted (p .name for p in kept .iterdir ()) 854self .assertIn ("run.json" ,names ) 855self .assertTrue (any (n .endswith (".child.json" )for n in names ),names ) 856self .assertTrue (any (n .endswith (".ready.json" )for n in names ),names ) 857self .assertIn ("updtest.server.log" ,names ) 858text = "" .join (p .read_text (encoding = "utf-8" )for p in kept .iterdir ()) 859self .assertNotIn ("sekret-key" ,text ) 860self .assertNotIn ("a1b2c3d4a1b2c3d4" ,text ,"no full token is kept" ) 861self .assertIn ('"child_pid": 111' ,text )# the PIDs that show a mismatch are 862self .assertIn ("server: pid 222" ,text ) 863self .assertFalse ((self .components / ".updates" ).exists ()and any (p .name .startswith ("t-" )for p in (self .components / ".updates" ).rglob ("*" )if p .is_dir ()), 864"the sandbox itself is still removed" ) 865 866def test_only_the_last_few_failed_starts_are_kept (self ): 867logs = updater .updates_dir (self .components )/ "logs" 868for i in range (5 ): 869folder = logs / f"test-start-0.1.4 { i } -failed" 870folder .mkdir (parents = True ) 871 (folder / "run.json" ).write_text ("{}" ,encoding = "utf-8" ) 872os .utime (folder , (1_700_000_000 + i ,1_700_000_000 + i )) 873from types import SimpleNamespace 874sandbox = self .root / "sandbox" 875sandbox .mkdir () 876 (sandbox / "run.json" ).write_text ("{}" ,encoding = "utf-8" ) 877updater ._keep_records (sandbox ,SimpleNamespace (version = "0.1.49" ),self .ctx ()) 878left = sorted (p .name for p in logs .glob ("test-start-*-failed" )) 879self .assertEqual (len (left ),3 ,left ) 880self .assertIn ("test-start-0.1.49-failed" ,left ) 881 882 883class GoneVersionPathsInTheTestStart (UpdaterCase ): 884"""#5681: a run config that names files in a Control version an update removed (cwd, --expert-profile under components/control/0.1.56) 885is resolved to the current Control before the test start runs with the stage as its components folder (which has no control folder).""" 886 887def test_the_test_start_gets_the_current_control_paths (self ): 888from strata_control import profiles ,runtime 889self .install_current () 890current = self .components / "control" / "0.1.60" 891 (current / "data" ).mkdir (parents = True ) 892 (current / "data" / "expert-profile.bin" ).write_bytes (b"p" ) 893 (self .components / "control" / "active.json" ).write_text (json .dumps ({"folder" :"0.1.60" }),encoding = "utf-8" ) 894gone = self .components / "control" / "0.1.56" 895cfg = json .loads (self .config .read_text ()) 896cfg .update ({"cwd" :str (gone ),"args" : ["--max-context" ,"4096" ,"--expert-profile" ,str (gone / "data" / "expert-profile.bin" )]}) 897self .config .write_text (json .dumps (cfg ),encoding = "utf-8" ) 898folder = fx .build_package (self .root / "lazy" ,"0.1.46" ,key = self .key ) 899stage = self .root / "stage" 900 (stage / "engine" ).mkdir (parents = True ) 901shutil .copytree (folder ,stage / "engine" / folder .name ) 902component = ec .read_manifest (stage / "engine" / folder .name ) 903seen = [] 904 905def start (name ,** kw ): 906profile ,_ = profiles .load (name ) 907seen .append (json .loads (Path (profile ["source_config" ]).read_text (encoding = "utf-8" ))) 908return {"ok" :True ,"state" :"ready" ,"generation_ready" :True } 909 910with mock .patch .object (runtime ,"start" ,side_effect = start ),mock .patch .object (runtime ,"stop" ,return_value = {}): 911result = updater .default_test_start (stage ,component ,self .ctx ()) 912self .assertEqual (result ["generation_ready" ],True ) 913self .assertEqual (len (seen ),1 ) 914self .assertEqual (seen [0 ]["cwd" ],str (current )) 915self .assertEqual (seen [0 ]["args" ][seen [0 ]["args" ].index ("--expert-profile" )+ 1 ],str (current / "data" / "expert-profile.bin" )) 916self .assertEqual (json .loads (self .config .read_text ())["cwd" ],str (gone ),"the person's run config is not written by a test start" ) 917 918 919if __name__ == "__main__" : 920unittest .main ()