okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
714ff8242
main
1"""Managed local instance lifecycle with an owned fake engine process.""" 2 3import io 4import hashlib 5import json 6import os 7import queue 8import signal 9import socket 10import subprocess 11import sys 12import tempfile 13import threading 14import time 15import unittest 16import urllib .request 17from contextlib import redirect_stdout 18from pathlib import Path 19from unittest import mock 20 21from strata_cli .cli import main 22from strata_cli import bench 23from strata_cli .client import Endpoint 24from strata_control import calibration ,journal ,management ,owner_transport ,procs ,profiles ,recipes ,runtime 25 26 27WINDOWS = os .name == "nt" 28 29 30@ unittest . skipUnless ( os . name in ( "posix" , "nt" ), "no qualified owner transport on this platform" ) 31class RuntimeTests (unittest .TestCase ): 32def setUp (self ): 33self .temp = tempfile .TemporaryDirectory (prefix = "strata-runtime-test-" ) 34self .addCleanup (self ._remove_temp ) 35self .root = Path (self .temp .name ) 36env = mock .patch .dict (os .environ , {"STRATA_PROFILE_DIR" :str (self .root / "profiles" ), 37"STRATA_RUNTIME_DIR" :str (self .root / "runtime" )}) 38env .start () 39self .addCleanup (env .stop ) 40previous_key = os .environ .pop ("STRATA_API_KEY" ,None ) 41self .addCleanup (lambda :os .environ .__setitem__ ("STRATA_API_KEY" ,previous_key ) 42if previous_key is not None else os .environ .pop ("STRATA_API_KEY" ,None )) 43engine = self .root / "engine.py" 44engine .write_text ("#!" + sys .executable + "\nimport sys\nfrom pathlib import Path\n" 45"if '--batch' in sys.argv: print('INFO batch_slots=2', flush=True)\n" 46"print('READY 4096 stop', flush=True)\n" 47"for line in sys.stdin:\n" 48" if line.strip() == 'QUIT': break\n" 49" if line.startswith(('GEN ', 'BGEN ')):\n" 50" slot = int(line.split()[1]) if line.startswith('BGEN ') else None\n" 51" if Path('fail-generation').exists():\n" 52" print('ERR generation-failed', flush=True)\n" 53" continue\n" 54" if Path('empty-generation').exists():\n" 55" print('DONE 0 1 1.0 0.0 stop 0 0 0', flush=True)\n" 56" if slot is not None: print(f'BADM {slot} 0', flush=True)\n" 57" continue\n" 58" print('T 97', flush=True)\n" 59" print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True)\n" 60" if slot is not None: print(f'BADM {slot} 0', flush=True)\n" ,encoding = "utf-8" ) 61engine .chmod (0o700 ) 62if WINDOWS : 63# a script cannot be an engine exe on Windows: a .cmd that runs it stands in for the binary 64wrapper = self .root / "engine.cmd" 65wrapper .write_bytes (f'@echo off\r\n" { sys . executable } " " { engine } " %*\r\n' .encode ()) 66engine = wrapper 67from tools .strata_tokenizer import BYTE_TO_UNICODE 68tokenizer = self .root / "tokenizer" 69tokenizer .mkdir () 70tokens = [BYTE_TO_UNICODE [i ]for i in range (256 )]+ [ 71"ab" ,"<|im_start|>" ,"<|im_end|>" ,"<|endoftext|>" ] 72 (tokenizer / "vocab.json" ).write_text (json .dumps ({token :i for i ,token in enumerate (tokens )})) 73 (tokenizer / "merges.txt" ).write_text ("a b" ) 74 (tokenizer / "token_type.json" ).write_text (json .dumps ([0 ]* 257 + [3 ,3 ,3 ])) 75self .config = self .root / "run.json" 76self .config .write_text (json .dumps ({"exe" :str (engine ),"tokenizer" :str (tokenizer ), 77"args" : [],"cwd" :str (self .root ),"model_name" :"fake" , 78"host" :"127.0.0.1" ,"port" :0 }),encoding = "utf-8" ) 79profiles .create ("local" ,str (self .config )) 80self .addCleanup (self ._stop ) 81 82def _remove_temp (self ): 83# On Windows the stopped host can still hold runtime\local.host.log for a moment while it exits (seen on a GitHub runner): retry for 84# up to 10 s, then fail with the path that stayed open 85deadline = time .monotonic ()+ 10 86while True : 87try : 88self .temp .cleanup () 89return 90except PermissionError : 91if time .monotonic ()> deadline : 92raise 93time .sleep (0.25 ) 94 95def _stop (self ): 96try : 97if runtime ._read_state ("local" )is not None : 98runtime .stop ("local" ,timeout = 12 ) 99except (OSError ,profiles .ProfileError ): 100pass 101 102def _cli (self ,* args ): 103output = io .StringIO () 104with redirect_stdout (output ): 105code = main (["runtime" ,* args ,"--output" ,"json" ]) 106return code ,json .loads (output .getvalue ()) 107 108def test_component_inspection_bridge_is_read_only_and_reports_missing_files (self ): 109command = [sys .executable ,"-m" ,"strata_control.management" ] 110root = Path (__file__ ).resolve ().parents [2 ] 111 112def send (live ): 113request = {"schema_version" :1 ,"action" :"components.inspect" , 114"profile" :"local" ,"params" : {"live" :live }} 115completed = subprocess .run (command ,input = json .dumps (request ),text = True , 116capture_output = True ,cwd = root ,env = os .environ .copy (),timeout = 15 ) 117return completed .returncode ,json .loads (completed .stdout ) 118 119code ,result = send (False ) 120self .assertEqual (code ,0 ) 121self .assertTrue (result ["ok" ]) 122self .assertTrue (result ["report" ]["ok" ]) 123self .assertEqual (result ["report" ]["profile" ],"local" ) 124self .assertEqual (Path (result ["report" ]["source_config" ]),self .config .resolve ()) 125self .assertIsNone (result ["report" ]["live_gpu_probe" ]) 126self .assertEqual (journal .list_runs ("local" ), []) 127self .assertEqual (runtime .status ("local" )["state" ],"stopped" ) 128 129code ,invalid = send ("true" ) 130self .assertEqual ((code ,invalid ["ok" ]), (2 ,False )) 131self .assertIn ("live must be true or false" ,invalid ["error" ]) 132engine = self .root / ("engine.cmd" if WINDOWS else "engine.py" ) 133engine .unlink () 134code ,missing = send (False ) 135self .assertEqual ((code ,missing ["ok" ],missing ["report" ]["ok" ]), (0 ,True ,False )) 136self .assertIn ("engine" , [row ["name" ]for row in missing ["report" ]["components" ] 137if row ["status" ]== "missing" ]) 138self .assertEqual (journal .list_runs ("local" ), []) 139 140def test_profile_change_bridge_reviews_revision_source_and_typed_overrides (self ): 141command = [sys .executable ,"-m" ,"strata_control.management" ] 142root = Path (__file__ ).resolve ().parents [2 ] 143 144def send (action ,params ): 145request = {"schema_version" :1 ,"action" :action ,"profile" :"local" ,"params" :params } 146completed = subprocess .run (command ,input = json .dumps (request ),text = True , 147capture_output = True ,cwd = root ,env = os .environ .copy (),timeout = 15 ) 148return completed .returncode ,json .loads (completed .stdout ) 149 150other = self .root / "strata-other.json" 151other .write_text (self .config .read_text ().replace ('"fake"' ,'"other"' ),encoding = "utf-8" ) 152with mock .patch .dict (os .environ , {"STRATA_INSTALL_DIR" :str (self .root )}): 153code ,listed = send ("models.installed" , {}) 154inspect_code ,inspected = send ("models.inspect" , {"model_id" :"other" }) 155self .assertEqual (code ,0 ) 156self .assertIn ("other" , [item ["id" ]for item in listed ["inventory" ]["models" ]]) 157self .assertEqual ((inspect_code ,inspected ["ok" ]), (0 ,True )) 158self .assertEqual (inspected ["inspection" ]["model" ]["id" ],"other" ) 159self .assertEqual (journal .list_runs ("local" ), []) 160candidate = self .root / "candidate.gguf" 161candidate .write_bytes (b"GGUF" + (3 ).to_bytes (4 ,"little" )) 162code ,import_plan = send ("models.import.plan" , {"path" :str (candidate )}) 163self .assertEqual ((code ,import_plan ["ok" ]), (0 ,True )) 164self .assertFalse (import_plan ["plan" ]["would_write" ]) 165self .assertEqual (import_plan ["plan" ]["execution_compatibility" ],"unverified" ) 166code ,invalid_import = send ("models.import.plan" , {"path" :"relative.gguf" }) 167self .assertEqual ((code ,invalid_import ["ok" ]), (2 ,False )) 168code ,current = send ("profile.inspect" , {}) 169self .assertEqual ((code ,current ["ok" ],current ["profile" ]["id" ]), (0 ,True ,"local" )) 170self .assertEqual (current ["profile" ]["overrides" ], {}) 171edits = {"overrides" : {"parallel" :4 ,"batch_groups" :"auto" ,"max_queue" :8 , 172"queue_timeout" :2.5 },"source_config" :str (other )} 173code ,plan = send ("profile.change.plan" , {** edits ,"if_revision" :current ["revision" ]}) 174self .assertEqual ((code ,plan ["ok" ],plan ["plan" ]["would_save" ]), (0 ,True ,True )) 175self .assertEqual (plan ["plan" ]["revision" ],current ["revision" ]) 176self .assertEqual (plan ["plan" ]["effective" ]["parallel" ],4 ) 177self .assertEqual (plan ["plan" ]["source_config_after" ],str (other .resolve ())) 178self .assertEqual (profiles .load ("local" )[0 ]["source_config" ],str (self .config .resolve ())) 179self .assertEqual (journal .list_runs ("local" ), []) 180 181execute = {** edits ,"if_revision" :plan ["plan" ]["revision" ], 182"if_source_sha256" :plan ["plan" ]["source_sha256" ]} 183profiles .set_values ("local" , ["max_queue=1" ]) 184code ,stale = send ("profile.change" ,execute ) 185self .assertEqual ((code ,stale ["ok" ]), (6 ,False )) 186self .assertIn ("changed after review" ,stale ["error" ]) 187code ,stale_plan = send ("profile.change.plan" , {** edits ,"if_revision" :current ["revision" ]}) 188self .assertEqual ((code ,stale_plan ["ok" ]), (6 ,False )) 189code ,plan = send ("profile.change.plan" , {** edits , 190"if_revision" :profiles .load ("local" )[1 ]}) 191execute .update (if_revision = plan ["plan" ]["revision" ], 192if_source_sha256 = plan ["plan" ]["source_sha256" ]) 193other .write_text (other .read_text ()+ "\n" ,encoding = "utf-8" ) 194code ,changed_source = send ("profile.change" ,execute ) 195self .assertEqual ((code ,changed_source ["ok" ]), (6 ,False )) 196code ,plan = send ("profile.change.plan" , {** edits , 197"if_revision" :profiles .load ("local" )[1 ]}) 198execute .update (if_revision = plan ["plan" ]["revision" ], 199if_source_sha256 = plan ["plan" ]["source_sha256" ]) 200code ,saved = send ("profile.change" ,execute ) 201self .assertEqual ((code ,saved ["ok" ],saved ["saved" ]), (0 ,True ,True )) 202self .assertEqual (profiles .load ("local" )[0 ]["source_config" ],str (other .resolve ())) 203self .assertEqual (profiles .load ("local" )[0 ]["overrides" ],edits ["overrides" ]) 204self .assertEqual (runtime .status ("local" )["state" ],"stopped" ) 205self .assertEqual (journal .list_runs ("local" ), []) 206 207code ,invalid = send ("profile.change.plan" , {"overrides" : {"parallel" :True }, 208"source_config" :str (other ),"if_revision" :profiles .load ("local" )[1 ]}) 209self .assertEqual ((code ,invalid ["ok" ]), (2 ,False )) 210 211started = runtime .start ("local" ,wait = 12 ) 212self .assertTrue (started ["ok" ],started ) 213running = runtime .status ("local" ) 214self .assertEqual (running ["state" ],"ready" ) 215running_revision = running ["profile_revision" ] 216next_edit = {"overrides" : {** edits ["overrides" ],"parallel" :6 }, 217"source_config" :str (other .resolve ())} 218code ,next_plan = send ("profile.change.plan" , {** next_edit , 219"if_revision" :profiles .load ("local" )[1 ]}) 220self .assertEqual ((code ,next_plan ["ok" ]), (0 ,True )) 221code ,next_saved = send ("profile.change" , {** next_edit , 222"if_revision" :next_plan ["plan" ]["revision" ], 223"if_source_sha256" :next_plan ["plan" ]["source_sha256" ]}) 224self .assertEqual ((code ,next_saved ["ok" ]), (0 ,True )) 225still_running = runtime .status ("local" ) 226self .assertEqual (still_running ["instance_id" ],running ["instance_id" ]) 227self .assertEqual (still_running ["profile_revision" ],running_revision ) 228restart_plan = runtime .plan_restart ("local" ) 229self .assertTrue (restart_plan ["ok" ],restart_plan ) 230self .assertEqual (restart_plan ["candidate_profile_revision" ],next_saved ["revision" ]) 231self .assertNotEqual (restart_plan ["candidate_profile_revision" ],running_revision ) 232 233def test_local_management_bridge_and_cli_share_owner_and_journal (self ): 234command = [sys .executable ,"-m" ,"strata_control.management" ] 235root = Path (__file__ ).resolve ().parents [2 ] 236 237def send (action ,params ): 238request = {"schema_version" :1 ,"action" :action ,"profile" :"local" ,"params" :params } 239completed = subprocess .run (command ,input = json .dumps (request ),text = True , 240capture_output = True ,cwd = root ,env = os .environ .copy (),timeout = 120 ) 241return completed .returncode ,json .loads (completed .stdout ) 242 243code ,invalid = send ("runtime.start" , {"wait_s" :True ,"shutdown_timeout_s" :2 , 244"if_profile_revision" :None , 245"if_source_sha256" :None }) 246self .assertEqual ((code ,invalid ["ok" ]), (2 ,False )) 247self .assertEqual (runtime .status ("local" )["state" ],"stopped" ) 248self .assertEqual (journal .list_runs ("local" ), []) 249code ,preview = send ("runtime.start.plan" , {"shutdown_timeout_s" :2 }) 250self .assertEqual (code ,0 ) 251self .assertFalse (preview ["plan" ]["would_start" ]) 252self .assertEqual (runtime .status ("local" )["state" ],"stopped" ) 253start_params = {"wait_s" :10 ,"shutdown_timeout_s" :2 , 254"if_profile_revision" :preview ["plan" ]["launch" ]["profile_revision" ], 255"if_source_sha256" :preview ["plan" ]["source_sha256" ]} 256self .assertEqual (preview ["plan" ]["source_sha256" ],hashlib .sha256 (self .config .read_bytes ()).hexdigest ()) 257code ,missing = send ("runtime.start" , {** start_params ,"if_source_sha256" :None }) 258self .assertEqual ((code ,missing ["ok" ]), (2 ,False )) 259self .config .write_bytes (self .config .read_bytes ()+ b" " ) 260code ,stale_source = send ("runtime.start" ,start_params ) 261self .assertEqual ((code ,stale_source ["error" ]), (6 ,"source_changed_after_start_plan" )) 262self .assertEqual (journal .list_runs ("local" ), []) 263self .config .write_bytes (self .config .read_bytes ()[:- 1 ]) 264profiles .set_values ("local" , ["max_queue=32" ]) 265code ,stale_profile = send ("runtime.start" ,start_params ) 266self .assertEqual ((code ,stale_profile ["error" ]), (6 ,"profile_changed_after_start_plan" )) 267self .assertEqual (journal .list_runs ("local" ), []) 268code ,preview = send ("runtime.start.plan" , {"shutdown_timeout_s" :2 }) 269self .assertEqual (code ,0 ) 270start_params .update (if_profile_revision = preview ["plan" ]["launch" ]["profile_revision" ], 271if_source_sha256 = preview ["plan" ]["source_sha256" ]) 272 273code ,started = send ("runtime.start" ,start_params ) 274self .assertEqual (code ,0 ,started ) 275self .assertTrue (started ["ok" ]) 276start_record = journal .load ("local" ,started ["operation_id" ]) 277self .assertEqual (start_record ["kind" ],"runtime.start" ) 278self .assertEqual (start_record ["intent" ]["expected_source_sha256" ],start_params ["if_source_sha256" ]) 279cli_code ,current = self ._cli ("status" ,"--profile" ,"local" ) 280self .assertEqual ((cli_code ,current ["instance_id" ]), (0 ,started ["instance_id" ])) 281code ,verify_plan = send ("runtime.verify.plan" , {"load" :False }) 282self .assertEqual ((code ,verify_plan ["ok" ]), (0 ,True )) 283self .assertEqual (verify_plan ["plan" ]["owner_id" ],started ["owner_id" ]) 284self .assertEqual (verify_plan ["plan" ]["instance_id" ],started ["instance_id" ]) 285self .assertFalse (verify_plan ["plan" ]["would_verify" ]) 286verify_params = {"wait_s" :10 ,"load" :False , 287"if_owner_id" :verify_plan ["plan" ]["owner_id" ], 288"if_instance_id" :verify_plan ["plan" ]["instance_id" ]} 289count = len (journal .list_runs ("local" )) 290code ,missing_verify = send ("runtime.verify" , {** verify_params ,"if_owner_id" :None }) 291self .assertEqual ((code ,missing_verify ["ok" ]), (2 ,False )) 292code ,stale_verify_owner = send ("runtime.verify" , {** verify_params , 293"if_owner_id" :"0" * 32 }) 294self .assertEqual ((code ,stale_verify_owner ["error" ]), 295 (6 ,"owner_changed_after_verify_plan" )) 296code ,stale_verify_instance = send ("runtime.verify" , {** verify_params , 297"if_instance_id" :"0" * 32 }) 298self .assertEqual ((code ,stale_verify_instance ["error" ]), 299 (6 ,"instance_changed_after_verify_plan" )) 300self .assertEqual (len (journal .list_runs ("local" )),count ) 301host_denied = runtime ._rpc ("local" ,"verify" ,params = { 302"wait" :10 ,"load" :False ,"expected_owner_id" :"0" * 32 , 303"expected_instance_id" :started ["instance_id" ]}) 304self .assertEqual (host_denied ["error" ],"owner_changed_after_verify_plan" ) 305host_denied = runtime ._rpc ("local" ,"verify" ,params = { 306"wait" :10 ,"load" :False ,"expected_owner_id" :started ["owner_id" ], 307"expected_instance_id" :"0" * 32 }) 308self .assertEqual (host_denied ["error" ],"instance_changed_after_verify_plan" ) 309code ,verified = send ("runtime.verify" ,verify_params ) 310self .assertEqual ((code ,verified ["ok" ],verified ["verified_now" ]), (0 ,True ,True )) 311self .assertEqual (verified ["instance_id" ],started ["instance_id" ]) 312verify_record = journal .load ("local" ,verified ["operation_id" ]) 313self .assertEqual (verify_record ["intent" ]["expected_instance_id" ],started ["instance_id" ]) 314cli_code ,cli_verify_plan = self ._cli ("verify" ,"--profile" ,"local" ,"--plan" ) 315self .assertEqual ((cli_code ,cli_verify_plan ["plan" ]["instance_id" ]), 316 (0 ,started ["instance_id" ])) 317code ,old_stop_plan = send ("runtime.stop.plan" , {}) 318self .assertEqual ((code ,old_stop_plan ["ok" ]), (0 ,True )) 319self .assertEqual (old_stop_plan ["plan" ]["instance_id" ],started ["instance_id" ]) 320code ,restart_plan = send ("runtime.restart.plan" , {"allow_source_switch" :False , 321"allow_source_migration" :False }) 322self .assertEqual ((code ,restart_plan ["ok" ]), (0 ,True )) 323self .assertEqual (restart_plan ["current_owner_id" ],started ["owner_id" ]) 324self .assertEqual (restart_plan ["current_instance_id" ],started ["instance_id" ]) 325restart_params = {"wait_s" :80 ,"startup_wait_s" :60 , 326"if_profile_revision" :restart_plan ["candidate_profile_revision" ], 327"if_owner_id" :restart_plan ["current_owner_id" ], 328"if_instance_id" :restart_plan ["current_instance_id" ], 329"if_source_sha256" :restart_plan ["candidate_source_sha256" ], 330"allow_source_switch" :False ,"allow_source_migration" :False } 331code ,missing_condition = send ("runtime.restart" , {** restart_params , 332"if_source_sha256" :None }) 333self .assertEqual ((code ,missing_condition ["ok" ]), (2 ,False )) 334code ,missing_owner = send ("runtime.restart" , {** restart_params , 335"if_owner_id" :None }) 336self .assertEqual ((code ,missing_owner ["ok" ]), (2 ,False )) 337count = len (journal .list_runs ("local" )) 338code ,stale_owner = send ("runtime.restart" , {** restart_params , 339"if_owner_id" :"0" * 32 }) 340self .assertEqual ((code ,stale_owner ["error" ]), (6 ,"owner_changed_after_restart_plan" )) 341code ,stale_instance = send ("runtime.restart" , {** restart_params , 342"if_instance_id" :"0" * 32 }) 343self .assertEqual ((code ,stale_instance ["error" ]), (6 ,"instance_changed_after_restart_plan" )) 344self .assertEqual (len (journal .list_runs ("local" )),count ) 345host_denied = runtime ._rpc ("local" ,"restart" ,params = { 346"expected_owner_id" :"0" * 32 ,"expected_instance_id" :started ["instance_id" ]}) 347self .assertEqual (host_denied ["error" ],"owner_changed_after_restart_plan" ) 348host_denied = runtime ._rpc ("local" ,"restart" ,params = { 349"expected_owner_id" :started ["owner_id" ],"expected_instance_id" :"0" * 32 }) 350self .assertEqual (host_denied ["error" ],"instance_changed_after_restart_plan" ) 351self .assertEqual (runtime .status ("local" )["instance_id" ],started ["instance_id" ]) 352code ,restarted = send ("runtime.restart" ,restart_params ) 353self .assertEqual ((code ,restarted ["ok" ]), (0 ,True ),restarted ) 354self .assertNotEqual (restarted ["instance_id" ],started ["instance_id" ]) 355self .assertEqual (journal .load ("local" ,restarted ["operation_id" ])["kind" ],"runtime.restart" ) 356count = len (journal .list_runs ("local" )) 357code ,stale_verify = send ("runtime.verify" ,verify_params ) 358self .assertEqual ((code ,stale_verify ["error" ]), (6 ,"instance_changed_after_verify_plan" )) 359self .assertEqual (len (journal .list_runs ("local" )),count ) 360code ,stale_review = send ("runtime.restart" ,restart_params ) 361self .assertEqual ((code ,stale_review ["error" ]), (6 ,"instance_changed_after_restart_plan" )) 362self .assertEqual (len (journal .list_runs ("local" )),count ) 363self .assertEqual (runtime .status ("local" )["instance_id" ],restarted ["instance_id" ]) 364old_stop_params = {"wait_s" :12 ,"if_owner_id" :old_stop_plan ["plan" ]["owner_id" ], 365"if_instance_id" :old_stop_plan ["plan" ]["instance_id" ]} 366count = len (journal .list_runs ("local" )) 367code ,stale_stop = send ("runtime.stop" ,old_stop_params ) 368self .assertEqual ((code ,stale_stop ["error" ]), (6 ,"instance_changed_after_stop_plan" )) 369self .assertEqual (len (journal .list_runs ("local" )),count ) 370self .assertEqual (runtime .status ("local" )["instance_id" ],restarted ["instance_id" ]) 371code ,stop_plan = send ("runtime.stop.plan" , {}) 372self .assertEqual ((code ,stop_plan ["ok" ]), (0 ,True )) 373stop_params = {"wait_s" :12 ,"if_owner_id" :stop_plan ["plan" ]["owner_id" ], 374"if_instance_id" :stop_plan ["plan" ]["instance_id" ]} 375code ,stale_owner = send ("runtime.stop" , {** stop_params ,"if_owner_id" :"0" * 32 }) 376self .assertEqual ((code ,stale_owner ["error" ]), (6 ,"owner_changed_after_stop_plan" )) 377self .assertEqual (len (journal .list_runs ("local" )),count ) 378host_denied = runtime ._rpc ("local" ,"stop" ,params = {"expected_owner_id" :"0" * 32 , 379"expected_instance_id" :restarted ["instance_id" ]}) 380self .assertEqual (host_denied ["error" ],"owner_changed_after_stop_plan" ) 381host_denied = runtime ._rpc ("local" ,"stop" ,params = {"expected_owner_id" :stop_params ["if_owner_id" ], 382"expected_instance_id" :started ["instance_id" ]}) 383self .assertEqual (host_denied ["error" ],"instance_changed_after_stop_plan" ) 384self .assertEqual (runtime .status ("local" )["instance_id" ],restarted ["instance_id" ]) 385code ,stopped = send ("runtime.stop" ,stop_params ) 386self .assertEqual ((code ,stopped ["state" ]), (0 ,"stopped" )) 387self .assertEqual (journal .load ("local" ,stopped ["operation_id" ])["kind" ],"runtime.stop" ) 388self .assertEqual (runtime .status ("local" )["state" ],"stopped" ) 389 390def test_local_management_bridge_rejects_ambiguous_requests (self ): 391command = [sys .executable ,"-m" ,"strata_control.management" ] 392root = Path (__file__ ).resolve ().parents [2 ] 393invalid = ( 394'{"schema_version":1,"action":"runtime.status","action":"runtime.start",' 395'"profile":"local","params":{}}' , 396'{"schema_version":1,"action":"runtime.start","profile":"local",' 397'"params":{"wait_s":NaN,"shutdown_timeout_s":2}}' , 398'{"schema_version":1,"action":"runtime.start","profile":"local",' 399'"params":{"wait_s":10,"shutdown_timeout_s":2,"command":"rm -rf /"}}' , 400'{"schema_version":2,"action":"runtime.status","profile":"local","params":{}}' , 401 ) 402for payload in invalid : 403with self .subTest (payload = payload [:50 ]): 404completed = subprocess .run (command ,input = payload ,text = True ,capture_output = True , 405cwd = root ,env = os .environ .copy (),timeout = 10 ) 406response = json .loads (completed .stdout ) 407self .assertEqual ((completed .returncode ,response ["ok" ]), (2 ,False )) 408self .assertEqual (runtime .status ("local" )["state" ],"stopped" ) 409self .assertEqual (journal .list_runs ("local" ), []) 410 411def test_owner_host_refuses_source_changed_after_start_review (self ): 412preview = management .runtime_action ("start" ,"local" ,plan = True )["plan" ] 413self .config .write_bytes (self .config .read_bytes ()+ b" " ) 414host = subprocess .Popen ([sys .executable ,"-m" ,"strata_control.runtime" ,"--host" ,"local" , 415"--shutdown-timeout" ,"2" ,"--startup-wait" ,"10" , 416"--expected-profile-revision" ,preview ["launch" ]["profile_revision" ], 417"--expected-source-sha256" ,preview ["source_sha256" ]], 418cwd = Path (__file__ ).resolve ().parents [2 ],env = os .environ .copy (), 419stdin = subprocess .DEVNULL ,stdout = subprocess .DEVNULL , 420stderr = subprocess .DEVNULL ) 421try : 422deadline = time .monotonic ()+ 8 423result = {"state" :"stopped" } 424while time .monotonic ()< deadline : 425result = runtime .status ("local" ) 426if result .get ("state" )== "failed" : 427break 428self .assertIsNone (host .poll (),"owner host exited before reporting status" ) 429time .sleep (0.05 ) 430self .assertEqual (result .get ("error" ),"source_changed_after_start_plan" ) 431self .assertIsNone (result .get ("child_pid" )) 432self .assertEqual (list ((self .root / "runtime" ).glob ("*.ready.json" )), []) 433finally : 434if host .poll ()is None : 435try : 436runtime .stop ("local" ,timeout = 8 ) 437finally : 438host .wait (timeout = 10 ) 439 440@ unittest . skipIf ( WINDOWS , "Windows console stop needs a platform-specific integration runner (no SIGTERM/SIGINT)" ) 441def test_foreground_jsonl_emits_ready_and_stop_without_human_stdout (self ): 442for stop_signal ,expected_code ,expected_reason ,quiet in ( 443 (signal .SIGTERM ,0 ,"sigterm" ,False ), 444 (signal .SIGINT ,130 ,"sigint" ,False ), 445 (signal .SIGTERM ,0 ,"sigterm" ,True )): 446with self .subTest (signal = expected_reason ,quiet = quiet ): 447rows = queue .Queue () 448stderr_path = self .root / f"serve- { expected_reason } - { 'quiet' if quiet else 'normal' } .stderr" 449with stderr_path .open ("w+" ,encoding = "utf-8" )as diagnostics : 450process = subprocess .Popen ( 451 [sys .executable ,"strata.py" ,"serve" ,"--profile" ,"local" ,"--port" ,"0" , 452"--shutdown-timeout" ,"2" ,"--output" ,"jsonl" ,* (["--quiet" ]if quiet else [])], 453cwd = Path (__file__ ).resolve ().parents [2 ],env = os .environ .copy (), 454stdout = subprocess .PIPE ,stderr = diagnostics ,text = True ,bufsize = 1 ) 455reader = threading .Thread (target = lambda : [rows .put (line )for line in process .stdout ], 456daemon = True ) 457reader .start () 458try : 459collected = [] 460for _ in range (4 ): 461collected .append (json .loads (rows .get (timeout = 15 ))) 462if collected [- 1 ].get ("event" )== "ready" : 463break 464self .assertEqual ([row ["event" ]for row in collected ], ["starting" ,"ready" ]) 465ready = collected [- 1 ] 466self .assertGreater (ready ["bound_port" ],0 ) 467self .assertEqual (ready ["model_state" ],"ready" ) 468self .assertEqual (ready ["pid" ],process .pid ) 469request = urllib .request .Request ( 470ready ["api_url" ]+ "/v1/chat/completions" ,method = "POST" , 471data = json .dumps ({"messages" : [{"role" :"user" ,"content" :"Hi" }], 472"max_tokens" :1 }).encode (), 473headers = {"Content-Type" :"application/json" }) 474with urllib .request .urlopen (request ,timeout = 5 )as response : 475self .assertEqual (response .status ,200 ) 476self .assertIn ("choices" ,json .load (response )) 477process .send_signal (stop_signal ) 478self .assertEqual (process .wait (timeout = 15 ),expected_code ) 479reader .join (timeout = 3 ) 480self .assertFalse (reader .is_alive ()) 481while not rows .empty (): 482collected .append (json .loads (rows .get_nowait ())) 483self .assertEqual ([row ["event" ]for row in collected ], 484 ["starting" ,"ready" ,"stopping" ,"draining" ,"stopped" ]) 485self .assertEqual (collected [- 1 ]["reason" ],expected_reason ) 486self .assertEqual (collected [- 1 ]["exit_code" ],expected_code ) 487self .assertTrue (all (row ["schema_version" ]== 1 for row in collected )) 488self .assertNotIn ("api_key" ,json .dumps (collected ).lower ()) 489diagnostics .flush () 490if quiet : 491self .assertNotIn ("ready:" ,stderr_path .read_text (encoding = "utf-8" )) 492else : 493self .assertIn ("ready:" ,stderr_path .read_text (encoding = "utf-8" )) 494finally : 495if process .poll ()is None : 496process .kill () 497process .wait (timeout = 5 ) 498reader .join (timeout = 2 ) 499process .stdout .close () 500 501def test_start_profile_revision_restart_and_stop (self ): 502code ,started = self ._cli ("start" ,"--profile" ,"local" ,"--wait" ,"60" , 503"--shutdown-timeout" ,"2" ) 504self .assertEqual (code ,0 ) 505self .assertEqual (started ["state" ],"ready" ) 506self .assertTrue (started ["api_identity_verified" ]) 507self .assertTrue (started ["launch_attested" ]) 508self .assertTrue (started ["generation_ready" ]) 509self .assertEqual (started ["readiness_state" ],"generation_ready" ) 510started_record = journal .load ("local" ,started ["operation_id" ]) 511self .assertEqual ((started_record ["schema_version" ],started_record ["kind" ],started_record ["state" ]), 512 (2 ,"runtime.start" ,"succeeded" )) 513self .assertTrue (started_record ["result" ]["launch_attested" ]) 514first_id = started ["instance_id" ] 515self .assertNotEqual (started ["host_pid" ],started ["child_pid" ]) 516status = self ._cli ("status" ,"--profile" ,"local" )[1 ] 517self .assertEqual (status ["instance_id" ],first_id ) 518self .assertNotIn ("operation_id" ,status ) 519code ,checked = self ._cli ("verify" ,"--profile" ,"local" ,"--wait" ,"60" ) 520self .assertEqual (code ,0 ) 521self .assertTrue (checked ["verified_now" ]) 522self .assertTrue (checked ["launch_attested" ]) 523self .assertTrue (checked ["generation_ready" ]) 524checked_record = journal .load ("local" ,checked ["operation_id" ]) 525self .assertEqual (checked_record ["kind" ],"runtime.verify" ) 526self .assertTrue (checked_record ["result" ]["launch_attested" ]) 527profiles .set_values ("local" , ["parallel=2" ]) 528code ,restarted = self ._cli ("restart" ,"--profile" ,"local" ,"--wait" ,"80" ) 529self .assertEqual (code ,0 ) 530self .assertTrue (restarted ["restarted" ]) 531self .assertTrue (restarted ["launch_attested" ]) 532self .assertTrue (restarted ["generation_ready" ]) 533self .assertEqual (journal .load ("local" ,restarted ["operation_id" ])["kind" ],"runtime.restart" ) 534self .assertEqual (restarted ["previous_instance_id" ],first_id ) 535self .assertNotEqual (restarted ["instance_id" ],first_id ) 536code ,stopped = self ._cli ("stop" ,"--profile" ,"local" ,"--wait" ,"12" ) 537self .assertEqual (code ,0 ) 538self .assertEqual (stopped ["state" ],"stopped" ) 539self .assertEqual (journal .load ("local" ,stopped ["operation_id" ])["kind" ],"runtime.stop" ) 540self .assertEqual ([row ["origin" ]for row in journal .list_runs ("local" )], ["direct" ]* 4 ) 541deadline = time .monotonic ()+ 3 542while runtime ._read_state ("local" )is not None and time .monotonic ()< deadline : 543time .sleep (0.05 ) 544self .assertIsNone (runtime ._read_state ("local" )) 545 546def test_cli_stop_plan_pins_the_reviewed_owner_and_instance (self ): 547started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 548self .assertTrue (started ["ok" ]) 549code ,preview = self ._cli ("stop" ,"--profile" ,"local" ,"--plan" ) 550self .assertEqual (code ,0 ,preview ) 551self .assertEqual (preview ["plan" ]["instance_id" ],started ["instance_id" ]) 552self .assertFalse (preview ["plan" ]["would_stop" ]) 553code ,denied = self ._cli ("stop" ,"--profile" ,"local" ,"--wait" ,"12" , 554"--if-owner-id" ,"0" * 32 , 555"--if-instance-id" ,preview ["plan" ]["instance_id" ]) 556self .assertEqual ((code ,denied ["error" ]["message" ]), (6 ,"owner_changed_after_stop_plan" )) 557self .assertEqual (runtime .status ("local" )["instance_id" ],started ["instance_id" ]) 558code ,stopped = self ._cli ("stop" ,"--profile" ,"local" ,"--wait" ,"12" , 559"--if-owner-id" ,preview ["plan" ]["owner_id" ], 560"--if-instance-id" ,preview ["plan" ]["instance_id" ]) 561self .assertEqual ((code ,stopped ["state" ]), (0 ,"stopped" )) 562record = journal .load ("local" ,stopped ["operation_id" ]) 563self .assertEqual (record ["intent" ]["expected_owner_id" ],preview ["plan" ]["owner_id" ]) 564 565def test_managed_benchmark_binds_to_owned_launch (self ): 566with socket .socket ()as reserved : 567reserved .bind (("127.0.0.1" ,0 )) 568port = reserved .getsockname ()[1 ] 569cfg = json .loads (self .config .read_text (encoding = "utf-8" )) 570cfg ["port" ]= port 571self .config .write_text (json .dumps (cfg ),encoding = "utf-8" ) 572started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 573self .assertTrue (started ["ok" ]) 574identity = {"profile" :"local" ,"revision" :profiles .load ("local" )[1 ], 575"source_sha256" :hashlib .sha256 (self .config .read_bytes ()).hexdigest ()} 576endpoint = Endpoint (started ["api_url" ]) 577output = self .root / "managed-bench" 578with redirect_stdout (io .StringIO ()): 579result = bench .run (endpoint ,endpoint ,output ,concurrency = 1 , 580profile_identity = identity ,require_managed_match = True ) 581self .assertTrue (result ["successful" ]) 582self .assertEqual (result ["profile_running_match" ],"managed_launch_checked" ) 583self .assertEqual (result ["instance_id" ],started ["instance_id" ]) 584self .assertTrue (result ["profile_running_check" ]["after" ]["matched" ]) 585output_json = io .StringIO () 586with redirect_stdout (output_json ): 587code = main (["bench" ,"run" ,"--suite" ,"serving-smoke" ,"--profile" ,"local" ,"--require-managed-match" , 588"--concurrency" ,"1" ,"--out" ,str (self .root / "cli-managed" ), 589"--output" ,"json" ]) 590self .assertEqual (code ,0 ) 591self .assertEqual (json .loads (output_json .getvalue ())["summary" ]["successful" ],True ) 592self .assertEqual (json .loads (output_json .getvalue ())["summary" ]["profile_running_match" ], 593"managed_launch_checked" ) 594self .assertEqual (bench .load (self .root / "cli-managed" )["profile_running_match" ], 595"managed_launch_checked" ) 596comparison = bench .compare (result ,bench .load (self .root / "cli-managed" )) 597self .assertEqual (comparison ["baseline" ]["profile_running_match" ],"managed_launch_checked" ) 598self .assertFalse (any ("running server config" in warning for warning in comparison ["warnings" ])) 599 600def test_owned_runtime_and_calibration_exclude_each_other_even_on_port_zero (self ): 601first = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 602self .assertTrue (first ["ok" ]) 603output = self .root / "blocked-calibration.json" 604with self .assertRaisesRegex (profiles .ProfileError ,"engine lease" ): 605calibration .measure ("local" ,output ,exclusive_ack = True , 606runner = lambda cfg ,say :self .fail ("calibration runner was started" )) 607self .assertFalse (output .exists ()) 608self .assertTrue (runtime .stop ("local" ,timeout = 12 )["ok" ]) 609with calibration ._managed_exclusive (): 610with self .assertRaisesRegex (profiles .ProfileError ,"runtime host failed to start" ): 611runtime .start ("local" ,wait = 1 ,shutdown_timeout = 2 ) 612self .assertTrue (runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 )["ok" ]) 613 614def test_failed_new_port_rolls_back_previous_owned_launch (self ): 615first = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 616self .assertTrue (first ["ok" ]) 617with socket .socket ()as occupied : 618occupied .bind (("127.0.0.1" ,0 )) 619occupied .listen (1 ) 620profiles .set_values ("local" , [f"port= { occupied . getsockname ()[ 1 ] } " ]) 621result = runtime .restart ("local" ,timeout = 20 ) 622self .assertFalse (result ["ok" ]) 623self .assertTrue (result ["rolled_back" ]) 624self .assertNotEqual (result ["instance_id" ],first ["instance_id" ]) 625self .assertEqual (runtime .status ("local" )["instance_id" ],result ["instance_id" ]) 626 627def test_changed_source_is_rejected_before_stopping_old_instance (self ): 628first = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 629self .assertTrue (first ["ok" ]) 630self .config .write_bytes (self .config .read_bytes ()+ b" " ) 631for allow in (False ,True ): 632result = runtime .restart ("local" ,timeout = 10 ,allow_source_switch = allow , 633expected_source_sha256 = hashlib .sha256 (self .config .read_bytes ()).hexdigest () 634if allow else None ) 635self .assertFalse (result ["ok" ]) 636self .assertEqual (result ["error" ],"source_config_changed_restart_requires_migration" ) 637self .assertEqual (runtime .status ("local" )["instance_id" ],first ["instance_id" ]) 638 639def test_edited_source_migration_is_previewed_digest_pinned_and_verified (self ): 640first = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 641self .assertTrue (first ["ok" ]) 642edited = json .loads (self .config .read_text ()) 643edited ["model_name" ]= "edited-fake" 644self .config .write_text (json .dumps (edited ),encoding = "utf-8" ) 645denied = runtime .plan_restart ("local" ) 646self .assertEqual (denied ["error" ],"source_config_changed_restart_requires_migration" ) 647self .assertTrue (denied ["requires_allow_source_migration" ]) 648code ,plan = self ._cli ("restart" ,"--profile" ,"local" ,"--allow-source-migration" ,"--plan" ) 649self .assertEqual (code ,0 ) 650self .assertTrue (plan ["source_migration" ]) 651self .assertTrue (plan ["rollback_snapshot_required" ]) 652self .assertFalse (plan ["source_switch" ]) 653self .assertTrue (plan ["changed" ]) 654self .assertEqual (runtime .status ("local" )["instance_id" ],first ["instance_id" ]) 655code ,missing = self ._cli ("restart" ,"--profile" ,"local" ,"--allow-source-migration" ) 656self .assertEqual ((code ,missing ["error" ]["code" ]), (2 ,2 )) 657self .config .write_bytes (self .config .read_bytes ()+ b" " ) 658code ,stale = self ._cli ("restart" ,"--profile" ,"local" ,"--allow-source-migration" , 659"--if-source-sha256" ,plan ["candidate_source_sha256" ]) 660self .assertEqual ((code ,stale ["error" ]), (6 ,"source_changed_after_preview" )) 661self .assertEqual (runtime .status ("local" )["instance_id" ],first ["instance_id" ]) 662self .config .write_text (json .dumps (edited ),encoding = "utf-8" ) 663code ,restarted = self ._cli ("restart" ,"--profile" ,"local" ,"--allow-source-migration" , 664"--if-profile-revision" ,plan ["candidate_profile_revision" ], 665"--if-source-sha256" ,plan ["candidate_source_sha256" ], 666"--startup-wait" ,"60" ,"--wait" ,"80" ) 667self .assertEqual (code ,0 ,restarted ) 668self .assertTrue (restarted ["source_migrated" ]) 669self .assertFalse (restarted ["source_switched" ]) 670self .assertTrue (restarted ["launch_attested" ]) 671self .assertTrue (restarted ["generation_ready" ]) 672self .assertNotEqual (restarted ["instance_id" ],first ["instance_id" ]) 673self .assertTrue (journal .load ("local" ,restarted ["operation_id" ])["result" ]["source_migrated" ]) 674self .assertEqual (list ((self .root / "runtime" ).glob ("*.rollback.json" )), []) 675 676def test_failed_edited_source_migration_uses_private_snapshot_for_rollback (self ): 677secret = "migration-test-key" 678original = json .loads (self .config .read_text ()) 679original ["api_key" ]= secret 680self .config .write_text (json .dumps (original ),encoding = "utf-8" ) 681first = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 682self .assertTrue (first ["ok" ]) 683with socket .socket ()as occupied : 684occupied .bind (("127.0.0.1" ,0 )) 685occupied .listen (1 ) 686edited = json .loads (self .config .read_text ()) 687edited ["port" ]= occupied .getsockname ()[1 ] 688self .config .write_text (json .dumps (edited ),encoding = "utf-8" ) 689plan = runtime .plan_restart ("local" ,allow_source_migration = True ) 690code ,result = self ._cli ("restart" ,"--profile" ,"local" ,"--allow-source-migration" , 691"--startup-wait" ,"30" ,"--wait" ,"80" , 692"--if-source-sha256" ,plan ["candidate_source_sha256" ]) 693self .assertEqual (code ,6 ) 694self .assertFalse (result ["ok" ]) 695self .assertTrue (result ["rolled_back" ]) 696self .assertEqual (result ["state" ],"ready" ) 697self .assertNotEqual (result ["instance_id" ],first ["instance_id" ]) 698self .assertEqual (json .loads (self .config .read_text ())["port" ],edited ["port" ]) 699snapshot = Path (result ["rollback_source_config" ]) 700self .assertEqual (snapshot .parent ,self .root / "runtime" ) 701if WINDOWS : 702from strata_control import private_files 703self .assertTrue (private_files .is_unshared (snapshot ))# NTFS has no mode bits: the ACL is the promise 704else : 705self .assertEqual (snapshot .stat ().st_mode & 0o077 ,0 ) 706self .assertEqual (json .loads (snapshot .read_text ())["port" ],0 ) 707self .assertEqual (json .loads (snapshot .read_text ())["api_key" ],secret ) 708self .assertNotIn (secret ,json .dumps (result )) 709record_result = journal .load ("local" ,result ["operation_id" ])["result" ] 710self .assertEqual (record_result ["rollback_source_config" ],str (snapshot )) 711self .assertNotIn (secret ,json .dumps (record_result )) 712self .assertTrue (runtime .status ("local" )["generation_ready" ]) 713# The edited file can be retried as a distinct source after freeing its port. 714plan = runtime .plan_restart ("local" ,allow_source_switch = True ) 715self .assertTrue (plan ["source_switch" ]) 716retried = runtime .restart ("local" ,timeout = 20 ,startup_wait = 60 , 717allow_source_switch = True , 718expected_source_sha256 = plan ["candidate_source_sha256" ]) 719self .assertTrue (retried ["ok" ],retried ) 720self .assertFalse (snapshot .exists ()) 721 722def test_explicit_source_switch_previews_and_restarts_new_config (self ): 723first = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 724self .assertTrue (first ["ok" ]) 725next_config = self .root / "next-run.json" 726changed = json .loads (self .config .read_text ()) 727changed ["model_name" ]= "fake-next" 728next_config .write_text (json .dumps (changed ),encoding = "utf-8" ) 729previous_revision = profiles .load ("local" )[1 ] 730source_output = io .StringIO () 731with redirect_stdout (source_output ): 732source_code = main (["profile" ,"use-config" ,"local" ,"--from-config" ,str (next_config ), 733"--if-revision" ,previous_revision ,"--output" ,"json" ]) 734self .assertEqual (source_code ,0 ) 735next_revision = json .loads (source_output .getvalue ())["revision" ] 736 737denied = runtime .plan_restart ("local" ) 738self .assertFalse (denied ["ok" ]) 739self .assertEqual (denied ["error" ],"source_switch_requires_opt_in" ) 740self .assertTrue (denied ["requires_allow_source_switch" ]) 741code ,preview = self ._cli ("restart" ,"--profile" ,"local" ,"--allow-source-switch" ,"--plan" ) 742self .assertEqual (code ,0 ) 743self .assertTrue (preview ["source_switch" ]) 744self .assertTrue (preview ["changed" ]) 745self .assertEqual (preview ["current_source_config" ],str (self .config .resolve ())) 746self .assertEqual (preview ["candidate_source_config" ],str (next_config .resolve ())) 747self .assertEqual (preview ["candidate_profile_revision" ],next_revision ) 748self .assertEqual (runtime .status ("local" )["instance_id" ],first ["instance_id" ]) 749 750code ,missing_digest = self ._cli ("restart" ,"--profile" ,"local" ,"--allow-source-switch" ) 751self .assertEqual (code ,2 ) 752self .assertFalse (missing_digest ["ok" ]) 753self .assertEqual (runtime .status ("local" )["instance_id" ],first ["instance_id" ]) 754next_config .write_bytes (next_config .read_bytes ()+ b" " ) 755code ,stale = self ._cli ("restart" ,"--profile" ,"local" ,"--allow-source-switch" , 756"--if-source-sha256" ,preview ["candidate_source_sha256" ]) 757self .assertEqual (code ,6 ) 758self .assertEqual (stale ["error" ],"source_changed_after_preview" ) 759self .assertEqual (runtime .status ("local" )["instance_id" ],first ["instance_id" ]) 760next_config .write_text (json .dumps (changed ),encoding = "utf-8" ) 761code ,switched = self ._cli ("restart" ,"--profile" ,"local" ,"--allow-source-switch" , 762"--if-profile-revision" ,next_revision ,"--wait" ,"80" , 763"--if-source-sha256" ,preview ["candidate_source_sha256" ], 764"--startup-wait" ,"60" ) 765self .assertEqual (code ,0 ,switched ) 766self .assertTrue (switched ["source_switched" ]) 767self .assertNotEqual (switched ["instance_id" ],first ["instance_id" ]) 768self .assertEqual (switched ["profile_revision" ],next_revision ) 769self .assertTrue (switched ["launch_attested" ]) 770record = journal .load ("local" ,switched ["operation_id" ]) 771self .assertTrue (record ["intent" ]["allow_source_switch" ]) 772self .assertEqual (runtime .plan_restart ("local" )["source_switch" ],False ) 773 774def test_failed_source_switch_restores_prior_owned_launch (self ): 775first = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 776self .assertTrue (first ["ok" ]) 777with socket .socket ()as occupied : 778occupied .bind (("127.0.0.1" ,0 )) 779occupied .listen (1 ) 780next_config = self .root / "bad-next-run.json" 781changed = json .loads (self .config .read_text ()) 782changed ["port" ]= occupied .getsockname ()[1 ] 783next_config .write_text (json .dumps (changed ),encoding = "utf-8" ) 784proposed ,revision = profiles .load ("local" ) 785proposed ["source_config" ]= str (next_config ) 786profiles .save ("local" ,proposed ,expected_revision = revision ) 787digest = hashlib .sha256 (next_config .read_bytes ()).hexdigest () 788result = runtime .restart ("local" ,timeout = 20 ,startup_wait = 30 ,allow_source_switch = True , 789expected_source_sha256 = digest ) 790self .assertFalse (result ["ok" ]) 791self .assertTrue (result ["rolled_back" ]) 792self .assertNotEqual (result ["instance_id" ],first ["instance_id" ]) 793self .assertEqual (runtime .status ("local" )["instance_id" ],result ["instance_id" ]) 794self .assertEqual (runtime .status ("local" )["profile_revision" ],revision ) 795 796def test_source_switch_needs_unchanged_distinct_regular_rollback_file (self ): 797first = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 798self .assertTrue (first ["ok" ]) 799hardlink = self .root / "same-inode.json" 800os .link (self .config ,hardlink ) 801proposed ,revision = profiles .load ("local" ) 802proposed ["source_config" ]= str (hardlink ) 803profiles .save ("local" ,proposed ,expected_revision = revision ) 804denied = runtime .plan_restart ("local" ,allow_source_switch = True ) 805self .assertEqual (denied ["error" ],"source_switch_requires_distinct_regular_files" ) 806 807next_config = self .root / "next-run.json" 808next_config .write_bytes (self .config .read_bytes ()) 809proposed ,revision = profiles .load ("local" ) 810proposed ["source_config" ]= str (next_config ) 811profiles .save ("local" ,proposed ,expected_revision = revision ) 812self .config .write_bytes (self .config .read_bytes ()+ b" " ) 813denied = runtime .plan_restart ("local" ,allow_source_switch = True ) 814self .assertEqual (denied ["error" ],"rollback_source_changed" ) 815self .assertEqual (runtime .status ("local" )["instance_id" ],first ["instance_id" ]) 816allowed = runtime .plan_restart ("local" ,allow_source_switch = True , 817allow_source_migration = True ) 818self .assertTrue (allowed ["source_switch" ]) 819self .assertTrue (allowed ["source_migration" ]) 820result = runtime .restart ("local" ,timeout = 20 ,startup_wait = 60 , 821allow_source_switch = True ,allow_source_migration = True , 822expected_source_sha256 = allowed ["candidate_source_sha256" ]) 823self .assertTrue (result ["ok" ],result ) 824self .assertTrue (result ["source_switched" ]) 825self .assertTrue (result ["source_migrated" ]) 826self .assertEqual (list ((self .root / "runtime" ).glob ("*.rollback.json" )), []) 827 828def test_server_reading_changed_config_fails_launch_attestation (self ): 829host = runtime .Host ("local" ,shutdown_timeout = 2 ,startup_wait = 10 ) 830plan ,args ,source ,original = host ._plan () 831# Change valid JSON between the owner's snapshot and the server's read. 832self .config .write_bytes (original + b" " ) 833try : 834host ._launch (args ,source ,original ,plan ["profile_revision" ]) 835result = host ._wait_ready (10 ) 836self .assertFalse (result ["ok" ]) 837self .assertEqual (result ["error" ],"probe_launch_attestation_mismatch" ) 838finally : 839host ._stop_child () 840 841def test_authenticated_generation_probe_keeps_credential_out_of_status (self ): 842secret = "runtime-probe-test-key" 843cfg = json .loads (self .config .read_text ()) 844cfg ["api_key" ]= secret 845self .config .write_text (json .dumps (cfg )) 846result = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 847self .assertTrue (result ["generation_ready" ]) 848self .assertTrue (result ["launch_attested" ]) 849self .assertNotIn (secret ,json .dumps (result )) 850self .assertNotIn (secret ,json .dumps (runtime .status ("local" ))) 851 852def test_remote_bind_preview_accepts_server_supported_key_list (self ): 853cfg = json .loads (self .config .read_text ()) 854cfg .update (host = "0.0.0.0" ,api_key = ["first" ,"second" ]) 855self .config .write_text (json .dumps (cfg )) 856from strata_cli .cli import _launch_plan 857plan ,_ = _launch_plan ("local" ) 858self .assertEqual (plan ["effective" ]["host" ],"0.0.0.0" ) 859self .assertNotIn ("first" ,json .dumps (plan )) 860 861def test_remote_bind_without_a_key_is_planned_not_refused (self ): 862# owner decision 2026-10-20: a key is recommended on a network, never required 863from strata_cli .cli import _launch_plan 864for key in (None ,"none" ): 865cfg = json .loads (self .config .read_text ()) 866cfg ["host" ]= "0.0.0.0" 867cfg .pop ("api_key" ,None ) 868if key : 869cfg ["api_key" ]= key 870self .config .write_text (json .dumps (cfg )) 871with mock .patch .dict (os .environ , {"STRATA_API_KEY" :"" }): 872plan ,args = _launch_plan ("local" ) 873self .assertEqual (plan ["effective" ]["host" ],"0.0.0.0" ) 874 875def test_lazy_model_is_verified_as_unloaded_without_generation (self ): 876cfg = json .loads (self .config .read_text ()) 877cfg ["lazy_load" ]= True 878self .config .write_text (json .dumps (cfg )) 879result = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 880self .assertTrue (result ["ok" ]) 881self .assertTrue (result ["api_identity_verified" ]) 882self .assertFalse (result ["generation_ready" ]) 883self .assertEqual ((result ["model_state" ],result ["readiness_state" ]), ("unloaded" ,"unloaded" )) 884code ,checked = self ._cli ("verify" ,"--profile" ,"local" ,"--wait" ,"60" ,"--load" ) 885self .assertEqual (code ,0 ) 886self .assertTrue (checked ["generation_ready" ]) 887self .assertEqual (runtime .status ("local" )["model_state" ],"ready" ) 888self .assertTrue (runtime .verify ("local" ,timeout = 10 )["generation_ready" ]) 889 890def test_failed_generation_probe_does_not_report_ready (self ): 891engine = self .root / "engine.py" 892engine .write_text (engine .read_text ().replace (" print('T 97', flush=True)" , 893" print('ERR probe-failed', flush=True)\n continue" )) 894result = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 895self .assertFalse (result ["ok" ]) 896self .assertEqual (result ["state" ],"failed" ) 897self .assertEqual (result ["error" ],"probe_http_400" ) 898 899def test_zero_token_completion_does_not_count_as_generation_ready (self ): 900 (self .root / "empty-generation" ).write_text ("empty" ) 901result = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 902self .assertFalse (result ["ok" ]) 903self .assertEqual (result ["error" ],"probe_generation_no_tokens" ) 904 905def test_explicit_verify_reports_later_engine_failure_without_stopping_instance (self ): 906first = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 907self .assertTrue (first ["generation_ready" ]) 908flag = self .root / "fail-generation" 909flag .write_text ("fail" ) 910code ,checked = self ._cli ("verify" ,"--profile" ,"local" ,"--wait" ,"60" ) 911self .assertEqual (code ,6 ) 912self .assertEqual (checked ["error" ],"probe_http_400" ) 913self .assertEqual (journal .load ("local" ,checked ["operation_id" ])["state" ],"failed" ) 914self .assertEqual (runtime .status ("local" )["instance_id" ],first ["instance_id" ]) 915flag .unlink () 916self .assertTrue (runtime .verify ("local" ,timeout = 10 )["generation_ready" ]) 917 918def test_failed_generation_after_profile_edit_rolls_back_prior_launch (self ): 919first = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 920self .assertTrue (first ["generation_ready" ]) 921engine = self .root / "engine.py" 922engine .write_text (engine .read_text ().replace ( 923" print('T 97', flush=True)" , 924" if slot is not None:\n" 925" print('ERR batch-probe-failed', flush=True)\n" 926" continue\n" 927" print('T 97', flush=True)" )) 928profiles .set_values ("local" , ["parallel=2" ]) 929result = runtime .restart ("local" ,timeout = 30 ,startup_wait = 60 ) 930self .assertFalse (result ["ok" ]) 931self .assertTrue (result ["rolled_back" ]) 932restored = runtime .status ("local" ) 933self .assertTrue (restored ["generation_ready" ]) 934self .assertEqual (restored ["instance_id" ],result ["instance_id" ]) 935 936def test_start_plan_is_read_only (self ): 937code ,result = self ._cli ("start" ,"--profile" ,"local" ,"--plan" ) 938self .assertEqual (code ,0 ) 939self .assertFalse (result ["plan" ]["would_start" ]) 940self .assertIsNone (runtime ._read_state ("local" )) 941self .assertEqual (journal .list_runs ("local" ), []) 942 943def test_restart_plan_compares_revision_without_stopping_instance (self ): 944started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 945self .assertTrue (started ["ok" ]) 946unchanged = runtime .plan_restart ("local" ) 947self .assertTrue (unchanged ["ok" ]) 948self .assertFalse (unchanged ["changed" ]) 949profiles .set_values ("local" , ["parallel=2" ]) 950code ,planned = self ._cli ("restart" ,"--profile" ,"local" ,"--plan" ) 951self .assertEqual (code ,0 ) 952self .assertTrue (planned ["changed" ]) 953self .assertFalse (planned ["would_drain" ]) 954self .assertFalse (planned ["would_start" ]) 955count = len (journal .list_runs ("local" )) 956code ,denied = self ._cli ("restart" ,"--profile" ,"local" , 957"--if-profile-revision" ,planned ["candidate_profile_revision" ], 958"--if-source-sha256" ,planned ["candidate_source_sha256" ], 959"--if-owner-id" ,planned ["current_owner_id" ], 960"--if-instance-id" ,"0" * 32 ) 961self .assertEqual ((code ,denied ["error" ]["message" ]), 962 (6 ,"instance_changed_after_restart_plan" )) 963self .assertEqual (len (journal .list_runs ("local" )),count ) 964self .assertEqual (runtime .status ("local" )["instance_id" ],started ["instance_id" ]) 965 966def test_editable_recipe_previews_and_reruns_owned_instance (self ): 967recipes .initialize ("local" ) 968started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 969self .assertTrue (started ["ok" ]) 970profiles .set_values ("local" , ["parallel=2" ]) 971code ,planned = self ._ops ("plan" ,"restart" ) 972self .assertEqual (code ,0 ) 973self .assertTrue (planned ["plan" ]["operation" ]["preflight" ]["changed" ]) 974self .assertEqual (runtime .status ("local" )["instance_id" ],started ["instance_id" ]) 975revision = planned ["plan" ]["recipe_revision" ] 976preflight = planned ["plan" ]["operation" ]["preflight" ] 977code ,ran = self ._ops ("run" ,"restart" ,"--if-revision" ,revision , 978"--if-profile-revision" ,planned ["plan" ]["profile_revision" ], 979"--if-owner-id" ,preflight ["current_owner_id" ], 980"--if-instance-id" ,preflight ["current_instance_id" ], 981"--if-source-sha256" ,preflight ["candidate_source_sha256" ]) 982self .assertEqual (code ,0 ) 983self .assertTrue (ran ["operation" ]["result" ]["restarted" ]) 984self .assertNotEqual (ran ["operation" ]["result" ]["instance_id" ],started ["instance_id" ]) 985record = journal .load ("local" ,ran ["operation" ]["operation_id" ]) 986self .assertEqual (record ["state" ],"succeeded" ) 987self .assertEqual (record ["result" ]["instance_id" ],ran ["operation" ]["result" ]["instance_id" ]) 988count = len (journal .list_runs ("local" )) 989with self .assertRaisesRegex (profiles .ProfileError ,"instance_changed_after_restart_plan" ): 990recipes .run ("local" ,"restart" ,expected_revision = revision , 991expected_profile_revision = planned ["plan" ]["profile_revision" ], 992expected_owner_id = preflight ["current_owner_id" ], 993expected_instance_id = preflight ["current_instance_id" ], 994expected_source_sha256 = preflight ["candidate_source_sha256" ]) 995self .assertEqual (len (journal .list_runs ("local" )),count ) 996 997def test_stale_profile_revision_does_not_drain_owned_instance (self ): 998started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 999self .assertTrue (started ["ok" ]) 1000previous = profiles .load ("local" )[1 ] 1001profiles .set_values ("local" , ["parallel=2" ]) 1002result = runtime .restart ("local" ,timeout = 10 ,expected_profile_revision = previous ) 1003self .assertFalse (result ["ok" ]) 1004self .assertEqual (result ["error" ],"profile_changed_after_preview" ) 1005self .assertEqual (runtime .status ("local" )["instance_id" ],started ["instance_id" ]) 1006 1007def _ops (self ,* args ): 1008output = io .StringIO () 1009with redirect_stdout (output ): 1010code = main (["ops" ,* args ,"--profile" ,"local" ,"--output" ,"json" ]) 1011return code ,json .loads (output .getvalue ()) 1012 1013@ unittest . skipIf ( WINDOWS , "SIGTERM to a Windows process is TerminateProcess: the hard-kill test below covers it" ) 1014def test_terminating_owner_host_stops_its_child_and_removes_state (self ): 1015started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 1016self .assertTrue (started ["ok" ]) 1017os .kill (started ["host_pid" ],signal .SIGTERM ) 1018deadline = time .monotonic ()+ 8 1019while runtime ._read_state ("local" )is not None and time .monotonic ()< deadline : 1020time .sleep (0.05 ) 1021self .assertIsNone (runtime ._read_state ("local" )) 1022owned = runtime ._STARTED_HOSTS .pop ("local" ,None ) 1023if owned is not None : 1024self .assertEqual (owned .wait (timeout = 3 ),0 ) 1025 1026def test_hard_killed_host_child_exits_and_next_start_recovers_private_state (self ): 1027started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 1028self .assertTrue (started ["ok" ]) 1029old_child = started ["child_pid" ] 1030state = runtime ._read_state ("local" ) 1031orphan = self .root / "runtime" / f"local- { state [ 'token' ] } - { 'a' * 32 } .rollback.json" 1032orphan .write_bytes (self .config .read_bytes ()) 1033orphan .chmod (0o600 ) 1034owned = runtime ._STARTED_HOSTS .pop ("local" ) 1035if WINDOWS : 1036owned .kill ()# TerminateProcess: the host cannot clean up after itself 1037owned .wait (timeout = 3 ) 1038# the job object ends the server tree with the host, no matter how the host ended 1039deadline = time .monotonic ()+ 15 1040while runtime ._pid_exists (old_child )and time .monotonic ()< deadline : 1041time .sleep (0.1 ) 1042self .assertFalse (runtime ._pid_exists (old_child )) 1043else : 1044os .kill (started ["host_pid" ],signal .SIGKILL ) 1045self .assertEqual (owned .wait (timeout = 3 ),- signal .SIGKILL ) 1046stale = runtime .status ("local" ) 1047self .assertEqual ((stale ["state" ],stale ["error" ]), ("stale" ,"owner_host_lost" )) 1048# The next start waits for the inherited-pipe guard to stop the old 1049# process group; it never sends a signal to the saved child PID. 1050replacement = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 1051self .assertTrue (replacement ["ok" ]) 1052self .assertNotEqual (replacement ["child_pid" ],old_child ) 1053self .assertFalse (runtime ._pid_exists (old_child )) 1054self .assertFalse (orphan .exists ()) 1055 1056def test_recovery_refuses_a_still_present_child (self ): 1057state_path ,socket_path ,_ = runtime ._paths ("local" ) 1058token = "a" * 64 1059state = {"schema_version" :1 ,"profile" :"local" , 1060"socket" :"tcp:127.0.0.1:50000" if WINDOWS else str (socket_path ), 1061"token" :token ,"host_pid" :999999 } 1062lease = runtime ._write_new (state_path , (json .dumps (state )+ "\n" ).encode ()) 1063os .close (lease ) 1064marker = runtime ._child_marker ("local" ,token ) 1065marker .write_text (json .dumps ({"host_token" :token ,"phase" :"owned" , 1066"pid" :os .getpid (), 1067"ready" :str (state_path .parent / "local-fake.ready.json" )}),encoding = "utf-8" ) 1068marker .chmod (0o600 ) 1069with self .assertRaisesRegex (profiles .ProfileError ,"still present" ): 1070runtime .start ("local" ,wait = 0 ,shutdown_timeout = 2 ) 1071self .assertTrue (state_path .exists ()) 1072 1073# ---- round 0213 LIFECYCLE: the owner answers while it starts, leaves when its server is gone, and is recoverable at every point 1074 1075def _slow_plan_owner (self ,delay ): 1076"""An owner host in another process whose plan takes `delay` seconds (the slow imports, hardware questions and virus scans of #5177).""" 1077code = ("import time\n" 1078"from strata_control import runtime\n" 1079"original = runtime.Host._plan\n" 1080"def slow(self):\n" 1081f" time.sleep( { delay } )\n" 1082" return original(self)\n" 1083"runtime.Host._plan = slow\n" 1084"raise SystemExit(runtime.Host('local', shutdown_timeout=2).serve())\n" ) 1085owner = subprocess .Popen ([sys .executable ,"-c" ,code ],cwd = Path (__file__ ).resolve ().parents [2 ], 1086env = os .environ .copy (),stdin = subprocess .DEVNULL , 1087stdout = subprocess .DEVNULL ,stderr = subprocess .DEVNULL ) 1088self .addCleanup (lambda :owner .poll ()is None and (owner .kill (),owner .wait (timeout = 5 ))) 1089deadline = time .monotonic ()+ 15 1090while runtime ._read_state ("local" )is None and owner .poll ()is None and time .monotonic ()< deadline : 1091time .sleep (0.05 ) 1092self .assertIsNotNone (runtime ._read_state ("local" ),"the owner did not publish its state" ) 1093return owner 1094 1095def test_the_owner_answers_status_while_it_is_still_planning (self ):# #5177 1096owner = self ._slow_plan_owner (6 ) 1097began = time .monotonic () 1098for _ in range (3 ): 1099answer = runtime ._rpc ("local" ,"status" ,timeout = 2 )# the old owner did not accept before its plan was done: this timed out 1100self .assertEqual ((answer ["state" ],answer ["phase" ]), ("starting" ,"preparing" )) 1101time .sleep (0.3 ) 1102self .assertLess (time .monotonic ()- began ,5 ,"the status answers waited for the plan" ) 1103deadline = time .monotonic ()+ 40 1104answer = runtime ._rpc ("local" ,"status" ,timeout = 2 ) 1105while answer ["state" ]== "starting" and time .monotonic ()< deadline : 1106time .sleep (0.2 ) 1107answer = runtime ._rpc ("local" ,"status" ,timeout = 2 ) 1108self .assertEqual (answer ["state" ],"ready" ,answer ) 1109self .assertIsInstance (answer ["child_pid" ],int ) 1110 1111def test_a_stop_while_the_owner_plans_starts_no_server (self ):# #5177 1112owner = self ._slow_plan_owner (4 ) 1113state = runtime ._read_state ("local" ) 1114answer = self ._send (state ,state ["token" ],"stop" ) 1115self .assertTrue (answer ["ok" ],answer ) 1116self .assertEqual (owner .wait (timeout = 20 ),0 ) 1117time .sleep (0.5 ) 1118self .assertFalse (list ((self .root / "runtime" ).glob ("*.server.log" ))and 1119any (p .stat ().st_size for p in (self .root / "runtime" ).glob ("*.server.log" )),"a server was started after the stop" ) 1120self .assertIsNone (runtime ._read_state ("local" )) 1121 1122def test_a_start_keeps_asking_a_busy_owner_until_its_wait_is_over (self ):# #5177: one missed answer is not a failed start 1123calls = [] 1124real = runtime ._rpc 1125 1126def flaky (name ,command ,** kw ): 1127if command == "status" and len (calls )< 2 : 1128calls .append (kw .get ("timeout" )) 1129raise profiles .ProfileError ("runtime operation wait expired; inspect runtime status" ,8 ) 1130return real (name ,command ,** kw ) 1131with mock .patch .object (runtime ,"_rpc" ,flaky ): 1132started = runtime .start ("local" ,wait = 30 ,shutdown_timeout = 2 ) 1133self .assertTrue (started ["ok" ],started ) 1134self .assertEqual (len (calls ),2 ) 1135self .assertTrue (all (x >= 1 for x in calls )) 1136 1137def test_a_lost_owner_is_still_a_failed_start_at_once (self ): 1138def gone (name ,command ,** kw ): 1139raise profiles .ProfileError ("runtime control is unavailable; inspect the private host log" ,3 ) 1140with mock .patch .object (runtime ,"_rpc" ,gone ),mock .patch .object (runtime ,"_owner_alive" ,return_value = False ): 1141with self .assertRaisesRegex (profiles .ProfileError ,"unavailable" ): 1142runtime .start ("local" ,wait = 30 ,shutdown_timeout = 2 ) 1143 1144def test_an_engine_that_is_up_gets_its_own_first_token_budget (self ):# #5177 #5059 #4293 1145host = runtime .Host ("local" ,shutdown_timeout = 2 ,startup_wait = 5 ) 1146ready = self .root / "ready.json" 1147child = mock .Mock (pid = 4321 ) 1148child .poll .return_value = None 1149ready .write_text (json .dumps ({"pid" :4321 ,"instance_id" :"i" * 32 }),encoding = "utf-8" ) 1150host .child ,host .ready_path = child ,ready 1151host .args ,host .source_bytes ,host .expected_attestation = ["--host" ,"127.0.0.1" ],b"{}" ,"0" * 64 1152host .probe_deadline = time .monotonic ()- 100 # the load used up the whole wait 1153seen = [] 1154started = threading .Event () 1155 1156def probe (self_ ,ready_ ,key ,host_ ,source ,attestation ,timeout ): 1157seen .append (timeout ) 1158started .set () 1159with mock .patch .object (runtime .Host ,"_verify_ready" ,probe ): 1160self .assertEqual (host ._status ()["phase" ],"verifying_generation" ) 1161self .assertTrue (started .wait (5 )) 1162self .assertGreaterEqual (seen [0 ],runtime .VERIFY_BUDGET ) 1163 1164def test_the_start_wait_does_not_end_while_the_first_token_is_being_checked (self ):# #5177 #4293 1165answers = [{"ok" :True ,"state" :"starting" ,"phase" :"verifying_generation" }]* 3 + [{"ok" :True ,"state" :"ready" ,"phase" :None ,"instance_id" :"i" * 32 }] 1166clock = [0.0 ] 1167 1168def rpc (name ,command ,** kw ): 1169clock [0 ]+= 100.0 # every look is 100 s later: the 150 s wait is over after the second 1170return answers .pop (0 ) 1171with mock .patch .object (runtime ,"_rpc" ,rpc ),mock .patch .object (runtime .time ,"sleep" ,lambda s :None ),mock .patch .object (runtime .time ,"monotonic" ,lambda :clock [0 ]): 1172result = runtime ._await_start ("local" ,150 ) 1173self .assertTrue (result ["ok" ],result )# the verifying phase carried it past the wait, up to VERIFY_BUDGET 1174answers [:]= [{"ok" :True ,"state" :"starting" ,"phase" :"loading" }]* 9 1175clock [0 ]= 0.0 1176with mock .patch .object (runtime ,"_rpc" ,rpc ),mock .patch .object (runtime .time ,"sleep" ,lambda s :None ),mock .patch .object (runtime .time ,"monotonic" ,lambda :clock [0 ]): 1177result = runtime ._await_start ("local" ,150 ) 1178self .assertEqual ((result ["error" ],result ["phase" ]), ("startup_wait_expired" ,"loading" ))# a load that does not finish still ends 1179 1180def test_the_host_leaves_when_its_server_ends_on_its_own (self ):# #4574 #4893 (#4893 is the PR: same idea, own code) 1181started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 1182self .assertTrue (started ["ok" ]) 1183owned = runtime ._STARTED_HOSTS .pop ("local" ) 1184os .kill (started ["child_pid" ],signal .SIGTERM )# the server dies; the host did not ask it to 1185failed = None 1186deadline = time .monotonic ()+ 8 1187while time .monotonic ()< deadline : 1188failed = runtime .status ("local" ) 1189if failed .get ("state" )== "failed" : 1190break 1191time .sleep (0.1 ) 1192self .assertEqual (failed ["state" ],"failed" ,"the server's end is published before the host leaves" ) 1193self .assertEqual (failed ["error" ],"server_exited" ) 1194try : 1195code = owned .wait (timeout = runtime .CHILD_EXIT_GRACE + 15 ) 1196except subprocess .TimeoutExpired : 1197self .fail ("the owner host stays alive as a husk after its server exited" ) 1198self .assertEqual (code ,6 ) 1199self .assertIsNone (runtime ._read_state ("local" ),"the host left its private state behind" ) 1200log = (self .root / "runtime" / "local.host.log" ).read_text (encoding = "utf-8" ,errors = "replace" ) 1201self .assertIn ("the server ended on its own" ,log ) 1202replacement = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 )# no manual kill 1203self .assertTrue (replacement ["ok" ]) 1204 1205def test_die_with_does_not_stop_an_engine_for_a_look_that_failed (self ):# #4973 1206host = runtime .Host ("local" ,shutdown_timeout = 2 ,die_with = (os .getpid (),"tok" )) 1207with mock .patch .object (runtime .procs ,"start_token" ,return_value = None ),mock .patch .object (runtime ,"_pid_exists" ,return_value = True ): 1208for _ in range (10 ): 1209self .assertFalse (host ._die_with_gone (),"a process that is there but cannot be read ended the engine" ) 1210with mock .patch .object (runtime .procs ,"start_token" ,return_value = "tok" ): 1211self .assertFalse (host ._die_with_gone ()) 1212with mock .patch .object (runtime .procs ,"start_token" ,return_value = "other" ): 1213self .assertTrue (host ._die_with_gone (),"a later process with that number is the end of the one followed" ) 1214host .die_misses = 0 1215with mock .patch .object (runtime .procs ,"start_token" ,return_value = None ),mock .patch .object (runtime ,"_pid_exists" ,return_value = False ): 1216self .assertEqual ([host ._die_with_gone ()for _ in range (runtime .DIE_WITH_MISSES )], [False ]* (runtime .DIE_WITH_MISSES - 1 )+ [True ]) 1217 1218def test_a_host_lost_before_it_launched_anything_is_recovered (self ):# #4250: the PR's idea 1219owner = self ._slow_plan_owner (120 ) 1220state = runtime ._read_state ("local" ) 1221marker = runtime ._child_marker ("local" ,state ["token" ]) 1222self .assertEqual (json .loads (marker .read_text (encoding = "utf-8" )), {"host_token" :state ["token" ],"phase" :"no_child" }) 1223owner .kill () 1224owner .wait (timeout = 5 ) 1225deadline = time .monotonic ()+ 5 1226while runtime ._host_lease_active ("local" )and time .monotonic ()< deadline : 1227time .sleep (0.05 ) 1228self .assertTrue (runtime ._recover_stale ("local" ,wait = 0 )) 1229self .assertIsNone (runtime ._read_state ("local" )) 1230self .assertFalse (marker .exists ()) 1231self .assertTrue (runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 )["ok" ]) 1232 1233def test_a_missing_or_foreign_marker_still_refuses_recovery (self ):# #4250 1234state_path ,socket_path ,_ = runtime ._paths ("local" ) 1235token = "a" * 64 1236state = {"schema_version" :1 ,"profile" :"local" ,"socket" :"tcp:127.0.0.1:50000" if WINDOWS else str (socket_path ), 1237"token" :token ,"host_pid" :999999 } 1238lease = runtime ._write_new (state_path , (json .dumps (state )+ "\n" ).encode ()) 1239runtime ._unlock_file (lease ) 1240os .close (lease ) 1241with self .assertRaisesRegex (profiles .ProfileError ,"no valid child ownership record" ): 1242runtime ._recover_stale ("local" ,wait = 0 ) 1243marker = runtime ._child_marker ("local" ,token ) 1244marker .write_text (json .dumps ({"host_token" :token ,"phase" :"no_child" ,"pid" :os .getpid ()}),encoding = "utf-8" )# more than the exact record 1245marker .chmod (0o600 ) 1246with self .assertRaisesRegex (profiles .ProfileError ,"unverified" ): 1247runtime ._recover_stale ("local" ,wait = 0 ) 1248self .assertTrue (state_path .exists ()) 1249 1250# ---- owner transport, attach and identity (POSIX socket and Windows loopback alike) 1251 1252def _stale_host (self ,child_pid ,* ,started = None ,token = "a" * 64 ): 1253"""A state file whose host is gone, and the ownership marker naming `child_pid` as its server.""" 1254state_path ,socket_path ,_ = runtime ._paths ("local" ) 1255state = {"schema_version" :1 ,"profile" :"local" , 1256"socket" :"tcp:127.0.0.1:50000" if WINDOWS else str (socket_path ), 1257"token" :token ,"host_pid" :999999 } 1258lease = runtime ._write_new (state_path , (json .dumps (state )+ "\n" ).encode ()) 1259runtime ._unlock_file (lease ) 1260os .close (lease ) 1261marker = runtime ._child_marker ("local" ,token ) 1262record = {"host_token" :token ,"phase" :"owned" ,"pid" :child_pid , 1263"ready" :str (state_path .parent / "local-fake.ready.json" )} 1264if started is not None : 1265record ["started" ]= started 1266marker .write_text (json .dumps (record ),encoding = "utf-8" ) 1267marker .chmod (0o600 ) 1268return state_path ,marker 1269 1270def _send (self ,state ,token ,command ): 1271client = owner_transport .connect (state ["socket" ],timeout = 5 ) 1272try : 1273client .sendall ((json .dumps ({"token" :token ,"command" :command })+ "\n" ).encode ()) 1274return json .loads (client .recv (4096 ).split (b"\n" )[0 ]) 1275finally : 1276client .close () 1277 1278def test_a_second_client_attaches_from_another_process_and_shares_the_owner (self ): 1279started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 1280self .assertTrue (started ["ok" ]) 1281state = runtime ._read_state ("local" ) 1282if WINDOWS : 1283self .assertRegex (state ["socket" ],r"^tcp:127\.0\.0\.1:[1-9][0-9]*$" ) 1284root = Path (__file__ ).resolve ().parents [2 ] 1285done = subprocess .run ([sys .executable ,"strata.py" ,"runtime" ,"status" ,"--profile" ,"local" , 1286"--output" ,"json" ],cwd = root ,env = os .environ .copy (),capture_output = True , 1287text = True ,timeout = 30 ) 1288self .assertEqual (done .returncode ,0 ,done .stderr ) 1289other = json .loads (done .stdout ) 1290self .assertEqual ((other ["state" ],other ["owner_id" ],other ["instance_id" ],other ["host_pid" ]), 1291 ("ready" ,started ["owner_id" ],started ["instance_id" ],started ["host_pid" ])) 1292self .assertEqual (runtime .status ("local" )["owner_id" ],started ["owner_id" ])# attaching took nothing over 1293self .assertEqual (runtime .stop ("local" ,timeout = 12 )["ok" ],True ) 1294self .assertEqual (runtime .status ("local" )["state" ],"stopped" ) 1295 1296def test_a_wrong_or_stale_token_cannot_stop_the_owner (self ): 1297started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 1298self .assertTrue (started ["ok" ]) 1299state = runtime ._read_state ("local" ) 1300wrong_last = "0" if state ["token" ][- 1 ]!= "0" else "1" 1301for bad in ("0" * 64 ,state ["token" ][:- 1 ]+ wrong_last ,"" ,"x" * 10 ): 1302with self .subTest (token = bad [:6 ]): 1303answer = self ._send (state ,bad ,"stop" ) 1304self .assertEqual ((answer ["ok" ],answer ["error" ]), (False ,"unauthorized" )) 1305self .assertEqual (runtime .status ("local" )["instance_id" ],started ["instance_id" ]) 1306self .assertTrue (self ._send (state ,state ["token" ],"status" )["ok" ])# the real token is what authorises 1307 1308def test_a_recorded_pid_of_an_unrelated_live_process_is_never_signalled (self ): 1309victim = subprocess .Popen ([sys .executable ,"-c" ,"import time; time.sleep(120)" ]) 1310try : 1311state_path ,marker = self ._stale_host (victim .pid ) 1312with self .assertRaisesRegex (profiles .ProfileError ,"still present" ): 1313runtime .start ("local" ,wait = 0 ,shutdown_timeout = 2 ) 1314with self .assertRaises (profiles .ProfileError ):# nothing answers on the recorded address 1315runtime .stop ("local" ,timeout = 2 ) 1316self .assertIsNone (victim .poll (),"an unrelated process was stopped" ) 1317self .assertTrue (state_path .exists ()and marker .exists ()) 1318finally : 1319victim .kill () 1320victim .wait (timeout = 10 ) 1321 1322@ unittest . skipUnless ( WINDOWS , "a creation time is recorded with the PID on Windows only" ) 1323def test_a_reused_pid_with_another_creation_time_is_not_the_recorded_child (self ): 1324victim = subprocess .Popen ([sys .executable ,"-c" ,"import time; time.sleep(120)" ]) 1325try : 1326real = runtime .winproc .process_started (victim .pid ) 1327self .assertTrue (runtime ._pid_exists (victim .pid ,real )) 1328self .assertFalse (runtime ._pid_exists (victim .pid ,real + 12345 )) 1329self ._stale_host (victim .pid ,started = real + 12345 )# the number was reused by another process 1330started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 1331self .assertTrue (started ["ok" ])# recovered: it was not the recorded child 1332self .assertIsNone (victim .poll (),"the process that reused the PID was stopped" ) 1333finally : 1334victim .kill () 1335victim .wait (timeout = 10 ) 1336 1337def test_marker_without_creation_time_ignores_a_reused_pid_of_a_foreign_program (self ): 1338# #3488: the marker had no `started`, the number was reused by another program, every load said "still present". 1339child = {"pid" :38552 } 1340with mock .patch .object (runtime ,"WINDOWS" ,True ), \ 1341mock .patch .object (runtime ,"_pid_exists" ,return_value = True ), \ 1342mock .patch .object (runtime .winproc ,"process_image" ,create = True )as image : 1343image .return_value = r"C:\Windows\System32\svchost.exe" 1344self .assertFalse (runtime ._child_present (child )) 1345image .return_value = r"C:\Users\a\AppData\Local\Strata\python\python.exe" 1346self .assertTrue (runtime ._child_present (child )) 1347image .return_value = None # unreadable: keep refusing, never guess 1348self .assertTrue (runtime ._child_present (child )) 1349image .return_value = r"C:\Windows\System32\svchost.exe" 1350self .assertTrue (runtime ._child_present ({"pid" :1 ,"started" :5 }))# a creation time decides by itself 1351 1352def test_a_process_created_after_the_marker_was_written_is_not_the_recorded_child (self ): 1353# 2026-10-22: the app was force-killed, its marker had no creation time, the number now belonged to another Python program, and every 1354# load said "lost host child is still present" until the marker was deleted by hand. The child was started BEFORE its marker was written. 1355child = {"pid" :4242 } 1356with mock .patch .object (runtime ,"_pid_exists" ,return_value = True ), \ 1357mock .patch .object (runtime .winproc ,"process_image" ,create = True ,return_value = "C:\\Python\\python.exe" ), \ 1358mock .patch .object (runtime .procs ,"started_epoch" )as created : 1359created .return_value = 1000.0 + 60 1360self .assertFalse (runtime ._child_present (child ,written = 1000.0 ),"created a minute after the marker: another process" ) 1361created .return_value = 1000.0 - 5 1362self .assertTrue (runtime ._child_present (child ,written = 1000.0 ),"created before the marker: could be the child, keep refusing" ) 1363created .return_value = 1000.0 + 1.5 1364self .assertTrue (runtime ._child_present (child ,written = 1000.0 ),"inside the clock slack: keep refusing" ) 1365created .return_value = None 1366self .assertTrue (runtime ._child_present (child ,written = 1000.0 ),"creation time unreadable: never guess" ) 1367created .return_value = 1000.0 + 60 1368self .assertTrue (runtime ._child_present ({"pid" :4242 ,"started" :7 },written = 1000.0 )is True ,"a recorded creation time decides by itself" ) 1369self .assertTrue (runtime ._child_present (child ),"no marker time: unchanged" ) 1370 1371def test_a_marker_left_by_a_killed_app_is_cleaned_up_when_its_number_belongs_to_a_later_program (self ): 1372victim = subprocess .Popen ([sys .executable ,"-c" ,"import time; time.sleep(120)" ]) 1373try : 1374state_path ,marker = self ._stale_host (victim .pid )# a marker with no creation time (Windows could not read it) 1375old = time .time ()- 3600 1376os .utime (marker , (old ,old ))# written an hour ago: the victim started after it 1377started = runtime .start ("local" ,wait = 60 ,shutdown_timeout = 2 ) 1378self .assertTrue (started ["ok" ],started ) 1379self .assertFalse (marker .exists (),"the stale marker was removed" ) 1380self .assertIsNone (victim .poll (),"the program that reused the number was left alone" ) 1381finally : 1382victim .kill () 1383victim .wait (timeout = 10 ) 1384 1385def test_started_epoch_reads_a_live_process_and_nothing_for_a_dead_number (self ): 1386victim = subprocess .Popen ([sys .executable ,"-c" ,"import time; time.sleep(120)" ]) 1387try : 1388now = time .time () 1389created = procs .started_epoch (victim .pid ) 1390self .assertIsNotNone (created ) 1391self .assertLess (abs (created - now ),60 ) 1392finally : 1393victim .kill () 1394victim .wait (timeout = 10 ) 1395self .assertIsNone (procs .started_epoch (victim .pid )) 1396self .assertIsNone (procs .started_epoch (0 )) 1397self .assertIsNone (procs .started_epoch (- 5 )) 1398 1399@ unittest . skipUnless ( WINDOWS , "os.kill(pid, 0) ends a process on Windows; liveness is a handle query" ) 1400def test_liveness_check_does_not_end_the_process_it_asks_about (self ): 1401victim = subprocess .Popen ([sys .executable ,"-c" ,"import time; time.sleep(120)" ]) 1402try : 1403for _ in range (5 ): 1404self .assertTrue (runtime ._pid_exists (victim .pid )) 1405self .assertIsNone (victim .poll ()) 1406finally : 1407victim .kill () 1408victim .wait (timeout = 10 ) 1409self .assertFalse (runtime ._pid_exists (victim .pid )) 1410 1411@ unittest . skipUnless ( WINDOWS , "ACLs stand in for mode 0700 on Windows" ) 1412def test_runtime_directory_is_owner_only_and_a_shared_one_is_refused (self ): 1413from strata_control import private_files 1414directory = runtime .runtime_dir () 1415self .assertTrue (private_files .is_private (directory )) 1416shared = Path (self .temp .name )/ "shared-runtime" 1417shared .mkdir () 1418done = subprocess .run (["icacls" ,str (shared ),"/grant" ,"*S-1-1-0:(OI)(CI)R" ],capture_output = True ) 1419if done .returncode != 0 : 1420self .skipTest ("icacls could not widen the test directory" ) 1421with mock .patch .dict (os .environ , {"STRATA_RUNTIME_DIR" :str (shared )}): 1422# a folder that names Everyone is the user's own state folder: it is locked down once and used (never a stop) 1423self .assertEqual (runtime .runtime_dir (),shared ) 1424self .assertTrue (private_files .is_unshared (shared )) 1425again = Path (self .temp .name )/ "shared-runtime-2" 1426again .mkdir () 1427subprocess .run (["icacls" ,str (again ),"/grant" ,"*S-1-1-0:(OI)(CI)R" ],capture_output = True ) 1428with mock .patch .dict (os .environ , {"STRATA_RUNTIME_DIR" :str (again )}), \ 1429mock .patch .object (private_files ,"restrict_to_current_user" ), \ 1430mock .patch .object (private_files ,"repair_access" ,return_value = False ): 1431# when the lock-down does not happen it still refuses, in plain words and naming who can open it 1432with self .assertRaisesRegex (profiles .ProfileError ,"Everyone" ): 1433runtime .runtime_dir () 1434 1435def test_ready_pid_may_be_a_child_of_the_launcher_on_windows_only (self ): 1436# #3683: a Windows venv's python.exe starts the real interpreter as its child, so the server that writes the ready file 1437# is one process below the pid the host started. It must still match; a stranger or a distant process must not. 1438parents = {200 :100 ,300 :200 ,400 :300 ,500 :400 } 1439with mock .patch .object (runtime .procs ,"parent_of" ,side_effect = lambda pid :parents .get (pid )): 1440with mock .patch .object (runtime ,"WINDOWS" ,True ): 1441self .assertTrue (runtime ._ready_pid_is_child (100 ,100 )) 1442self .assertTrue (runtime ._ready_pid_is_child (200 ,100 )) 1443self .assertTrue (runtime ._ready_pid_is_child (300 ,100 )) 1444self .assertTrue (runtime ._ready_pid_is_child (400 ,100 )) 1445self .assertFalse (runtime ._ready_pid_is_child (500 ,100 ))# too far below 1446self .assertFalse (runtime ._ready_pid_is_child (999 ,100 ))# unrelated 1447self .assertFalse (runtime ._ready_pid_is_child (None ,100 )) 1448self .assertFalse (runtime ._ready_pid_is_child ("200" ,100 )) 1449self .assertFalse (runtime ._ready_pid_is_child (0 ,100 )) 1450with mock .patch .object (runtime ,"WINDOWS" ,False ): 1451self .assertTrue (runtime ._ready_pid_is_child (100 ,100 )) 1452self .assertFalse (runtime ._ready_pid_is_child (200 ,100 ))# POSIX has no launcher in between 1453 1454@ unittest . skipUnless ( WINDOWS , "the venv launcher is a Windows thing" ) 1455def test_server_started_through_a_launcher_process_becomes_ready (self ): 1456launcher = self .root / "launcher.cmd" 1457launcher .write_bytes (f'@echo off\r\n" { sys . executable } " %*\r\n' .encode ()) 1458host = runtime .Host ("local" ,shutdown_timeout = 2 ,startup_wait = 20 ) 1459plan ,args ,source ,original = host ._plan () 1460with mock .patch .object (sys ,"executable" ,str (launcher )): 1461host ._launch (args ,source ,original ,plan ["profile_revision" ]) 1462try : 1463result = host ._wait_ready (30 ) 1464self .assertTrue (result ["ok" ],result ) 1465self .assertTrue (result ["generation_ready" ]) 1466ready = json .loads (host .ready_path .read_text (encoding = "utf-8" )) 1467self .assertNotEqual (ready ["pid" ],host .child .pid )# the server is below the launcher 1468finally : 1469host ._stop_child () 1470 1471def test_a_ready_file_that_is_not_ours_is_named_in_the_status_phase (self ): 1472host = runtime .Host ("local" ,shutdown_timeout = 2 ,startup_wait = 10 ) 1473host .child = mock .Mock (pid = 111 ) 1474host .child .poll .return_value = None 1475host .ready_path = self .root / "ready.json" 1476host .ready_path .write_text (json .dumps ({"pid" :222 ,"instance_id" :"a" * 32 }),encoding = "utf-8" ) 1477with mock .patch .object (runtime .procs ,"parent_of" ,return_value = None ): 1478self .assertEqual (host ._status ()["phase" ],"ready_file_not_matched" ) 1479host .ready_path .unlink () 1480self .assertEqual (host ._status ()["phase" ],"loading" ) 1481 1482def test_exclusive_lease_waits_for_shared_holders_and_shared_holders_coexist (self ): 1483first = runtime .acquire_activity_lease (shared = True ) 1484second = runtime .acquire_activity_lease (shared = True ) 1485try : 1486with self .assertRaisesRegex (profiles .ProfileError ,"engine lease" ): 1487runtime .acquire_activity_lease (shared = False ) 1488finally : 1489for descriptor in (first ,second ): 1490runtime ._unlock_file (descriptor ) 1491os .close (descriptor ) 1492exclusive = runtime .acquire_activity_lease (shared = False ) 1493try : 1494with self .assertRaisesRegex (profiles .ProfileError ,"engine lease" ): 1495runtime .acquire_activity_lease (shared = True ) 1496finally : 1497runtime ._unlock_file (exclusive ) 1498os .close (exclusive ) 1499 1500 1501class StartWaitLimit (unittest .TestCase ): 1502def setUp (self ): 1503# A start writes an operation record before the engine runs, so these tests keep their records (and any profile 1504# lookup) in a scratch folder rather than in the person's own state. 1505temp = tempfile .TemporaryDirectory (prefix = "strata-start-wait-test-" ) 1506self .addCleanup (temp .cleanup ) 1507root = Path (temp .name ) 1508 (root / "profiles" ).mkdir () 1509env = mock .patch .dict (os .environ , {"STRATA_PROFILE_DIR" :str (root / "profiles" ), 1510"STRATA_RUNTIME_DIR" :str (root / "runtime" )}) 1511env .start () 1512self .addCleanup (env .stop ) 1513 1514def test_a_start_may_wait_up_to_thirty_minutes_for_a_big_model (self ):# #3949 1515from strata_control import runtime as rt ,profiles as pr 1516self .assertEqual (rt .MAX_START_WAIT ,1800 ) 1517with self .assertRaisesRegex (pr .ProfileError ,"start wait must be 0..1800" ): 1518rt .start ("x" ,wait = 1801 ) 1519with mock .patch .object (rt ,"_name" ,side_effect = pr .ProfileError ("reached" )): 1520with self .assertRaisesRegex (pr .ProfileError ,"reached" ): 1521rt .start ("x" ,wait = 1800 ) 1522 1523def test_a_long_start_wait_reaches_the_runtime_through_the_cli (self ):# #3459 #4191 1524# The desktop app starts models through `strata runtime start --wait`, and that wait is checked three times before 1525# the engine is reached: by management, by the operation record, and by the runtime itself. When only the runtime's 1526# ceiling was raised (#3949), a long start died at each of the first two with 1527# "start wait must be finite seconds in 0..600" / "direct runtime intent has an invalid timeout". So this walks the 1528# whole way with only the engine itself faked: any layer that still carries the old 600 s shows up here. 1529from strata_control import journal as jn ,management as mg ,profiles as pr ,runtime as rt 1530revision = "0123456789abcdef" 1531for wait in (300 ,600 ,601 ,rt .MAX_START_WAIT ): 1532reached = {} 1533with mock .patch .object (rt ,"_name" ,lambda name :name ), \ 1534mock .patch .object (mg .profiles ,"load" ,lambda name : ("src" ,revision )), \ 1535mock .patch .object (rt ,"start" ,lambda name ,** kw : (reached .update (kw ), 1536 {"ok" :True ,"state" :"ready" ,"profile" :name })[1 ]): 1537result = mg .runtime_action ("start" ,"demo" ,wait = wait ,shutdown_timeout = 15 ) 1538self .assertEqual (result ["state" ],"ready" ) 1539self .assertEqual (reached ["wait" ],float (wait ), 1540f"a start asked for { wait } s did not reach runtime.start with it" ) 1541 1542def test_a_start_wait_above_the_runtime_ceiling_is_named_by_the_runtime (self ):# #3459 #4191 1543from strata_control import management as mg ,profiles as pr ,runtime as rt 1544revision = "0123456789abcdef" 1545with mock .patch .object (rt ,"_name" ,lambda name :name ), \ 1546mock .patch .object (mg .profiles ,"load" ,lambda name : ("src" ,revision )): 1547with self .assertRaisesRegex (pr .ProfileError ,f"start wait must be finite seconds in 0.. { rt . MAX_START_WAIT } " ): 1548mg .runtime_action ("start" ,"demo" ,wait = rt .MAX_START_WAIT + 1 ,shutdown_timeout = 15 ) 1549with self .assertRaisesRegex (pr .ProfileError ,f"startup wait must be finite seconds in 1.. { rt . MAX_START_WAIT } " ): 1550mg .runtime_action ("restart" ,"demo" ,startup_wait = rt .MAX_START_WAIT + 1 , 1551if_owner_id = "0" * 32 ,if_instance_id = "0" * 32 ) 1552 1553def test_the_operation_record_takes_the_runtimes_own_start_ceiling (self ): 1554# The record is written before the start runs, so a ceiling kept here would stop a long wait no matter what the 1555# two validators above allow. Waits that are not a start or a restart keep their own 600 s. 1556from strata_control import journal as jn ,profiles as pr ,runtime as rt 1557for kind ,intent ,allowed in ( 1558 ("runtime.start" , {"wait_s" :rt .MAX_START_WAIT ,"shutdown_timeout_s" :15 },True ), 1559 ("runtime.start" , {"wait_s" :rt .MAX_START_WAIT + 1 ,"shutdown_timeout_s" :15 },False ), 1560 ("runtime.restart" , {"wait_s" :1000 ,"startup_wait_s" :rt .MAX_START_WAIT , 1561"expected_profile_revision" :"0" * 16 , 1562"expected_owner_id" :"0" * 32 ,"expected_instance_id" :"0" * 32 , 1563"allow_source_switch" :False ,"allow_source_migration" :False , 1564"expected_source_sha256" :"0" * 64 },True ), 1565 ("runtime.stop" , {"wait_s" :rt .MAX_START_WAIT },False ), 1566 ("runtime.verify" , {"wait_s" :rt .MAX_START_WAIT ,"load" :False },False )): 1567with self .subTest (kind = kind ,wait = intent ["wait_s" ]): 1568if allowed : 1569jn ._validate_direct_intent (kind ,dict (intent )) 1570else : 1571with self .assertRaisesRegex (pr .ProfileError ,"invalid timeout" ): 1572jn ._validate_direct_intent (kind ,dict (intent )) 1573 1574 1575if __name__ == "__main__" : 1576unittest .main ()