okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""An engine update beside a loaded model (owner, 11-01: "it updated the engine by itself mid-session and he had a model loaded"). 2 3The rule under test: an update never starts by itself while a model is loaded; nothing replaces or removes the engine a running model uses; the 4update is the person's choice: warn naming the model, download while it keeps serving, stop it cleanly, update, ask whether to start it again with the 5same settings; a failed update leaves the old engine in use and the model can be started again; a script is never asked anything. 6 7Real pieces: the owner runtime starts and stops a real (stub) engine from the installed package, so "serving", "stopped" and "serving again on the new 8engine" are read from the runtime and from the file the stub engine writes when it starts. Only the questions are scripted. 9""" 10from __future__import annotations 11 12import argparse 13import contextlib 14import io 15import json 16import os 17import shutil 18import socket 19import sys 20import threading 21import time 22import unittest 23from pathlib import Path 24from unittest import mock 25 26sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [2 ])) 27from strata_cli import update_cmd # noqa: E402 28from strata_control import engine_component as ec ,engine_update ,profiles ,runtime ,updater # noqa: E402 29from tests .terminal import update_fixture as fx # noqa: E402 30from tests .terminal .test_updater import PLATFORM ,UpdaterCase # noqa: E402 31 32PROFILE = "launch-demo" 33NAME = "Demo model" 34 35 36class Script : 37"""The person at the keyboard: answers in order, remembers every question.""" 38 39def __init__ (self ,* answers ): 40self .answers ,self .asked = list (answers ), [] 41 42def __call__ (self ,question ,default ): 43self .asked .append ((question ,default )) 44return self .answers .pop (0 )if self .answers else default 45 46 47def free_port ()-> int : 48with socket .socket ()as s : 49s .bind (("127.0.0.1" ,0 )) 50return s .getsockname ()[1 ] 51 52 53class ModelCase (UpdaterCase ): 54def setUp (self ): 55super ().setUp () 56self .install_current ("0.1.45" ) 57self .lines :list [str ]= [] 58self .events :list [dict ]= [] 59 60# ------------------------------------------------------------------ a real loaded model 61def start_model (self ,profile = PROFILE ,name = NAME ,port = None ): 62cfg = json .loads (self .config .read_text ()) 63cfg .update (exe = ec .REFERENCE_PREFIX + ec .COMPONENT_ID ,backend = "cuda" ,host = "127.0.0.1" ,port = port or free_port (),model_name = name , 64log = str (self .root / f" { profile } .engine.log" )) 65cfg .pop ("lib_dirs" ,None ) 66path = self .root / f"run- { profile } .json" 67path .write_text (json .dumps (cfg )) 68profiles .create (profile ,str (path )) 69got = runtime .start (profile ,wait = 60 ) 70self .assertTrue (got .get ("ok" ),got ) 71self .addCleanup (self ._stop ,profile ) 72return profile 73 74def _stop (self ,profile ): 75try : 76runtime .stop (profile ,timeout = 20 ) 77except Exception :# noqa: BLE001 78pass 79 80def state (self ,profile = PROFILE ): 81return runtime .status (profile ).get ("state" ) 82 83def engine_of_last_start (self ): 84"""Which engine folder the stub engine ran from the last time it started.""" 85return Path ((self .root / "ran.txt" ).read_text ().splitlines ()[0 ]).parent .name 86 87# ------------------------------------------------------------------ the update 88def gate (self ,* answers ,** flags ): 89self .script = Script (* answers ) 90ask = None if flags .pop ("nobody" ,False )else self .script 91return engine_update .ModelGate (ask = ask ,say = self .lines .append ,emit = self .events .append ,** flags ) 92 93def update (self ,gate ,** over ): 94over .setdefault ("serving" ,updater .serving_now ) 95ctx = self .ctx (events = self .events ,** over ) 96return engine_update .update_with_models (ctx ,gate ,control = False ) 97 98def publish_new (self ,version = "0.1.46" ,source = None ): 99self .publish ((version ,source or fx .GOOD_ENGINE )) 100 101def said (self ): 102return " " .join (self .lines ) 103 104 105class WithAModel (ModelCase ): 106def setUp (self ): 107super ().setUp () 108self .start_model () 109self .publish_new () 110 111# ---- yes, then start it again 112def test_yes_and_start_again_stops_after_the_download_updates_and_starts_the_same_model_on_the_new_engine (self ): 113archives_when_stopped = [] 114real_stop = engine_update .stop_model 115 116def stop (model ): 117archives_when_stopped .append (len (self .archive_requests ())) 118real_stop (model ) 119gate = self .gate (True ,True ) 120gate ._stop = stop 121out = self .update (gate ) 122self .assertEqual ((out ["exit_code" ],out ["results" ][0 ]["status" ]), (0 ,"updated" ),out ) 123self .assertEqual (archives_when_stopped , [1 ],"the new engine was downloaded while the model kept serving; it was stopped after" ) 124self .assertEqual (self .state (),"ready" ,"the model is serving again" ) 125self .assertEqual (self .resolved (),"0.1.46" ) 126self .assertEqual (self .engine_of_last_start (),f"0.1.46- { PLATFORM } -cuda-cuda13" ,"the restarted model runs on the NEW engine" ) 127# the warning came first, named the model, and said what would happen 128first ,second = self .script .asked 129self .assertIn (NAME ,first [0 ]) 130self .assertFalse (first [1 ],"stopping a model is never the default answer" ) 131self .assertIn (NAME ,second [0 ]) 132self .assertIn ("same settings" ,second [0 ]) 133self .assertTrue (second [1 ]) 134self .assertIn (NAME ,self .said ()) 135self .assertIn ("keeps serving" ,self .said ()) 136phases = [e .get ("phase" )for e in self .events if e .get ("event" )== "models" ] 137self .assertEqual (phases , ["consent" ,"stopping" ,"stopped" ,"restarting" ,"restarted" ]) 138self .assertEqual (out ["models" ]["restarts" ][0 ]["restarted" ],True ) 139self .assert_user_data_untouched () 140 141def test_the_old_engine_stays_installed_and_the_restart_uses_the_saved_settings_untouched (self ): 142before = (profiles .load (PROFILE )[0 ],Path (profiles .load (PROFILE )[0 ]["source_config" ]).read_bytes ()) 143self .update (self .gate (True ,True )) 144after = (profiles .load (PROFILE )[0 ],Path (profiles .load (PROFILE )[0 ]["source_config" ]).read_bytes ()) 145self .assertEqual (before ,after ,"the model's profile and run config are exactly what they were" ) 146self .assertEqual (self .engine_folders (), [f"0.1.45- { PLATFORM } -cuda-cuda13" ,f"0.1.46- { PLATFORM } -cuda-cuda13" ]) 147 148# ---- yes, but do not start it again 149def test_yes_and_no_to_start_again_leaves_it_stopped_and_says_how_to_start_it (self ): 150out = self .update (self .gate (True ,False )) 151self .assertEqual (out ["exit_code" ],0 ) 152self .assertEqual (self .state (),"stopped" ) 153self .assertEqual (self .resolved (),"0.1.46" ) 154self .assertIn ("is stopped. Start it when you want with" ,self .said ()) 155self .assertEqual (out ["models" ]["restarts" ][0 ]["restarted" ],False ) 156self .assertEqual ([e ["phase" ]for e in self .events if e .get ("event" )== "models" ][- 1 ],"left-stopped" ) 157 158# ---- no 159def test_no_changes_nothing_downloads_nothing_and_the_model_keeps_serving (self ): 160with self .assertRaises (engine_update .Declined )as caught : 161self .update (self .gate (False )) 162self .assertEqual (caught .exception .exit_code ,0 ) 163self .assertEqual (self .state (),"ready" ) 164self .assertEqual (self .resolved (),"0.1.45" ) 165self .assertEqual (self .archive_requests (), [],"nothing was downloaded" ) 166self .assertEqual (len (self .script .asked ),1 ) 167 168# ---- the update fails 169def test_a_new_engine_that_will_not_start_leaves_the_old_one_in_use_and_the_model_can_be_started_again (self ): 170self .publish_new (source = fx .BAD_ENGINE ) 171out = self .update (self .gate (True ,True )) 172self .assertEqual (out ["exit_code" ],6 ,out ) 173self .assertEqual (out ["results" ][0 ]["status" ],"failed" ) 174self .assertEqual (self .resolved (),"0.1.45" ,"the old engine is still the one in use" ) 175self .assertEqual (self .engine_folders (), [f"0.1.45- { PLATFORM } -cuda-cuda13" ],"the engine that failed is not installed" ) 176self .assertEqual (self .state (),"ready" ,"the model was started again on the old engine" ) 177self .assertEqual (self .engine_of_last_start (),f"0.1.45- { PLATFORM } -cuda-cuda13" ) 178question = self .script .asked [1 ][0 ] 179self .assertIn ("old engine is unchanged" ,question ) 180self .assertIn (NAME ,question ) 181 182def test_a_failed_update_and_no_to_start_again_leaves_the_model_stopped_with_the_old_engine (self ): 183self .publish_new (source = fx .BAD_ENGINE ) 184out = self .update (self .gate (True ,False )) 185self .assertEqual (out ["exit_code" ],6 ) 186self .assertEqual (self .state (),"stopped" ) 187self .assertEqual (self .resolved (),"0.1.45" ) 188 189def test_a_download_that_fails_never_stops_the_model (self ): 190 (next ((self .release / "engine" ).glob ("*.tar.gz" ))).unlink ()# the server answers 404 for the archive (a cut connection is resumed in the same run now) 191out = self .update (self .gate (True ,True )) 192self .assertEqual (out ["exit_code" ],6 ,out ) 193self .assertEqual (self .state (),"ready" ,"the model was not stopped for a download that failed" ) 194self .assertEqual (self .resolved (),"0.1.45" ) 195self .assertEqual (out ["models" ]["stopped" ], []) 196self .assertEqual (len (self .script .asked ),1 ,"no 'start it again' question: it was never stopped" ) 197 198# ---- the model does not start again 199def test_a_model_that_does_not_start_again_is_said_plainly_and_the_exit_code_is_8 (self ): 200gate = self .gate (True ,True ) 201real_stop = engine_update .stop_model 202 203def stop_and_break (model ): 204real_stop (model ) 205Path (profiles .load (PROFILE )[0 ]["source_config" ]).write_text ("{ not a run config" )# whatever would stop it starting 206gate ._stop = stop_and_break 207out = self .update (gate ) 208self .assertEqual (out ["exit_code" ],engine_update .EXIT_NOT_RESTARTED ,out ) 209self .assertEqual (out ["results" ][0 ]["status" ],"updated" ,"the update itself is done and stays" ) 210self .assertEqual (self .resolved (),"0.1.46" ) 211self .assertIn ("did not start again" ,self .said ()) 212self .assertEqual (self .state (),"stopped" ,"nothing is left half alive" ) 213self .assertEqual ([r ["restarted" ]for r in out ["models" ]["restarts" ]], [False ]) 214 215# ---- nobody can be asked 216def test_a_script_is_never_asked_and_nothing_is_downloaded_or_changed (self ): 217with self .assertRaises (updater .UpdateError )as caught : 218self .update (self .gate (nobody = True )) 219self .assertEqual (caught .exception .exit_code ,7 ) 220text = str (caught .exception ) 221self .assertIn (NAME ,text ) 222self .assertIn ("--stop-model" ,text ) 223self .assertIn ("strata launch --stop" ,text ) 224self .assertIn ("nothing was changed" ,text ) 225self .assertEqual (self .archive_requests (), []) 226self .assertEqual ((self .state (),self .resolved ()), ("ready" ,"0.1.45" )) 227 228def test_stop_model_stops_updates_and_leaves_it_stopped_when_start_again_is_not_given (self ): 229out = self .update (self .gate (nobody = True ,allow_stop = True )) 230self .assertEqual (out ["exit_code" ],0 ) 231self .assertEqual ((self .state (),self .resolved ()), ("stopped" ,"0.1.46" )) 232self .assertIn ("Start it when you want with" ,self .said ()) 233 234def test_stop_model_and_start_again_in_a_script_do_it_all_without_a_question (self ): 235gate = self .gate (nobody = True ,allow_stop = True ,start_again = True ) 236out = self .update (gate ) 237self .assertEqual (out ["exit_code" ],0 ) 238self .assertEqual (self .state (),"ready" ) 239self .assertEqual (self .engine_of_last_start (),f"0.1.46- { PLATFORM } -cuda-cuda13" ) 240self .assertEqual (self .script .asked , []) 241 242def test_start_again_after_a_failed_update_puts_the_model_back_on_the_old_engine (self ): 243self .publish_new (source = fx .BAD_ENGINE ) 244out = self .update (self .gate (nobody = True ,allow_stop = True ,start_again = True )) 245self .assertEqual (out ["exit_code" ],6 ) 246self .assertEqual ((self .state (),self .resolved ()), ("ready" ,"0.1.45" )) 247 248# ---- a server nobody here started (a service) 249def test_a_server_that_strata_did_not_start_is_never_stopped_even_with_stop_model (self ): 250with self .assertRaises (updater .UpdateError )as caught : 251self .update (self .gate (nobody = True ,allow_stop = True ),serving = lambda : [{"profile" :"a running Strata server" ,"state" :"serving" }]) 252self .assertEqual (caught .exception .exit_code ,7 ) 253self .assertIn ("did not start it from here" ,str (caught .exception )) 254self .assertIn ("Stop it yourself" ,str (caught .exception )) 255self .assertEqual (self .archive_requests (), []) 256self .assertEqual (self .state (),"ready" ) 257 258# ---- offline and a feed that does not answer 259def test_an_unreachable_feed_is_said_before_anything_is_stopped (self ): 260for dead in ("http://127.0.0.1:9/strata-feed.json" ,str (self .root / "no-such-feed" )): 261with self .assertRaises (Exception )as caught : 262self .update (self .gate (True ,True ),source = dead ) 263self .assertTrue ("could not be read" in str (caught .exception )or "so the update check could not run" in str (caught .exception ), 264str (caught .exception ))# a folder that is gone: the old sentence; a host nobody answers for: the network rule's (W7) 265self .assertEqual (self .state (),"ready" ,dead ) 266self .assertEqual (self .resolved (),"0.1.45" ) 267 268def test_a_feed_that_never_answers_gives_up_and_leaves_the_model_alone (self ): 269hang = socket .socket () 270hang .bind (("127.0.0.1" ,0 )) 271hang .listen (5 ) 272self .addCleanup (hang .close ) 273started = time .monotonic () 274with self .assertRaises (Exception )as caught : 275self .update (self .gate (True ,True ),source = f"http://127.0.0.1: { hang . getsockname ()[ 1 ] } /strata-feed.json" ,feed_timeout = 1.0 ) 276self .assertLess (time .monotonic ()- started ,20 ) 277self .assertIn ("did not answer within" ,str (caught .exception ))# the network rule (W7): the host, and that nothing was changed 278self .assertIn ("so the update check could not run" ,str (caught .exception )) 279self .assertEqual ((self .state (),self .resolved ()), ("ready" ,"0.1.45" )) 280 281def test_nothing_to_update_asks_nothing_and_leaves_the_model_alone (self ): 282self .publish ((("0.1.45" ,fx .GOOD_ENGINE ))) 283out = self .update (self .gate (True ,True )) 284self .assertEqual ((out ["exit_code" ],out ["results" ][0 ]["status" ]), (0 ,"current" )) 285self .assertEqual (self .script .asked , []) 286self .assertEqual (self .state (),"ready" ) 287 288 289class StartedDuringTheUpdate (ModelCase ): 290"""A model started after the person said yes is a different model: nobody agreed to stop it.""" 291 292def setUp (self ): 293super ().setUp () 294self .start_model () 295self .publish_new () 296 297def run_update (self ,gate ): 298"""Runs the update; a second model is started as soon as the download is done (before the engine is put in place).""" 299real = updater ._download 300 301def download (* args ,** kwargs ): 302got = real (* args ,** kwargs ) 303self .start_model ("launch-second" ,"Second model" ) 304return got 305ctx = self .ctx (serving = updater .serving_now ,events = self .events ) 306with mock .patch .object (updater ,"_download" ,download ): 307return engine_update .update_with_models (ctx ,gate ,control = False ) 308 309def test_in_a_script_the_new_model_is_refused_and_nothing_more_is_changed (self ): 310out = self .run_update (self .gate (nobody = True ,allow_stop = True ,start_again = True )) 311self .assertEqual (out ["exit_code" ],7 ) 312self .assertEqual (out ["results" ][0 ]["status" ],"failed" ) 313self .assertIn ("Second model" ,out ["results" ][0 ]["error" ]) 314self .assertIn ("started while the update was running" ,out ["results" ][0 ]["error" ]) 315self .assertIn ("the download is kept" ,out ["results" ][0 ]["error" ]) 316self .assertEqual (self .resolved (),"0.1.45" ) 317self .assertEqual (self .state ("launch-second" ),"ready" ,"the model nobody agreed to stop was not stopped" ) 318self .assertEqual (self .state (PROFILE ),"ready" ,"nothing was stopped at all" ) 319 320def test_at_the_keyboard_the_person_is_asked_again_and_both_come_back (self ): 321out = self .run_update (self .gate (True ,True ,True ,True )) 322self .assertEqual (out ["exit_code" ],0 ,out ) 323self .assertEqual (self .resolved (),"0.1.46" ) 324self .assertEqual ((self .state (PROFILE ),self .state ("launch-second" )), ("ready" ,"ready" )) 325self .assertTrue (any ("Second model" in q for q ,_ in self .script .asked )) 326 327def test_at_the_keyboard_no_to_the_new_model_changes_nothing_more (self ): 328out = self .run_update (self .gate (True ,False )) 329self .assertEqual (out ["exit_code" ],7 ) 330self .assertEqual (self .resolved (),"0.1.45" ) 331self .assertEqual ((self .state ("launch-second" ),self .state (PROFILE )), ("ready" ,"ready" ),"nothing was stopped" ) 332 333 334class TwoTerminals (ModelCase ): 335def setUp (self ): 336super ().setUp () 337self .start_model () 338self .publish_new () 339 340def test_a_second_update_while_the_first_runs_is_refused_and_stops_nothing (self ): 341with updater .update_lock (self .components ): 342with self .assertRaises (updater .UpdateError )as caught : 343self .update (self .gate (True ,True )) 344self .assertEqual (caught .exception .exit_code ,7 ) 345self .assertIn ("another update is already running" ,str (caught .exception )) 346self .assertEqual ((self .state (),self .resolved ()), ("ready" ,"0.1.45" )) 347self .assertEqual (self .script .asked , [],"the model was not even asked about: the lock comes first" ) 348 349def test_two_updates_at_once_stop_the_model_once_and_start_it_once (self ): 350results = [] 351 352def go (): 353try : 354results .append (("ok" ,self .update (self .gate (True ,True ))["exit_code" ])) 355except updater .UpdateError as exc : 356results .append (("refused" ,exc .exit_code )) 357threads = [threading .Thread (target = go )for _ in range (2 )] 358for t in threads : 359t .start () 360for t in threads : 361t .join (180 ) 362self .assertEqual (sorted (results ), [("ok" ,0 ), ("refused" ,7 )],results ) 363self .assertEqual ((self .state (),self .resolved ()), ("ready" ,"0.1.46" )) 364 365 366class WithoutAGate (ModelCase ): 367"""Anything that runs the update without the questions (the app's button today, a library caller) is refused BEFORE a download, whole.""" 368 369def setUp (self ): 370super ().setUp () 371self .start_model () 372 373def bundle (self ): 374folder = self .root / "control-bundle" 375 (folder / "strata_control" ).mkdir (parents = True ) 376 (folder / "strata.py" ).write_text ("print('strata 0.1.46 (python stub)')\n" ) 377 (folder / "strata_control" / "__init__.py" ).write_text ("" ) 378from feed_tool import build_feed ,pack_control 379 (self .release / "control" ).mkdir () 380pack_control (folder ,self .release / "control" ,version = "0.1.46" ,platform = PLATFORM ) 381build_feed (self .release ,key = self .key ,sequence = self .sequence + 1 ,engine_dir = self .release / "engine" ,control_dir = self .release / "control" ) 382 383def test_engine_and_control_are_both_left_alone_and_nothing_is_downloaded (self ): 384self .publish_new () 385self .bundle () 386with self .assertRaises (updater .Busy )as caught : 387updater .run_update (self .ctx (serving = updater .serving_now )) 388self .assertEqual (caught .exception .exit_code ,7 ) 389self .assertEqual (self .archive_requests (), [],"no download beside a loaded model" ) 390self .assertIsNone (updater .active_control (self .components ),"Control did not move on while the engine was refused" ) 391self .assertEqual ((self .state (),self .resolved ()), ("ready" ,"0.1.45" )) 392 393def test_nothing_to_install_is_not_a_busy_error (self ): 394self .publish ((("0.1.45" ,fx .GOOD_ENGINE ))) 395out = updater .run_update (self .ctx (serving = updater .serving_now ),control = False ) 396self .assertEqual (out ["exit_code" ],0 ) 397 398def test_wait_lets_the_model_finish_first (self ): 399self .publish_new () 400answers = [[{"profile" :PROFILE }], [{"profile" :PROFILE }], [], [], []] 401out = updater .run_update (self .ctx (serving = lambda :answers .pop (0 )if answers else [],wait = 30 ),control = False ) 402self .assertEqual (out ["results" ][0 ]["status" ],"updated" ) 403 404 405class TheCommand (ModelCase ): 406"""`strata update` as a person or a script runs it.""" 407 408def setUp (self ): 409super ().setUp () 410self .start_model () 411self .publish_new () 412sp = argparse .ArgumentParser ().add_subparsers (dest = "command" ) 413comp = sp .add_parser ("components" ).add_subparsers (dest = "components_command" ) 414update_cmd .add_parsers (sp ,comp ) 415self .parser = sp 416 417def run_cmd (self ,* flags ,asks = None ): 418argv = ["update" ,"--feed" ,self .server .url + "/strata-feed.json" ,"--components-dir" ,str (self .components ),"--no-control" , 419"--model-config" ,str (self .config ),* flags ] 420a = self .parser .choices ["update" ].parse_args (argv [1 :]) 421a .command ,a .components_command = "update" ,None 422out ,err = io .StringIO (),io .StringIO () 423with mock .patch .object (update_cmd ,"_ask_factory" ,return_value = asks ),contextlib .redirect_stdout (out ),contextlib .redirect_stderr (err ): 424code = update_cmd .run (a ) 425return code ,out .getvalue (),err .getvalue () 426 427def test_yes_alone_never_stops_a_model (self ): 428code ,out ,err = self .run_cmd ("--yes" ) 429self .assertEqual (code ,7 ) 430self .assertIn (NAME ,err ) 431self .assertIn ("--stop-model" ,err ) 432self .assertEqual ((self .state (),self .resolved ()), ("ready" ,"0.1.45" )) 433self .assertEqual (self .archive_requests (), []) 434 435def test_stop_model_and_start_again (self ): 436code ,out ,err = self .run_cmd ("--yes" ,"--stop-model" ,"--start-again" ) 437self .assertEqual (code ,0 , (out ,err )) 438self .assertIn ("Engine" ,out ) 439self .assertIn ("serving again with the same settings" ,out ) 440self .assertEqual ((self .state (),self .resolved ()), ("ready" ,"0.1.46" )) 441 442def test_stop_model_alone_leaves_it_stopped_and_prints_the_start_line (self ): 443code ,out ,err = self .run_cmd ("--yes" ,"--stop-model" ) 444self .assertEqual (code ,0 , (out ,err )) 445self .assertIn ("is stopped. Start it when you want with" ,out ) 446self .assertEqual (self .state (),"stopped" ) 447 448def test_the_questions_in_a_terminal (self ): 449asks = Script (True ,True ) 450code ,out ,err = self .run_cmd (asks = asks ) 451self .assertEqual (code ,0 , (out ,err )) 452self .assertEqual (len (asks .asked ),2 ) 453self .assertEqual ((self .state (),self .resolved ()), ("ready" ,"0.1.46" )) 454 455def test_no_in_a_terminal_exits_0_and_says_nothing_was_changed (self ): 456code ,out ,err = self .run_cmd (asks = Script (False )) 457self .assertEqual (code ,0 ) 458self .assertIn ("Nothing was changed" ,out ) 459self .assertEqual ((self .state (),self .resolved ()), ("ready" ,"0.1.45" )) 460 461def test_the_exit_code_when_a_model_does_not_start_again_is_8 (self ): 462real = engine_update .start_model 463with mock .patch .object (engine_update ,"start_model" ,return_value = (False ,"Demo model did not start again: out of memory." )): 464code ,out ,err = self .run_cmd ("--yes" ,"--stop-model" ,"--start-again" ) 465self .assertEqual (code ,8 , (out ,err )) 466self .assertIn ("did not start again" ,out ) 467self .assertIn ("the new engine is in use" ,out ) 468self .assertEqual (self .resolved (),"0.1.46" ) 469del real 470 471def test_machine_output_has_the_models_and_never_a_question (self ): 472code ,out ,err = self .run_cmd ("--output" ,"json" ,"--stop-model" ,"--start-again" ) 473self .assertEqual (code ,0 , (out ,err )) 474data = json .loads (out ) 475self .assertTrue (data ["ok" ]) 476self .assertEqual (data ["models" ]["stopped" ][0 ]["name" ],NAME ) 477self .assertTrue (data ["models" ]["restarts" ][0 ]["restarted" ]) 478 479def test_machine_output_with_a_model_and_no_flag_is_error_7_as_json (self ): 480code ,out ,err = self .run_cmd ("--output" ,"json" ) 481self .assertEqual (code ,7 ) 482data = json .loads (out ) 483self .assertFalse (data ["ok" ]) 484self .assertEqual (data ["error" ]["code" ],7 ) 485self .assertIn (NAME ,data ["error" ]["message" ]) 486 487def test_jsonl_carries_the_model_events_for_the_app (self ): 488code ,out ,err = self .run_cmd ("--output" ,"jsonl" ,"--stop-model" ,"--start-again" ) 489self .assertEqual (code ,0 , (out ,err )) 490events = [json .loads (line )for line in out .splitlines ()if line .startswith ("{" )] 491phases = [e ["phase" ]for e in events if e .get ("event" )== "models" ] 492self .assertEqual (phases , ["consent" ,"stopping" ,"stopped" ,"restarting" ,"restarted" ]) 493self .assertEqual (events [[e .get ("phase" )for e in events ].index ("consent" )]["models" ][0 ]["profile" ],PROFILE ) 494 495def test_check_names_the_model_and_the_one_next_step (self ): 496code ,out ,err = self .run_cmd ("--check" ) 497self .assertEqual (code ,0 ) 498self .assertIn (NAME ,out ) 499self .assertIn ("asks before it stops it" ,out ) 500self .assertEqual ((self .state (),self .resolved ()), ("ready" ,"0.1.45" ),"a check changes nothing" ) 501 502 503class AfterTheStop (unittest .TestCase ): 504"""Found by the real DeepSeek flow: right after a big model was stopped, the next look still saw 'a running Strata server' (its engine had not let 505go of the shared lease yet) and the update was refused half way.""" 506 507def gate (self ,** kw ): 508stopped = [] 509asked = [] 510gate = engine_update .ModelGate (ask = lambda q ,d :asked .append (q )or True ,stop = stopped .append ,start = lambda m : (True ,"ok" ),** kw ) 511model = engine_update .RunningModel ("launch-x" ,"X" ,port = 8080 ) 512gate .consented ["launch-x" ]= model 513gate .asked ,gate .stops = asked ,stopped 514return gate ,model 515 516def test_the_update_waits_until_the_stopped_engine_has_let_go (self ): 517gate ,_ = self .gate (settle_s = 30 ) 518answers = [[{"profile" :"launch-x" }], [{"profile" :"a running Strata server" }], [{"profile" :"a running Strata server" }], []] 519with mock .patch ("time.sleep" ): 520gate .release (lambda :answers .pop (0 )if answers else []) 521self .assertEqual (len (gate .stops ),1 ) 522self .assertEqual (answers , [],"it looked until nothing was serving" ) 523 524def test_an_engine_that_never_lets_go_is_said_plainly_and_nothing_more_is_changed (self ): 525gate ,_ = self .gate (settle_s = 0.3 ) 526calls = {"n" :0 } 527 528def serving (): 529calls ["n" ]+= 1 530return [{"profile" :"launch-x" }]if calls ["n" ]== 1 else [{"profile" :"a running Strata server" }] 531with self .assertRaises (updater .UpdateError )as caught : 532gate .release (serving ) 533self .assertEqual (caught .exception .exit_code ,7 ) 534self .assertIn ("has not let go of the graphics card" ,str (caught .exception )) 535 536def test_the_start_again_question_says_same_settings_when_part_of_the_update_was_made (self ): 537for changed ,text in ((True ,"with the same settings" ), (False ,"The old engine is unchanged" )): 538gate ,model = self .gate () 539gate .stopped .append (model ) 540gate .finish (False ,changed ) 541self .assertIn (text ,gate .asked [0 ],changed ) 542 543 544class StartWait (unittest .TestCase ): 545"""Found by the real DeepSeek flow: a DeepSeek run config asks for a long engine wait; runtime.start takes 0..1800 only, so the model did not start again.""" 546 547def test_the_wait_never_exceeds_what_the_runtime_accepts (self ): 548import tempfile 549with tempfile .TemporaryDirectory ()as d : 550cfg = Path (d )/ "run.json" 551for ready ,want in ((None ,960.0 ), (300 ,360.0 ), (1800 ,1800.0 ), (5000 ,1800.0 )): 552cfg .write_text (json .dumps ({"engine_ready_s" :ready }if ready else {})) 553model = engine_update .RunningModel ("launch-x" ,"X" ) 554with mock .patch .object (profiles ,"load" ,return_value = ({"source_config" :str (cfg )},"r" )): 555self .assertEqual (engine_update ._start_wait (model ),want ,ready ) 556 557 558class TheQuestion (unittest .TestCase ): 559def test_a_person_at_a_keyboard_gets_the_question_and_default_on_enter (self ): 560a = argparse .Namespace (yes = False ) 561with mock .patch .object (sys .stdin ,"isatty" ,return_value = True ),mock .patch .object (sys .stdout ,"isatty" ,return_value = True ): 562ask = update_cmd ._ask_factory (a ,False ) 563self .assertIsNotNone (ask ) 564for typed ,default ,want in (("" ,False ,False ), ("" ,True ,True ), ("y" ,False ,True ), ("Yes" ,False ,True ), ("n" ,True ,False ), ("what" ,True ,False )): 565with mock .patch ("builtins.input" ,return_value = typed ): 566self .assertEqual (ask ("q?" ,default ),want , (typed ,default )) 567with mock .patch ("builtins.input" ,side_effect = EOFError ): 568self .assertFalse (ask ("q?" ,False )) 569 570def test_nobody_is_asked_for_a_program_a_pipe_or_yes (self ): 571with mock .patch .object (sys .stdin ,"isatty" ,return_value = True ),mock .patch .object (sys .stdout ,"isatty" ,return_value = True ): 572self .assertIsNone (update_cmd ._ask_factory (argparse .Namespace (yes = True ),False )) 573self .assertIsNone (update_cmd ._ask_factory (argparse .Namespace (yes = False ),True )) 574with mock .patch .object (sys .stdin ,"isatty" ,return_value = False ): 575self .assertIsNone (update_cmd ._ask_factory (argparse .Namespace (yes = False ),False )) 576 577 578if __name__ == "__main__" : 579unittest .main ()