okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
998077b33
main
1"""Local owner-controlled supervisor for one saved Strata serving profile. 2 3The supervisor holds the Popen handle for the server it started. A client never 4sends a signal to a PID found in a ready file. The control channel and token live 5in an owner-private directory. 6 7POSIX: an owner-private AF_UNIX socket, flock leases, SIGTERM to the server's own 8process group. Windows: a loopback-only TCP listener authorised by the 256-bit 9token (strata_control/owner_transport.py), byte-range leases (winproc.py), a 10protected one-entry ACL on the state directory, and a kill-on-close job object 11around the server tree. A PID in a state file is never signalled: it is only 12compared (with its creation time on Windows) to decide whether the recorded 13child is still there. 14""" 15 16from __future__import annotations 17 18from strata_control .private_files import private_mkdir as _private_mkdir 19from strata_control .childenv import quiet_crash_env 20import argparse 21import errno 22import hashlib 23import json 24import os 25import re 26import secrets 27import signal 28import socket 29import stat 30import subprocess 31import sys 32import threading 33import time 34import uuid 35from pathlib import Path 36 37try : 38import fcntl 39except ImportError :# Windows has no qualified owner transport yet. 40fcntl = None 41 42from strata_control import owner_transport ,paths ,posix_owner ,private_files ,procs ,profiles ,readiness ,winproc 43from serve import launch_identity 44from strata_control .profiles import ProfileError 45 46 47MAX_MESSAGE = 64 * 1024 48ROOT = Path (__file__ ).resolve ().parents [1 ] 49WINDOWS = os .name == "nt" 50_STARTED_HOSTS :dict [str ,subprocess .Popen ]= {} 51 52 53def _is_private (details :os .stat_result ,path :Path )-> bool : 54"""Owner-only: POSIX owner and no group/other bits; Windows an ACL that shuts out every other account.""" 55if WINDOWS : 56try : 57return private_files .is_unshared (path ) 58except OSError : 59return False 60return not posix_owner .owner_only_wrong (path ,details ) 61 62 63def _lock_file (descriptor :int ,* ,exclusive :bool )-> bool : 64"""Take a lease without waiting: True when taken, False when another holder has it.""" 65if WINDOWS : 66return winproc .try_lock (descriptor ,exclusive = exclusive ) 67try : 68fcntl .flock (descriptor , (fcntl .LOCK_EX if exclusive else fcntl .LOCK_SH )| fcntl .LOCK_NB ) 69except OSError as exc : 70if exc .errno in (errno .EWOULDBLOCK ,errno .EAGAIN ): 71return False 72raise 73return True 74 75 76def _unlock_file (descriptor :int )-> None : 77"""Windows releases a lock only some time after the handle closes: release it now. POSIX closes.""" 78if WINDOWS : 79winproc .unlock (descriptor ) 80 81 82def _supported ()-> None : 83"""Refuse only when no transport exists at all. 84 85POSIX uses an owner-private ``AF_UNIX`` socket. Windows uses a loopback-only TCP listener whose 86authority rests on the 256-bit control token plus a ``0700`` state directory, because the Python 87standard library cannot create a named pipe with a security descriptor; the difference is 88recorded in ``owner_transport`` and in ``history/docs/work/IMPLEMENTATION_STATUS.md`` rather than being 89presented as equivalent. Anything else is refused. 90""" 91if os .name == "nt" or (os .name == "posix" and hasattr (socket ,"AF_UNIX" )): 92return 93raise ProfileError ("managed runtime has no qualified local control transport on this platform" ,5 ) 94 95 96def _name (value :str )-> str : 97if not profiles .PROFILE_ID .fullmatch (value ): 98raise ProfileError ("runtime commands require a saved profile name" ) 99return value 100 101 102def runtime_dir ()-> Path : 103_supported () 104override = os .environ .get ("STRATA_RUNTIME_DIR" ) 105if override : 106base = Path (override ).expanduser () 107else : 108base = paths .state_base ()/ "runtime" 109if not base .is_absolute (): 110raise ProfileError ("STRATA_RUNTIME_DIR must be absolute" ) 111existed = base .exists () 112_private_mkdir (base ,parents = True ,exist_ok = True ) 113details = base .lstat () 114if WINDOWS and stat .S_ISDIR (details .st_mode ): 115if not private_files .volume_has_acls (base ):# exFAT / FAT: no permissions exist, so there is nothing to check 116_warn_no_acls (base ) 117return base 118if not existed : 119_make_private (base )# no mode bits on NTFS: a protected ACL 120if not _is_private (details ,base ): 121# A folder that was there before (made by an elevated install, an older version, or with the parent's ACL inherited) can 122# name other accounts. It is the user's own state folder: take that away instead of stopping the launch, then check again. 123_make_private (base ) 124try : 125details = base .lstat () 126except OSError : 127pass 128if not stat .S_ISDIR (details .st_mode )or not _is_private (details ,base ): 129raise ProfileError (_not_private_message (base ),5 ) 130return base 131 132 133def _make_private (base :Path )-> None : 134"""Windows: a protected ACL naming this user; where that is refused (a folder made by an elevated run), take ownership first.""" 135try : 136private_files .restrict_to_current_user (base ,directory = True ) 137except OSError : 138pass 139if _is_private (None ,base ):# type: ignore[arg-type] - details are not used on Windows 140return 141try : 142private_files .repair_access (base ,tree = False ) 143except OSError : 144pass 145 146 147_NO_ACL_WARNED :set [str ]= set () 148 149 150def _warn_no_acls (base :Path )-> None : 151if str (base )not in _NO_ACL_WARNED : 152_NO_ACL_WARNED .add (str (base )) 153f"[strata] { base } is on a drive that has no file permissions (FAT or exFAT), so other accounts on this PC could " 154f"read what Strata keeps there. Use a drive formatted as NTFS if that matters." ,file = sys .stderr ,flush = True ) 155 156 157def _not_private_message (base :Path )-> str : 158if WINDOWS : 159try : 160names = private_files .who_can_reach (base )if base .is_dir ()else [] 161readable = True 162except OSError : 163names ,readable = [],False 164if not readable : 165return (f"Strata cannot read the permissions of { base } , the folder where it keeps its running state. Run Strata once as " 166f"yourself (not as administrator), or delete that folder: Strata makes a private one again." ) 167who = ", " .join (names )if names else "other accounts" 168return (f"Strata keeps its running state in { base } , and { who } can open that folder. Strata could not change that. " 169f"Right-click the folder, choose Properties > Security, and remove those accounts (or delete the folder: Strata " 170f"makes a private one again)." ) 171return "runtime directory must be owner-only (mode 0700)" 172 173 174def acquire_activity_lease (* ,shared :bool )-> int : 175"""Let managed hosts coexist while excluding a local calibration run.""" 176directory = runtime_dir () 177flags = os .O_RDWR | os .O_CREAT | getattr (os ,"O_NOFOLLOW" ,0 ) 178try : 179descriptor = os .open (directory / ".activity.lock" ,flags ,0o600 ) 180details = os .fstat (descriptor ) 181if not stat .S_ISREG (details .st_mode )or not _is_private (details ,directory / ".activity.lock" ): 182raise ProfileError ("runtime activity lock must be owner-only" ,5 ) 183if not _lock_file (descriptor ,exclusive =not shared ): 184raise ProfileError ("a managed runtime or calibration owns the local engine lease" ,6 ) 185return descriptor 186except BaseException : 187if "descriptor" in locals (): 188os .close (descriptor ) 189raise 190 191 192def active_managed_instances ()-> list [dict ]: 193"""Inspect private owner records, including stale or uncertain instances.""" 194directory = runtime_dir () 195names = [path .stem for path in directory .glob ("*.json" )if profiles .PROFILE_ID .fullmatch (path .stem )] 196if len (names )> 64 : 197raise ProfileError ("too many managed runtime records to verify exclusive access" ,6 ) 198active = [] 199for name in names : 200current = status (name ) 201if current .get ("state" )!= "stopped" : 202active .append ({"profile" :name ,"state" :current .get ("state" ,"unknown" )}) 203return active 204 205 206def _paths (name :str )-> tuple [Path ,Path ,Path ]: 207directory = runtime_dir () 208digest = hashlib .sha256 ((str (directory )+ "\0" + name ).encode ("utf-8" )).hexdigest ()[:16 ] 209# The address form is the transport's business: POSIX gets a private socket path (with the 210# short-path fallback for a long home directory), Windows gets its loopback placeholder, which 211# the listener replaces with the real port when it binds. 212address = owner_transport .address_for (directory ,name ) 213return directory / f" { name } .json" ,address ,directory / f" { name } .host.log" 214 215 216def _read_state (name :str ,pending_ok :bool = False )-> dict | None : 217"""The owner's state file, or None when there is none. `pending_ok` (a start waiting for the owner it just launched): an empty or half-written 218file is that owner still writing its state (it creates the file as its lease, then writes it), so it reads as not there yet instead of 219unreadable (#5601: the test start of an update failed on a 0-byte read that was 191 bytes 100 ms later).""" 220path ,socket_path ,_ = _paths (_name (name )) 221try : 222details = path .lstat () 223except FileNotFoundError : 224return None 225if pending_ok and stat .S_ISREG (details .st_mode )and details .st_size == 0 : 226return None 227if not stat .S_ISREG (details .st_mode )or not _is_private (details ,path )or details .st_size > 16 * 1024 : 228raise ProfileError ("runtime state file is not private or is invalid" ,5 ) 229try : 230state = json .loads (path .read_text (encoding = "utf-8" )) 231except FileNotFoundError : 232return None # the owner left between the look and the read: there is no state any more 233except (OSError ,UnicodeError ,ValueError ): 234if pending_ok : 235return None 236raise ProfileError ("runtime state file is unreadable" ,5 )from None 237# POSIX: the address is the one derived from the profile. Windows: the port is chosen when the owner binds, so 238# the state file carries it, and the only address a client may be sent to is a loopback port. 239address_ok = bool (re .fullmatch (r"tcp:127\.0\.0\.1:[1-9][0-9]{0,4}" ,str (state .get ("socket" ,"" )))) \ 240if WINDOWS and isinstance (state ,dict )else (isinstance (state ,dict )and state .get ("socket" )== socket_path ) 241if not isinstance (state ,dict )or state .get ("schema_version" )!= 1 or state .get ("profile" )!= name or \ 242not address_ok or not isinstance (state .get ("token" ),str )or \ 243not re .fullmatch (r"[0-9a-f]{64}" ,state ["token" ]): 244raise ProfileError ("runtime state file has an unsupported shape" ,5 ) 245return state 246 247 248def _child_marker (name :str ,token :str )-> Path : 249return runtime_dir ()/ f" { name } - { token } .child.json" 250 251 252def _pid_exists (pid :int ,started :int | None = None )-> bool : 253"""Whether the recorded child is still there. Never signals: on Windows `os.kill(pid, 0)` would END the process, 254so liveness is a handle query, and `started` (the creation time recorded with the PID) tells the recorded 255process from a later one that reused the number.""" 256if WINDOWS : 257return winproc .pid_alive (pid ,started ) 258try : 259os .kill (pid ,0 )# Liveness check only; never signal a PID from saved state. 260except ProcessLookupError : 261return False 262except PermissionError : 263return True 264return True 265 266 267_MARKER_SLACK = 2.0 # seconds: the child starts before its marker is written; this much of clock rounding is allowed 268 269 270def _child_present (child :dict ,written :float | None = None )-> bool : 271"""Whether the child recorded in an owner marker is still there. A marker without a creation time (Windows could not 272read it when the child started) cannot tell the recorded server from a later process that reused the number, so 273a live process that is not a Python or Strata executable is a reused number: the child is gone (#3488). 274 275`written` is when the marker was written (its file time). The child was started before that, so a process that was created 276AFTER it cannot be the child, whatever its image: the number was reused. This is what clears a marker left by a force-killed app 277when the number now belongs to another Python program (2026-10-22: every load said "still present", and removing the marker by 278hand was the only way out).""" 279started = child .get ("started" )if type (child .get ("started" ))is int else None 280if not _pid_exists (child ["pid" ],started ): 281return False 282if started is None and written is not None : 283created = procs .started_epoch (child ["pid" ]) 284if created is not None and created > written + _MARKER_SLACK : 285return False 286if WINDOWS and started is None : 287image = winproc .process_image (child ["pid" ]) 288if image is not None : 289name = os .path .basename (image ).lower () 290if "python" not in name and "strata" not in name : 291return False 292return True 293 294 295def _host_lease_active (name :str )-> bool : 296path ,_ ,_ = _paths (name ) 297descriptor = os .open (path ,os .O_RDONLY | getattr (os ,"O_NOFOLLOW" ,0 )) 298try : 299if not _lock_file (descriptor ,exclusive = True ): 300return True 301_unlock_file (descriptor ) 302return False 303finally : 304os .close (descriptor ) 305 306 307def _recover_stale (name :str ,* ,wait :float )-> bool : 308"""Reclaim private state only after the host lease and owned child are gone.""" 309state = _read_state (name ) 310if state is None : 311return False 312state_path ,socket_path ,_ = _paths (name ) 313flags = os .O_RDONLY | getattr (os ,"O_NOFOLLOW" ,0 ) 314descriptor = os .open (state_path ,flags ) 315try : 316if os .fstat (descriptor ).st_ino != state_path .lstat ().st_ino : 317raise ProfileError ("runtime state changed during recovery" ,6 ) 318if not _lock_file (descriptor ,exclusive = True ): 319raise ProfileError ("this profile already has a live managed runtime" ,6 ) 320marker = _child_marker (name ,state ["token" ]) 321try : 322details = marker .lstat () 323if not stat .S_ISREG (details .st_mode )or not _is_private (details ,marker )or details .st_size > 4096 : 324raise ValueError ("invalid owner marker" ) 325child = json .loads (marker .read_text (encoding = "utf-8" )) 326except (OSError ,ValueError ): 327raise ProfileError ("lost host has no valid child ownership record; inspect before recovery" ,6 )from None 328if not isinstance (child ,dict )or child .get ("host_token" )!= state ["token" ]: 329raise ProfileError ("lost host child launch is unverified; inspect before recovery" ,6 ) 330# #4250: the owner writes {"phase": "no_child"} before it publishes its state, and "launching" before it starts a server. A host 331# lost in between has no server by that exact record (this host's token, nothing else in it); a missing or other record proves nothing. 332prelaunch = child .get ("phase" )== "no_child" 333if prelaunch : 334if set (child )!= {"host_token" ,"phase" }: 335raise ProfileError ("lost host child launch is unverified; inspect before recovery" ,6 ) 336else : 337if child .get ("phase" )!= "owned" or type (child .get ("pid" ))is not int or child ["pid" ]<= 0 : 338raise ProfileError ("lost host child launch is unverified; inspect before recovery" ,6 ) 339deadline = time .monotonic ()+ min (45.0 ,max (5.0 ,wait )) 340written = details .st_mtime 341while _child_present (child ,written )and time .monotonic ()< deadline : 342time .sleep (0.1 ) 343if _child_present (child ,written ): 344raise ProfileError ("lost host child is still present; retry after it exits" ,6 ) 345if not isinstance (child .get ("ready" ),str ): 346raise ProfileError ("lost host ready path is invalid; inspect before recovery" ,6 ) 347ready = Path (child ["ready" ]) 348if ready .parent != runtime_dir ()or not ready .name .startswith (name + "-" )or \ 349not ready .name .endswith (".ready.json" ): 350raise ProfileError ("lost host ready path is invalid; inspect before recovery" ,6 ) 351try : 352details = ready .lstat () 353if not stat .S_ISREG (details .st_mode )or not _is_private (details ,ready ): 354raise ProfileError ("lost host ready file is invalid; inspect before recovery" ,6 ) 355ready .unlink () 356except FileNotFoundError : 357pass 358if not owner_transport .WINDOWS : 359# POSIX: the endpoint is a filesystem socket, so it can be inspected directly. A socket 360# that is still accepting means a live owner, and nothing may be recovered over it. 361try : 362details = Path (socket_path ).lstat () 363if not stat .S_ISSOCK (details .st_mode )or details .st_uid != os .getuid (): 364raise ProfileError ("lost host socket is invalid; inspect before recovery" ,6 ) 365with socket .socket (socket .AF_UNIX ,socket .SOCK_STREAM )as probe : 366probe .settimeout (0.2 ) 367try : 368probe .connect (str (socket_path )) 369except OSError as exc : 370if exc .errno not in (errno .ECONNREFUSED ,errno .ENOENT ): 371raise ProfileError ( 372"lost host socket cannot be verified; inspect before recovery" ,6 )from None 373else : 374raise ProfileError ( 375"a control listener still owns this socket; inspect before recovery" ,6 ) 376Path (socket_path ).unlink () 377except FileNotFoundError : 378pass 379# Windows: the endpoint is a loopback port chosen at bind time, so there is no artifact to 380# inspect and none to clean up. Recovery rests on the state file, the owner pid and the 381# token, all of which the caller has already validated. 382snapshots = list (runtime_dir ().glob (f" { name } - { state [ 'token' ] } -*.rollback.json" )) 383if prelaunch and snapshots : 384raise ProfileError ("lost host prelaunch state has config snapshots; inspect before recovery" ,6 ) 385if len (snapshots )> 64 : 386raise ProfileError ("too many lost-host config snapshots; inspect before recovery" ,6 ) 387for snapshot in snapshots : 388details = snapshot .lstat () 389if not stat .S_ISREG (details .st_mode )or not _is_private (details ,snapshot ): 390raise ProfileError ("lost-host config snapshot is not private; inspect before recovery" ,6 ) 391snapshot .unlink () 392marker .unlink () 393if WINDOWS :# an open file cannot be deleted on Windows: release the lease first 394_unlock_file (descriptor ) 395os .close (descriptor ) 396descriptor = - 1 397state_path .unlink () 398return True 399finally : 400if descriptor >= 0 : 401os .close (descriptor ) 402 403 404def _write_new (path :Path ,data :bytes )-> int : 405descriptor = os .open (path ,os .O_WRONLY | os .O_CREAT | os .O_EXCL ,0o600 ) 406try : 407# Keep this lease open in the owner host. The kernel releases it even 408# after SIGKILL, unlike a PID file or a stale Unix socket. 409if not _lock_file (descriptor ,exclusive = True ): 410raise OSError (errno .EWOULDBLOCK ,"the runtime lease is held" ) 411with os .fdopen (os .dup (descriptor ),"wb" )as stream : 412stream .write (data ) 413stream .flush () 414os .fsync (descriptor ) 415return descriptor 416except BaseException : 417os .close (descriptor ) 418path .unlink (missing_ok = True ) 419raise 420 421 422def _rpc (name :str ,command :str ,* ,timeout :float = 5 ,params :dict | None = None )-> dict : 423state = _read_state (name ) 424if state is None : 425raise ProfileError ("runtime is not managed or is stopped" ,3 ) 426request = {"token" :state ["token" ],"command" :command } 427if params : 428request .update (params ) 429raw = (json .dumps (request )+ "\n" ).encode ("utf-8" ) 430# The transport decides the address family: a private POSIX socket, or the loopback listener 431# on Windows. The token in `raw` is what authorises the request either way. 432try : 433client = owner_transport .connect (state ["socket" ],timeout = timeout ) 434except OSError :# nothing listens there any more (a lost owner), or it did not answer in time 435raise ProfileError ("runtime control is unavailable; inspect the private host log" ,3 )from None 436try : 437try : 438client .sendall (raw ) 439answer = bytearray () 440while len (answer )<= MAX_MESSAGE : 441chunk = client .recv (4096 ) 442if not chunk : 443break 444answer .extend (chunk ) 445if b"\n" in chunk : 446break 447except socket .timeout : 448raise ProfileError ("runtime operation wait expired; inspect runtime status" ,8 )from None 449except OSError : 450raise ProfileError ("runtime control is unavailable; inspect the private host log" ,3 )from None 451finally : 452client .close () 453if len (answer )> MAX_MESSAGE : 454raise ProfileError ("runtime control response is too large" ,6 ) 455try : 456result = json .loads (answer .split (b"\n" ,1 )[0 ]) 457except (ValueError ,UnicodeError ): 458raise ProfileError ("runtime control returned an invalid response" ,6 )from None 459if not isinstance (result ,dict )or type (result .get ("ok" ))is not bool : 460raise ProfileError ("runtime control returned an invalid response" ,6 ) 461return result 462 463 464def status (name :str )-> dict : 465state = _read_state (name ) 466if state is None : 467return {"ok" :True ,"profile" :name ,"state" :"stopped" } 468try : 469active = _host_lease_active (name ) 470except FileNotFoundError : 471return {"ok" :True ,"profile" :name ,"state" :"stopped" } 472if not active : 473return {"ok" :False ,"profile" :name ,"state" :"stale" ,"error" :"owner_host_lost" , 474"next_action" :"runtime start will recover after the owned child exits" ,"exit_code" :6 } 475return _rpc (name ,"status" ) 476 477 478def _start_candidate (name :str )-> tuple [dict ,str ]: 479from strata_cli .cli import _launch_plan 480plan ,_ = _launch_plan (name ) 481digest = hashlib .sha256 (Path (plan ["source_config" ]).read_bytes ()).hexdigest () 482return plan ,digest 483 484 485def _engine_preflight (plan :dict )-> None : 486"""Refuse a start before any process exists when the run config names its engine as a component and the package for this 487PC is missing or fails its integrity check (every file's SHA-256). The server checks again when it starts the engine; this 488check makes the refusal the first thing the user sees, with the file named, instead of a log line behind 'server_exited'.""" 489try : 490cfg = json .loads (Path (plan ["source_config" ]).read_text (encoding = "utf-8-sig" )) 491except (OSError ,ValueError ,KeyError ,TypeError ): 492return 493if not isinstance (cfg ,dict ): 494return 495from strata_control import engine_component 496if not engine_component .is_reference (cfg .get ("exe" )): 497return 498try : 499engine_component .expand (cfg ["exe" ],cfg ) 500except engine_component .EngineMissing as exc : 501raise ProfileError (str (exc ),exc .exit_code )from None 502 503 504def _ready_pid_is_child (ready_pid ,child_pid :int )-> bool : 505"""Is the process named in the ready file the one this host started? 506 507Normally the pids are equal. A Windows venv (the python.exe of a source checkout's .venv) starts its real interpreter as a 508CHILD of the launcher it was given, so the server that writes the ready file is one process below the pid ``Popen`` returned 509(#3683: the staged engine was ready, this check never matched, and the start waited out its whole deadline). Only on Windows, 510and only for a process that sits within three parents of the process this host started, so another process cannot pass.""" 511if type (ready_pid )is not int or ready_pid <= 0 : 512return False 513if ready_pid == child_pid : 514return True 515if not WINDOWS : 516return False 517current = ready_pid 518for _ in range (3 ): 519parent = procs .parent_of (current ) 520if parent is None or parent <= 0 : 521return False 522if parent == child_pid : 523return True 524current = parent 525return False 526 527 528def _check_start_candidate (name :str ,expected_profile_revision :str | None , 529expected_source_sha256 :str | None )-> tuple [dict ,str ]: 530plan ,digest = _start_candidate (name ) 531if expected_profile_revision is not None and plan ["profile_revision" ]!= expected_profile_revision : 532raise ProfileError ("profile_changed_after_start_plan" ,6 ) 533if expected_source_sha256 is not None and digest != expected_source_sha256 : 534raise ProfileError ("source_changed_after_start_plan" ,6 ) 535return plan ,digest 536 537 538def _repair_config_paths (name :str )-> tuple [str | None ,str | None ]: 539"""Before a start: every path of the saved run configs that names a version folder of Strata's own that an update removed (the Control bundle 540that ran setup: cwd, --expert-profile; an engine package: the picture reader, library folders) is pointed at the current 541version and written once (strata_control/cfg_paths.py; the same resolver the config reader applies in memory). One line of what it did goes to 542the profile's host log. Returns (the profile's own run config digest before, after) when it changed that file, for a caller that planned the 543start on the old digest. A path that exists in no current version stops the start with the file named.""" 544try : 545from strata_control import cfg_paths 546profile ,_ = profiles .load (name ) 547own = Path (profile ["source_config" ]) 548before = hashlib .sha256 (own .read_bytes ()).hexdigest () 549configs = [own ,* [c for c in cfg_paths .saved_configs ()if c != own ]] 550notes ,problems = cfg_paths .repair (configs ) 551if notes : 552_ ,_ ,log_path = _paths (name ) 553if log_path .parent .is_dir (): 554with open (log_path ,"ab" )as stream : 555for note in notes : 556stream .write (f" { time . strftime ( '%Y-%m-%dT%H:%M:%S' ) } config: { note } \n" .encode ("utf-8" )) 557mine = [p for p in problems if p .startswith (own .name + ":" )] 558after = hashlib .sha256 (own .read_bytes ()).hexdigest () 559if mine : 560raise ProfileError (mine [0 ],6 ) 561return (before ,after )if after != before else (None ,None ) 562except ProfileError : 563raise 564except Exception :# noqa: BLE001 - a start never fails because of this 565return None ,None 566 567 568def _refuse_deepseek (name :str )-> None : 569"""Before a start: a saved profile whose run config is a DeepSeek one stops here with the plain refusal (the model's folder and size 570when they can be read; strata_control/retired.py). Nothing is written, no process is started; a local, bounded check.""" 571from strata_control import retired 572try : 573profile ,_ = profiles .load (name ) 574source = profile .get ("source_config" ) 575except Exception :# noqa: BLE001 - the usual checks below say what is wrong with the profile 576return 577cfg = retired .read_config (source ) 578if retired .config_reason (cfg )or retired .config_file_reason (source ): 579raise ProfileError (retired .refusal (cfg ,retired .title (cfg ,source )),6 ) 580 581 582CHILD_EXIT_GRACE = 10.0 # seconds a host whose server ended on its own keeps answering "failed" (a waiting client reads why), then leaves (#4574 #4824) 583DIE_WITH_MISSES = 3 # consecutive looks, a second apart, at a process that cannot be found before the owner calls it gone (#4973) 584STATUS_RPC_TIMEOUT = 10.0 # seconds one status question may take; a busy owner is asked again until the start's wait is over (#5177) 585VERIFY_BUDGET = 180.0 # seconds an engine that says it is up may take to answer its first token, whatever is left of the load wait (#5177 #5059) 586MAX_START_WAIT = 1800 # seconds a start may wait for the model: a 250 GB set on a slow disk needs more than 10 minutes (#3949) 587 588 589def start (name :str ,* ,wait :float = 300 ,shutdown_timeout :float = 30 , 590expected_profile_revision :str | None = None , 591expected_source_sha256 :str | None = None , 592die_with_pid :int | None = None ,on_status = None )-> dict : 593"""Start the saved profile under a new owner host. 594 595``on_status`` (optional) is called with each status answer while the start waits (about every 0.2 s; the caller throttles), so a 596caller can show progress. The result of a wait that ran out names the last phase (``loading``, ``verifying_generation``, 597``ready_file_not_matched``). 598 599The owner host is a background service: it is not tied to the terminal or the process that ran this command and 600keeps serving after they end. It stops on `runtime stop`, when its server ends, or - only if `die_with_pid` 601names a process - when that process is gone (the desktop app uses this for the engines it starts).""" 602name = _name (name ) 603die_with = None 604if die_with_pid is not None : 605token = procs .start_token (die_with_pid )if type (die_with_pid )is int else None 606if token is None : 607raise ProfileError ("the process to follow with --die-with-pid is not running" ) 608die_with = (die_with_pid ,token ) 609if not 0 <= wait <= MAX_START_WAIT or not 0 <= shutdown_timeout <= 300 : 610raise ProfileError (f"start wait must be 0.. { MAX_START_WAIT } and shutdown timeout 0..300 seconds" ) 611if expected_profile_revision is not None and (not isinstance (expected_profile_revision ,str )or 612not re .fullmatch (r"[0-9a-f]{16}" ,expected_profile_revision )): 613raise ProfileError ("expected profile revision must be 16 lowercase hex characters" ) 614if expected_source_sha256 is not None and (not isinstance (expected_source_sha256 ,str )or 615not re .fullmatch (r"[0-9a-f]{64}" ,expected_source_sha256 )): 616raise ProfileError ("expected source digest must be 64 lowercase hex characters" ) 617_refuse_deepseek (name )# before anything is written or started (strata_control/retired.py) 618changed_from ,changed_to = _repair_config_paths (name ) 619if changed_from is not None and expected_source_sha256 == changed_from : 620expected_source_sha256 = changed_to # (the caller planned on the file as it was; Strata rewrote it, the caller did not) 621plan ,_ = _check_start_candidate (name ,expected_profile_revision ,expected_source_sha256 ) 622on_status = _progress (on_status , {"ok" :True ,"profile" :name ,"state" :"starting" ,"phase" :"checking_engine" }) 623_engine_preflight (plan )# hashes every engine file (1.4 GB or more): minutes on a slow disk, no owner exists yet 624_ ,_ ,log_path = _paths (name ) 625flags = os .O_WRONLY | os .O_CREAT | os .O_APPEND 626if hasattr (os ,"O_NOFOLLOW" ): 627flags |= os .O_NOFOLLOW 628lock_name = "rt" + hashlib .sha256 (name .encode ("utf-8" )).hexdigest ()[:24 ] 629with profiles ._lock (lock_name ): 630if expected_profile_revision is not None or expected_source_sha256 is not None : 631_check_start_candidate (name ,expected_profile_revision ,expected_source_sha256 ) 632procs .end_leftovers (profile = name )# a server or engine a lost owner left behind (verified one by one) 633if _read_state (name )is not None : 634_recover_stale (name ,wait = wait ) 635descriptor = os .open (log_path ,flags ,0o600 ) 636with os .fdopen (descriptor ,"ab" )as stream : 637command = [sys .executable ,"-m" ,"strata_control.runtime" ,"--host" ,name , 638"--shutdown-timeout" ,str (shutdown_timeout ), 639"--startup-wait" ,str (wait if wait else 300 )] 640if expected_profile_revision is not None : 641command += ["--expected-profile-revision" ,expected_profile_revision ] 642if expected_source_sha256 is not None : 643command += ["--expected-source-sha256" ,expected_source_sha256 ] 644if die_with is not None : 645command += ["--die-with-pid" ,str (die_with [0 ]),"--die-with-token" ,die_with [1 ]] 646detach = ({"creationflags" :subprocess .CREATE_NEW_PROCESS_GROUP | subprocess .CREATE_NO_WINDOW } 647if WINDOWS else {"start_new_session" :True }) 648proc = subprocess .Popen (command , 649cwd = ROOT ,stdin = subprocess .DEVNULL ,stdout = stream , 650stderr = subprocess .STDOUT ,close_fds = True ,** detach ) 651_STARTED_HOSTS [name ]= proc 652deadline = time .monotonic ()+ max (5.0 ,wait ) 653while _read_state (name ,pending_ok = True )is None and proc .poll ()is None and time .monotonic ()< deadline : 654time .sleep (0.05 ) 655if _read_state (name ,pending_ok = True )is None : 656if proc .poll ()is not None : 657_STARTED_HOSTS .pop (name ,None ) 658raise ProfileError ("runtime host failed to start; inspect " + str (log_path ),6 ) 659if wait == 0 : 660return {"ok" :True ,"profile" :name ,"state" :"starting" ,"plan" :plan } 661return _await_start (name ,wait ,on_status ) 662 663 664def _await_start (name :str ,wait :float ,on_status = None )-> dict : 665"""Ask the owner how the start is going until it is ready, failed, or `wait` seconds have passed.""" 666deadline = time .monotonic ()+ wait 667result :dict = {} 668while True : 669now = time .monotonic () 670# The wait is the time for the model to LOAD. An engine that has said it is up is being checked with its first token, which has 671# its own budget in the owner (VERIFY_BUDGET): the wait does not end under it (#5177 #5059 #4293) 672limit = deadline + VERIFY_BUDGET if result .get ("phase" )== "verifying_generation" else deadline 673if now >= limit : 674break 675try : 676result = _rpc (name ,"status" ,timeout = min (STATUS_RPC_TIMEOUT ,max (1.0 ,limit - now ))) 677except ProfileError as exc : 678# An owner that is busy does not answer for a while (its first imports, a slow disk, a virus scan of the engine). One 679# missed answer is not a failed start: keep asking until the wait is over, as long as the owner is still alive. A lost 680# owner (its lease is free, or nothing listens any more) is a failure now. 681if exc .exit_code not in (3 ,8 )or not _owner_alive (name ): 682raise 683result = {** result ,"state" :"starting" ,"phase" :result .get ("phase" )or "owner_not_answering" } 684time .sleep (0.2 ) 685continue 686if on_status is not None : 687try : 688on_status (result ) 689except Exception :# noqa: BLE001 - progress must never break a start 690on_status = None 691if result .get ("state" )in ("ready" ,"failed" ): 692return {** result ,"ok" :result ["state" ]== "ready" , 693"exit_code" :6 if result ["state" ]== "failed" else 0 } 694time .sleep (0.2 ) 695return {"ok" :False ,"profile" :name ,"state" :"starting" ,"error" :"startup_wait_expired" , 696"phase" :result .get ("phase" ),"exit_code" :8 } 697 698 699def _progress (on_status ,first :dict ): 700"""`on_status` after one more answer is shown now: the phase before the owner exists.""" 701if on_status is not None : 702try : 703on_status (first ) 704except Exception :# noqa: BLE001 - progress must never break a start 705return None 706return on_status 707 708 709def _owner_alive (name :str )-> bool : 710"""Whether the owner host of this profile is still running (its lease is held), without asking it anything.""" 711try : 712if _read_state (name )is None : 713return False 714return _host_lease_active (name ) 715except (ProfileError ,OSError ): 716return False 717 718 719def plan_stop (name :str )-> dict : 720current = status (_name (name )) 721if current .get ("state" )not in ("ready" ,"starting" ,"failed" )or not current .get ("owner_id" ): 722return {"ok" :False ,"profile" :name ,"state" :current .get ("state" ,"unknown" ), 723"error" :"runtime_not_owned" ,"exit_code" :6 } 724return {"ok" :True ,"plan" : {"profile" :name ,"state" :current ["state" ], 725"owner_id" :current ["owner_id" ], 726"instance_id" :current .get ("instance_id" ), 727"profile_revision" :current .get ("profile_revision" ), 728"would_drain" :False ,"would_stop" :False }} 729 730 731def stop (name :str ,* ,timeout :float = 330 , 732expected_owner_id :str | None = None , 733expected_instance_id :str | None = None )-> dict : 734if not 1 <= timeout <= 600 : 735raise ProfileError ("stop wait must be 1..600 seconds" ) 736name = _name (name ) 737if expected_owner_id is not None and (not isinstance (expected_owner_id ,str )or 738not re .fullmatch (r"[0-9a-f]{32}" ,expected_owner_id )): 739raise ProfileError ("expected owner ID must be 32 lowercase hex characters" ) 740if expected_instance_id is not None and (not isinstance (expected_instance_id ,str )or 741not re .fullmatch (r"[0-9a-f]{32}" ,expected_instance_id )): 742raise ProfileError ("expected instance ID must be 32 lowercase hex characters" ) 743params = {"expected_owner_id" :expected_owner_id , 744"expected_instance_id" :expected_instance_id } 745lost = _stop_lost (name ) 746if lost is not None : 747return lost 748result = _rpc (name ,"stop" ,timeout = timeout ,params = params ) 749if not result ["ok" ]: 750return result 751owned = _STARTED_HOSTS .pop (name ,None ) 752if owned is not None : 753try : 754owned .wait (timeout = 5 ) 755except subprocess .TimeoutExpired : 756_STARTED_HOSTS [name ]= owned 757return result 758 759 760def _stop_lost (name :str )-> dict | None : 761"""`stop` when there is no live owner host: the host was killed or crashed, so nobody can be asked to stop the 762server it started. End what it left behind - the recorded server and engine, each re-checked by PID, start time 763and command line - and clear the private state. None when an owner is running (the normal stop applies).""" 764try : 765state = _read_state (name ) 766except ProfileError : 767state = None 768if state is not None : 769try : 770if _host_lease_active (name ): 771return None 772except FileNotFoundError : 773state = None 774outcome = procs .end_leftovers (profile = name ) 775recovered = False 776if state is not None : 777recovered = _recover_stale (name ,wait = 20 ) 778if state is None and not any (outcome [key ]for key in ("ended" ,"stuck" ,"unverifiable" )): 779return None # nothing recorded: the normal "not managed or is stopped" 780stuck = bool (outcome ["stuck" ]or outcome ["unverifiable" ]) 781return {"ok" :not stuck ,"profile" :name ,"state" :"failed" if stuck else "stopped" ,"recovered" :recovered , 782"ended" :outcome ["ended" ],"leftover_unverified" :outcome ["unverifiable" ], 783"exit_code" :6 if stuck else 0 , 784** ({"error" :"leftover_process_not_ended" }if stuck else {})} 785 786 787def cleanup (profile :str | None = None )-> dict : 788"""End the servers and engines Strata started whose owner is gone (`strata runtime cleanup`). Owned instances 789that are running are not touched, and neither is any process that is not exactly what Strata recorded.""" 790if profile is not None : 791profile = _name (profile ) 792outcome = procs .end_leftovers (profile = profile ) 793if profile is not None : 794try : 795if _read_state (profile )is not None and not _host_lease_active (profile ): 796outcome ["recovered" ]= _recover_stale (profile ,wait = 20 ) 797except (ProfileError ,FileNotFoundError ): 798pass 799stuck = bool (outcome ["stuck" ]or outcome ["unverifiable" ]) 800return {"ok" :not stuck ,"state" :"cleaned" if not stuck else "failed" ,** outcome , 801"exit_code" :6 if stuck else 0 } 802 803 804def verify (name :str ,* ,timeout :float = 300 ,load :bool = False , 805expected_owner_id :str | None = None , 806expected_instance_id :str | None = None )-> dict : 807if not 1 <= timeout <= 600 or type (load )is not bool : 808raise ProfileError ("verify wait must be 1..600 seconds and load must be true or false" ) 809for label ,identity in (("owner" ,expected_owner_id ), ("instance" ,expected_instance_id )): 810if identity is not None and (not isinstance (identity ,str )or 811not re .fullmatch (r"[0-9a-f]{32}" ,identity )): 812raise ProfileError (f"expected { label } ID must be 32 lowercase hex characters" ) 813return _rpc (_name (name ),"verify" ,timeout = timeout + 5 , 814params = {"wait" :timeout ,"load" :load , 815"expected_owner_id" :expected_owner_id , 816"expected_instance_id" :expected_instance_id }) 817 818 819def restart (name :str ,* ,timeout :float = 1000 ,startup_wait :float = 300 , 820expected_profile_revision :str | None = None , 821expected_owner_id :str | None = None , 822expected_instance_id :str | None = None , 823allow_source_switch :bool = False , 824allow_source_migration :bool = False , 825expected_source_sha256 :str | None = None )-> dict : 826if (not 1 <= timeout <= 1800 or not 1 <= startup_wait <= MAX_START_WAIT or 827type (allow_source_switch )is not bool or type (allow_source_migration )is not bool ): 828raise ProfileError (f"restart wait must be 1..1800 and startup wait 1.. { MAX_START_WAIT } seconds" ) 829if expected_source_sha256 is not None and (not isinstance (expected_source_sha256 ,str )or 830not re .fullmatch (r"[0-9a-f]{64}" ,expected_source_sha256 )): 831raise ProfileError ("expected source SHA-256 must be 64 lowercase hex characters" ) 832for label ,identity in (("owner" ,expected_owner_id ), ("instance" ,expected_instance_id )): 833if identity is not None and (not isinstance (identity ,str )or 834not re .fullmatch (r"[0-9a-f]{32}" ,identity )): 835raise ProfileError (f"expected { label } ID must be 32 lowercase hex characters" ) 836if (allow_source_switch or allow_source_migration )and expected_source_sha256 is None : 837raise ProfileError ("source change needs the candidate SHA-256 from runtime restart --plan" ) 838params = {"startup_wait" :startup_wait ,"allow_source_switch" :allow_source_switch , 839"allow_source_migration" :allow_source_migration } 840if expected_source_sha256 is not None : 841params ["expected_source_sha256" ]= expected_source_sha256 842if expected_profile_revision is not None : 843params ["expected_profile_revision" ]= expected_profile_revision 844if expected_owner_id is not None : 845params ["expected_owner_id" ]= expected_owner_id 846if expected_instance_id is not None : 847params ["expected_instance_id" ]= expected_instance_id 848return _rpc (_name (name ),"restart" ,timeout = timeout ,params = params ) 849 850 851def plan_restart (name :str ,* ,allow_source_switch :bool = False , 852allow_source_migration :bool = False )-> dict : 853if type (allow_source_switch )is not bool or type (allow_source_migration )is not bool : 854raise ProfileError ("source change options must be true or false" ) 855return _rpc (_name (name ),"plan_restart" ,timeout = 10 , 856params = {"allow_source_switch" :allow_source_switch , 857"allow_source_migration" :allow_source_migration }) 858 859 860class Host : 861def __init__ (self ,name :str ,shutdown_timeout :float ,startup_wait :float = 300 , 862expected_profile_revision :str | None = None , 863expected_source_sha256 :str | None = None , 864die_with :tuple [int ,str ]| None = None ): 865self .name = _name (name ) 866self .die_with = die_with # (pid, start token): stop the server when that process is gone 867self .shutdown_timeout = shutdown_timeout 868self .expected_profile_revision = expected_profile_revision 869self .expected_source_sha256 = expected_source_sha256 870self .state_path ,self .socket_path ,self .log_path = _paths (name ) 871self .token = secrets .token_hex (32 ) 872self .owner_id = uuid .uuid4 ().hex 873self .child :subprocess .Popen | None = None 874self .ready_path :Path | None = None 875self .args :list [str ]| None = None 876self .source :Path | None = None 877self .source_bytes :bytes | None = None 878self .expected_attestation :str | None = None 879self .revision :str | None = None 880self .last_error :str | None = None 881self .running = True 882self .state_fd :int | None = None 883self .owner_write_fd :int | None = None 884self .owner_write = None # Windows: the server's stdin pipe, whose EOF asks it to drain and stop 885self .probe_timeout = startup_wait 886self .gone_at :float | None = None # when the server was first seen ended (the host leaves CHILD_EXIT_GRACE seconds later) 887self .exit_status = 0 888self .die_misses = 0 889self .starting = False # the plan and the launch run in a thread (_startup): the owner answers status meanwhile (#5177) 890self .phase :str | None = None # what that thread is doing: preparing | launching 891self ._launch_lock = threading .Lock ()# held while the server is being started or stopped, so a stop never races the launch 892self .probe_deadline = 0.0 893self .probe_key :tuple [int ,str ]| None = None 894self .probe_result :dict | None = None 895self .rollback_snapshots :set [Path ]= set () 896 897def _mark_child (self ,phase :str ,* ,pid :int | None = None ,ready :Path | None = None )-> None : 898payload = {"host_token" :self .token ,"phase" :phase } 899if pid is not None and ready is not None : 900payload .update (pid = pid ,ready = str (ready )) 901if WINDOWS : 902started = winproc .process_started (pid ) 903if started is None : 904time .sleep (0.05 ) 905started = winproc .process_started (pid )# one more try: the child may not be queryable yet 906if started is not None : 907payload ["started" ]= started # tells this process from a later one with the same number 908profiles ._atomic (_child_marker (self .name ,self .token ), (json .dumps (payload )+ "\n" ).encode ()) 909 910def _plan (self )-> tuple [dict ,list [str ],Path ,bytes ]: 911from strata_cli .cli import _launch_plan 912plan ,args = _launch_plan (self .name ) 913source = Path (plan ["source_config" ]) 914return plan ,args ,source ,source .read_bytes () 915 916def _source_change_check (self ,source :Path ,source_bytes :bytes , 917allow_source_switch :bool , 918allow_source_migration :bool )-> tuple [bool ,bool ,str | None ]: 919"""Identify when rollback needs an owner-private copy of the running config.""" 920if source == self .source : 921migrated = source_bytes != self .source_bytes 922return False ,migrated , ("source_config_changed_restart_requires_migration" 923if migrated and not allow_source_migration else None ) 924if not allow_source_switch : 925return True ,False ,"source_switch_requires_opt_in" 926try : 927old_stat ,new_stat = self .source .lstat (),source .lstat () 928if (not stat .S_ISREG (old_stat .st_mode )or not stat .S_ISREG (new_stat .st_mode )or 929 (old_stat .st_dev ,old_stat .st_ino )== (new_stat .st_dev ,new_stat .st_ino )): 930return True ,False ,"source_switch_requires_distinct_regular_files" 931migrated = self .source .read_bytes ()!= self .source_bytes 932except OSError : 933return True ,False ,"rollback_source_unavailable" 934return True ,migrated , ("rollback_source_changed" if migrated and not allow_source_migration else None ) 935 936def _snapshot_running_config (self )-> Path : 937"""Save launch bytes before drain; never overwrite the operator's edited file.""" 938path = self .state_path .parent / f" { self . name } - { self . token } - { uuid . uuid4 (). hex } .rollback.json" 939descriptor = _write_new (path ,self .source_bytes ) 940os .close (descriptor ) 941self .rollback_snapshots .add (path ) 942return path 943 944def _retire_snapshot (self ,path :Path )-> bool : 945if path in self .rollback_snapshots : 946try : 947path .unlink (missing_ok = True ) 948except OSError : 949return False 950self .rollback_snapshots .discard (path ) 951return True 952 953@staticmethod 954def _config_args (args :list [str ],source :Path )-> list [str ]: 955result = list (args ) 956try : 957index = result .index ("--config" ) 958result [index + 1 ]= str (source ) 959except (ValueError ,IndexError ): 960raise ProfileError ("owned launch has no run config argument" ,6 )from None 961return result 962 963def _launch (self ,args :list [str ],source :Path ,source_bytes :bytes , 964revision :str | None )-> None : 965ready = self .state_path .parent / f" { self . name } - { uuid . uuid4 (). hex } .ready.json" 966flags = os .O_WRONLY | os .O_CREAT | os .O_APPEND 967if hasattr (os ,"O_NOFOLLOW" ): 968flags |= os .O_NOFOLLOW 969log = self .state_path .parent / f" { self . name } .server.log" 970self ._mark_child ("launching" ) 971descriptor = os .open (log ,flags ,0o600 ) 972# POSIX: an inherited pipe with one writer (this host). Windows: the server's standard input is that pipe. 973reader ,writer = (None ,None )if WINDOWS else os .pipe () 974server_args = [* args ,"--ready-file" ,str (ready ), 975"--shutdown-timeout" ,str (self .shutdown_timeout ), 976"--owner-fd" ,"0" if WINDOWS else str (reader )] 977attestation_key = secrets .token_bytes (32 ) 978expected_attestation = launch_identity .attestation (attestation_key ,source_bytes ,server_args ) 979child_env = quiet_crash_env (os .environ .copy ())# the server's engine and reader start no debugger on a user's machine 980child_env ["STRATA_OWNER_ATTEST_KEY" ]= attestation_key .hex () 981child_env ["STRATA_NO_ACQUIRE" ]= "1" # a managed server never installs or downloads (acquisition.py) 982child_env ["STRATA_RUNTIME_PROFILE" ]= self .name # the records of its engine say which profile they belong to 983try : 984with os .fdopen (descriptor ,"ab" )as stream : 985if WINDOWS : 986self .child = subprocess .Popen ([sys .executable ,"-m" ,"serve.server" ,* server_args ], 987cwd = ROOT ,stdin = subprocess .PIPE ,stdout = stream , 988stderr = subprocess .STDOUT ,close_fds = True ,env = child_env , 989creationflags = subprocess .CREATE_NO_WINDOW ) 990# the whole server tree ends with this host, however the host ends (a kill-on-close job) 991from serve import winjob 992winjob .contain (self .child ) 993else : 994self .child = subprocess .Popen ([sys .executable ,"-m" ,"serve.server" ,* server_args ], 995cwd = ROOT ,stdin = subprocess .DEVNULL ,stdout = stream , 996stderr = subprocess .STDOUT ,close_fds = True , 997pass_fds = (reader ,),start_new_session = True ,env = child_env ) 998except BaseException : 999if writer is not None : 1000os .close (writer ) 1001raise 1002finally : 1003if reader is not None : 1004os .close (reader ) 1005if WINDOWS : 1006self .owner_write = self .child .stdin 1007else : 1008self .owner_write_fd = writer 1009procs .write_record (self .child .pid ,"server" ,profile = self .name ) 1010try : 1011self ._mark_child ("owned" ,pid = self .child .pid ,ready = ready ) 1012except BaseException : 1013# No ownership record means a future start cannot safely reclaim 1014# this instance. Stop this child immediately instead. 1015self ._kill_child_tree () 1016self .child .wait (timeout = 10 ) 1017self ._close_owner_pipe () 1018raise 1019# (the status answer reads these from another thread: the ready path comes last, it is what makes the rest be read) 1020self .args ,self .source ,self .source_bytes ,self .revision = list (args ),source ,source_bytes ,revision 1021self .expected_attestation = expected_attestation 1022self .last_error = None 1023self .probe_deadline = time .monotonic ()+ self .probe_timeout 1024self .probe_key = None 1025self .probe_result = None 1026self .ready_path = ready 1027 1028def _verify_ready (self ,ready :dict ,key :tuple [int ,str ],host :str ,source_bytes :bytes , 1029expected_attestation :str ,timeout :float )-> None : 1030try : 1031result = readiness .verify (ready ,source_bytes ,expected_host = host , 1032expected_instance = key [1 ], 1033expected_attestation = expected_attestation ,timeout = timeout ) 1034except readiness .ReadinessError as exc : 1035result = {"error" :str (exc )} 1036except Exception : 1037result = {"error" :"probe_internal_error" } 1038if self .probe_key == key : 1039self .probe_result = result 1040if "error" in result : 1041self .last_error = result ["error" ] 1042 1043def _log_tail (self ,limit :int = 4096 )-> str | None : 1044"""The last lines the server wrote (a failed start is explained by them), or None. Bounded read, never raises.""" 1045try : 1046with open (self .state_path .parent / f" { self . name } .server.log" ,"rb" )as stream : 1047stream .seek (0 ,os .SEEK_END ) 1048stream .seek (max (0 ,stream .tell ()- limit )) 1049lines = [x .rstrip ()for x in stream .read ().decode ("utf-8" ,"replace" ).splitlines ()if x .strip ()] 1050except OSError : 1051return None 1052# not the indented frames of a Python traceback: the engine's own lines and the final exception line say why 1053plain = [x for x in lines if not x [0 ].isspace ()and not x .startswith ("Traceback" )] 1054chosen = plain [- 3 :]or lines [- 1 :] 1055return " | " .join (x [:200 ]for x in chosen )if chosen else None 1056 1057def _status (self )-> dict : 1058child = self .child 1059base = {"ok" :True ,"profile" :self .name ,"host_pid" :os .getpid (), 1060"owner_id" :self .owner_id , 1061"child_pid" :child .pid if child else None ,"profile_revision" :self .revision , 1062"shutdown_timeout" :self .shutdown_timeout } 1063if child is None : 1064if self .starting : 1065return {** base ,"state" :"starting" ,"phase" :self .phase or "preparing" } 1066if self .last_error is not None : 1067return {** base ,"ok" :False ,"state" :"failed" ,"error" :self .last_error ,"exit_code" :6 } 1068return {** base ,"state" :"stopped" } 1069if child .poll ()is not None : 1070# engine_exit_code: how the engine process ended (Windows: 0xC0000135 = a DLL was not found); `exit_code` is 1071# Control's own and the start command overwrites it with 6, so the engine's code travels under its own name. 1072return {** base ,"ok" :False ,"state" :"failed" ,"exit_code" :child .returncode ,"engine_exit_code" :child .returncode , 1073"error" :self .last_error or "server_exited" ,"log_tail" :self ._log_tail ()} 1074if self .ready_path is not None : 1075try : 1076ready = json .loads (self .ready_path .read_text (encoding = "utf-8" )) 1077if _ready_pid_is_child (ready .get ("pid" ),child .pid )and isinstance (ready .get ("instance_id" ),str ): 1078key = (child .pid ,ready ["instance_id" ]) 1079if self .probe_key != key : 1080self .probe_key ,self .probe_result = key ,None 1081host = self .args [self .args .index ("--host" )+ 1 ] 1082threading .Thread (target = self ._verify_ready , 1083args = (ready ,key ,host ,self .source_bytes , 1084self .expected_attestation , 1085max (VERIFY_BUDGET ,self .probe_deadline - time .monotonic ())), 1086name = "strata-generation-probe" ,daemon = True ).start () 1087if self .probe_result is None : 1088return {** base ,"state" :"starting" ,"phase" :"verifying_generation" , 1089"instance_id" :ready ["instance_id" ]} 1090if "error" in self .probe_result : 1091return {** base ,"ok" :False ,"state" :"failed" ,"error" :self .probe_result ["error" ], 1092"exit_code" :6 ,"instance_id" :ready ["instance_id" ]} 1093return {** base ,"state" :"ready" ,"instance_id" :ready ["instance_id" ], 1094"model_state" :ready .get ("model_state" ), 1095** self .probe_result } 1096if isinstance (ready ,dict ): 1097# the server published its ready file but it is not the process this host started: say so, so a wait that 1098# ends can name it (before #3683 this looked exactly like a model that was still loading) 1099return {** base ,"state" :"starting" ,"phase" :"ready_file_not_matched" } 1100except (OSError ,ValueError ): 1101pass 1102return {** base ,"state" :"starting" ,"phase" :"loading" } 1103 1104def _wait_ready (self ,timeout :float )-> dict : 1105deadline = time .monotonic ()+ timeout 1106while True : 1107current = self ._status () 1108if current ["state" ]in ("ready" ,"failed" ): 1109return current 1110# an engine that has said it is up is being checked with its first token, which has its own budget (VERIFY_BUDGET) 1111limit = deadline + VERIFY_BUDGET if current .get ("phase" )== "verifying_generation" else deadline 1112if time .monotonic ()>= limit : 1113break 1114time .sleep (0.15 ) 1115current = self ._status () 1116if current ["state" ]in ("ready" ,"failed" ): 1117return current 1118return {** current ,"ok" :False ,"error" :"startup_wait_expired" ,"exit_code" :8 } 1119 1120def _stop_child (self )-> dict : 1121child = self .child 1122if child is None or child .poll ()is not None : 1123self ._close_owner_pipe () 1124if self .ready_path is not None : 1125self .ready_path .unlink (missing_ok = True ) 1126return {"ok" :True ,"state" :"stopped" ,"exit_code" :child .returncode if child else 0 } 1127if WINDOWS : 1128self ._close_owner_pipe ()# EOF on the server's stdin: it drains and stops (no SIGTERM here) 1129else : 1130child .send_signal (signal .SIGTERM ) 1131try : 1132code = child .wait (timeout = self .shutdown_timeout + 8 ) 1133except subprocess .TimeoutExpired : 1134self ._kill_child_tree () 1135child .wait (timeout = 10 ) 1136self ._close_owner_pipe () 1137return {"ok" :False ,"state" :"failed" ,"error" :"server_stop_deadline_expired" ,"exit_code" :8 } 1138self ._close_owner_pipe () 1139if self .ready_path is not None : 1140self .ready_path .unlink (missing_ok = True ) 1141return {"ok" :code == 0 ,"state" :"stopped" if code == 0 else "failed" , 1142"exit_code" :code ,"error" :None if code == 0 else "server_stop_failed" } 1143 1144def _close_owner_pipe (self )-> None : 1145if self .owner_write_fd is not None : 1146os .close (self .owner_write_fd ) 1147self .owner_write_fd = None 1148if self .owner_write is not None : 1149try : 1150self .owner_write .close () 1151except OSError : 1152pass 1153self .owner_write = None 1154 1155def _kill_child_tree (self )-> None : 1156"""The deadline kill of the server this host started, and everything it started. Only our own child: POSIX 1157signals its process group, Windows ends the job the child was put in (taskkill of our own child's tree if 1158the job could not be made).""" 1159child = self .child 1160if child is None : 1161return 1162if WINDOWS : 1163from serve import winjob 1164if not winjob .terminate (): 1165subprocess .run (["taskkill" ,"/T" ,"/F" ,"/PID" ,str (child .pid )],capture_output = True ) 1166try : 1167child .kill () 1168except OSError : 1169pass 1170else : 1171os .killpg (child .pid ,signal .SIGKILL ) 1172 1173def _restart (self ,startup_wait :float ,expected_profile_revision :str | None = None , 1174allow_source_switch :bool = False , 1175allow_source_migration :bool = False , 1176expected_source_sha256 :str | None = None , 1177expected_owner_id :str | None = None , 1178expected_instance_id :str | None = None )-> dict : 1179old = self ._status () 1180if expected_owner_id is not None and old .get ("owner_id" )!= expected_owner_id : 1181return {"ok" :False ,"error" :"owner_changed_after_restart_plan" ,"exit_code" :6 } 1182if expected_instance_id is not None and old .get ("instance_id" )!= expected_instance_id : 1183return {"ok" :False ,"error" :"instance_changed_after_restart_plan" ,"exit_code" :6 } 1184if old ["state" ]!= "ready" : 1185return {"ok" :False ,"state" :old ["state" ],"error" :"runtime_not_ready" ,"exit_code" :6 } 1186try : 1187plan ,new_args ,source ,source_bytes = self ._plan () 1188except (ProfileError ,OSError ): 1189return {"ok" :False ,"state" :"ready" ,"error" :"new_profile_preflight_failed" ,"exit_code" :5 } 1190switched ,migrated ,source_error = self ._source_change_check ( 1191source ,source_bytes ,allow_source_switch ,allow_source_migration ) 1192if source_error : 1193return {"ok" :False ,"state" :"ready" ,"error" :source_error ,"exit_code" :6 } 1194if expected_source_sha256 is not None and \ 1195hashlib .sha256 (source_bytes ).hexdigest ()!= expected_source_sha256 : 1196return {"ok" :False ,"state" :"ready" ,"error" :"source_changed_after_preview" ,"exit_code" :6 } 1197if expected_profile_revision is not None and plan ["profile_revision" ]!= expected_profile_revision : 1198return {"ok" :False ,"state" :"ready" ,"error" :"profile_changed_after_preview" ,"exit_code" :6 } 1199current = self ._status () 1200if expected_instance_id is not None and current .get ("instance_id" )!= expected_instance_id : 1201return {"ok" :False ,"error" :"instance_changed_after_restart_plan" ,"exit_code" :6 } 1202if current ["state" ]!= "ready" : 1203return {"ok" :False ,"state" :current ["state" ],"error" :"runtime_not_ready" ,"exit_code" :6 } 1204old_args ,old_source ,old_bytes ,old_revision = self .args ,self .source ,self .source_bytes ,self .revision 1205rollback_source = old_source 1206rollback_args = old_args 1207if migrated : 1208try : 1209rollback_source = self ._snapshot_running_config () 1210rollback_args = self ._config_args (old_args ,rollback_source ) 1211except (OSError ,ProfileError ): 1212if rollback_source != old_source : 1213self ._retire_snapshot (rollback_source ) 1214return {"ok" :False ,"state" :"ready" ,"error" :"rollback_snapshot_failed" ,"exit_code" :6 } 1215self .probe_timeout = startup_wait 1216stopped = self ._stop_child () 1217if not stopped ["ok" ]: 1218return {** stopped ,"profile" :self .name ,"previous_instance_id" :old .get ("instance_id" )} 1219try : 1220if source .read_bytes ()!= source_bytes : 1221raise ProfileError ("source changed during drain" ,6 ) 1222self ._launch (new_args ,source ,source_bytes ,plan ["profile_revision" ]) 1223result = self ._wait_ready (startup_wait ) 1224if result .get ("ok" )and result ["state" ]== "ready" : 1225cleanup_ok = True 1226if rollback_source != source : 1227cleanup_ok = self ._retire_snapshot (rollback_source )and cleanup_ok 1228if old_source != source : 1229cleanup_ok = self ._retire_snapshot (old_source )and cleanup_ok 1230return {** result ,"previous_instance_id" :old .get ("instance_id" ),"restarted" :True , 1231"source_switched" :switched ,"source_migrated" :migrated , 1232"rollback_snapshot_cleanup_pending" :not cleanup_ok } 1233if self .child is not None and self .child .poll ()is None : 1234self ._stop_child () 1235except (ProfileError ,OSError ): 1236result = {"state" :"failed" ,"error" :"new_instance_launch_failed" ,"exit_code" :6 } 1237# The old launch needs its original bytes, even if the operator edited 1238# the same file. A private snapshot is used only for explicit migration. 1239try : 1240old_source_unchanged = rollback_source .read_bytes ()== old_bytes 1241except OSError : 1242old_source_unchanged = False 1243if old_source_unchanged : 1244try : 1245self ._launch (rollback_args ,rollback_source ,old_bytes ,old_revision ) 1246rollback = self ._wait_ready (startup_wait ) 1247except (OSError ,ProfileError ): 1248rollback = {"state" :"failed" } 1249if rollback .get ("ok" )and rollback .get ("state" )== "ready" : 1250cleanup_ok = True 1251if old_source != rollback_source : 1252cleanup_ok = self ._retire_snapshot (old_source ) 1253return {"ok" :False ,"state" :"ready" ,"error" :result .get ("error" ,"new_instance_failed" ), 1254"exit_code" :6 ,"rolled_back" :True , 1255"rollback_snapshot_cleanup_pending" :not cleanup_ok , 1256"rollback_source_config" :str (rollback_source ), 1257"instance_id" :rollback .get ("instance_id" ), 1258"previous_instance_id" :old .get ("instance_id" )} 1259return {"ok" :False ,"state" :"failed" ,"error" :result .get ("error" ,"restart_failed" ), 1260"exit_code" :6 ,"rolled_back" :False } 1261 1262def _plan_restart (self ,allow_source_switch :bool = False , 1263allow_source_migration :bool = False )-> dict : 1264current = self ._status () 1265if current ["state" ]!= "ready" : 1266return {"ok" :False ,"state" :current ["state" ],"error" :"runtime_not_ready" ,"exit_code" :6 } 1267try : 1268plan ,candidate_args ,source ,source_bytes = self ._plan () 1269except (ProfileError ,OSError ): 1270return {"ok" :False ,"state" :"ready" ,"error" :"new_profile_preflight_failed" ,"exit_code" :5 } 1271switched ,migrated ,source_error = self ._source_change_check ( 1272source ,source_bytes ,allow_source_switch ,allow_source_migration ) 1273if source_error : 1274return {"ok" :False ,"state" :"ready" ,"error" :source_error ,"exit_code" :6 , 1275"source_switch" :switched ,"source_migration" :migrated , 1276"requires_allow_source_switch" :switched and not allow_source_switch , 1277"requires_allow_source_migration" :migrated and not allow_source_migration } 1278from strata_cli .cli import _redact_argv 1279return {"ok" :True ,"state" :"ready" ,"profile" :self .name , 1280"current_owner_id" :current ["owner_id" ], 1281"current_instance_id" :current ["instance_id" ], 1282"current_profile_revision" :self .revision , 1283"candidate_profile_revision" :plan ["profile_revision" ], 1284"current_source_config" :str (self .source ),"candidate_source_config" :str (source ), 1285"current_source_sha256" :hashlib .sha256 (self .source_bytes ).hexdigest (), 1286"candidate_source_sha256" :hashlib .sha256 (source_bytes ).hexdigest (), 1287"source_switch" :switched ,"source_migration" :migrated , 1288"rollback_snapshot_required" :migrated , 1289"current_server_argv" :_redact_argv (self .args ), 1290"candidate_server_argv" :_redact_argv (candidate_args ), 1291"changed" :switched or migrated or self .args != candidate_args or 1292self .revision != plan ["profile_revision" ], 1293"shutdown_timeout" :self .shutdown_timeout , 1294"would_drain" :False ,"would_start" :False } 1295 1296def _handle (self ,request :dict )-> dict : 1297if not secrets .compare_digest (str (request .get ("token" ,"" )),self .token ): 1298return {"ok" :False ,"error" :"unauthorized" ,"exit_code" :4 } 1299command = request .get ("command" ) 1300if command == "status" : 1301return self ._status () 1302if command == "verify" : 1303timeout ,force_load = request .get ("wait" ,300 ),request .get ("load" ,False ) 1304if type (timeout )not in (int ,float )or not 1 <= timeout <= 600 or type (force_load )is not bool : 1305return {"ok" :False ,"error" :"invalid_verification_options" ,"exit_code" :2 } 1306owner = request .get ("expected_owner_id" ) 1307instance = request .get ("expected_instance_id" ) 1308for label ,identity in (("owner" ,owner ), ("instance" ,instance )): 1309if identity is not None and (not isinstance (identity ,str )or 1310not re .fullmatch (r"[0-9a-f]{32}" ,identity )): 1311return {"ok" :False ,"error" :f"invalid_expected_ { label } _id" ,"exit_code" :2 } 1312if (owner is None )!= (instance is None ): 1313return {"ok" :False ,"error" :"verification_requires_both_identities" ,"exit_code" :2 } 1314current = self ._status () 1315if owner is not None and owner != self .owner_id : 1316return {"ok" :False ,"error" :"owner_changed_after_verify_plan" ,"exit_code" :6 } 1317if instance is not None and current .get ("instance_id" )!= instance : 1318return {"ok" :False ,"error" :"instance_changed_after_verify_plan" ,"exit_code" :6 } 1319if current ["state" ]!= "ready" or self .ready_path is None or self .child is None : 1320return {"ok" :False ,"state" :current ["state" ],"error" :"runtime_not_ready" ,"exit_code" :6 } 1321try : 1322ready = json .loads (self .ready_path .read_text (encoding = "utf-8" )) 1323if not _ready_pid_is_child (ready .get ("pid" ),self .child .pid )or ready .get ("instance_id" )!= current ["instance_id" ]: 1324raise readiness .ReadinessError ("probe_instance_mismatch" ) 1325host = self .args [self .args .index ("--host" )+ 1 ] 1326result = readiness .verify (ready ,self .source_bytes ,expected_host = host , 1327expected_instance = current ["instance_id" ], 1328expected_attestation = self .expected_attestation ,timeout = timeout , 1329force_load = force_load ) 1330except readiness .ReadinessError as exc : 1331return {"ok" :False ,"state" :current ["state" ],"instance_id" :current ["instance_id" ], 1332"error" :str (exc ),"exit_code" :6 } 1333except (OSError ,ValueError ): 1334return {"ok" :False ,"state" :current ["state" ],"instance_id" :current ["instance_id" ], 1335"error" :"probe_invalid_ready_file" ,"exit_code" :6 } 1336if self .probe_key == (self .child .pid ,current ["instance_id" ]): 1337self .probe_result = result 1338return {** self ._status (),"verified_now" :True } 1339if command == "stop" : 1340owner = request .get ("expected_owner_id" ) 1341instance = request .get ("expected_instance_id" ) 1342if owner is not None and (not isinstance (owner ,str )or 1343not re .fullmatch (r"[0-9a-f]{32}" ,owner )): 1344return {"ok" :False ,"error" :"invalid_expected_owner_id" ,"exit_code" :2 } 1345if instance is not None and (not isinstance (instance ,str )or 1346not re .fullmatch (r"[0-9a-f]{32}" ,instance )): 1347return {"ok" :False ,"error" :"invalid_expected_instance_id" ,"exit_code" :2 } 1348if owner is not None and owner != self .owner_id : 1349return {"ok" :False ,"error" :"owner_changed_after_stop_plan" ,"exit_code" :6 } 1350if instance is not None and self ._status ().get ("instance_id" )!= instance : 1351return {"ok" :False ,"error" :"instance_changed_after_stop_plan" ,"exit_code" :6 } 1352self .running = False # (a launch that has not begun will not) 1353with self ._launch_lock : 1354result = self ._stop_child () 1355return {** result ,"profile" :self .name } 1356if command == "restart" : 1357startup_wait = request .get ("startup_wait" ,300 ) 1358if type (startup_wait )not in (int ,float )or not 1 <= startup_wait <= MAX_START_WAIT : 1359return {"ok" :False ,"error" :"invalid_startup_wait" ,"exit_code" :2 } 1360revision = request .get ("expected_profile_revision" ) 1361if revision is not None and (not isinstance (revision ,str )or 1362not re .fullmatch (r"[0-9a-f]{16}" ,revision )): 1363return {"ok" :False ,"error" :"invalid_profile_revision" ,"exit_code" :2 } 1364allow_source_switch = request .get ("allow_source_switch" ,False ) 1365if type (allow_source_switch )is not bool : 1366return {"ok" :False ,"error" :"invalid_source_switch_option" ,"exit_code" :2 } 1367allow_source_migration = request .get ("allow_source_migration" ,False ) 1368if type (allow_source_migration )is not bool : 1369return {"ok" :False ,"error" :"invalid_source_migration_option" ,"exit_code" :2 } 1370expected_source_sha256 = request .get ("expected_source_sha256" ) 1371if (allow_source_switch or allow_source_migration )and \ 1372 (not isinstance (expected_source_sha256 ,str )or 1373not re .fullmatch (r"[0-9a-f]{64}" ,expected_source_sha256 )): 1374return {"ok" :False ,"error" :"source_change_needs_candidate_digest" ,"exit_code" :2 } 1375if expected_source_sha256 is not None and (not isinstance (expected_source_sha256 ,str )or 1376not re .fullmatch (r"[0-9a-f]{64}" ,expected_source_sha256 )): 1377return {"ok" :False ,"error" :"invalid_source_digest" ,"exit_code" :2 } 1378expected_owner_id = request .get ("expected_owner_id" ) 1379expected_instance_id = request .get ("expected_instance_id" ) 1380if expected_owner_id is not None and (not isinstance (expected_owner_id ,str )or 1381not re .fullmatch (r"[0-9a-f]{32}" ,expected_owner_id )): 1382return {"ok" :False ,"error" :"invalid_expected_owner_id" ,"exit_code" :2 } 1383if expected_instance_id is not None and (not isinstance (expected_instance_id ,str )or 1384not re .fullmatch (r"[0-9a-f]{32}" ,expected_instance_id )): 1385return {"ok" :False ,"error" :"invalid_expected_instance_id" ,"exit_code" :2 } 1386return self ._restart (startup_wait ,revision ,allow_source_switch , 1387allow_source_migration ,expected_source_sha256 , 1388expected_owner_id ,expected_instance_id ) 1389if command == "plan_restart" : 1390allow_source_switch = request .get ("allow_source_switch" ,False ) 1391allow_source_migration = request .get ("allow_source_migration" ,False ) 1392if type (allow_source_switch )is not bool or type (allow_source_migration )is not bool : 1393return {"ok" :False ,"error" :"invalid_source_change_options" ,"exit_code" :2 } 1394return self ._plan_restart (allow_source_switch ,allow_source_migration ) 1395return {"ok" :False ,"error" :"unsupported_runtime_command" ,"exit_code" :2 } 1396 1397def _say (self ,line :str )-> None : 1398"""One line to the host log (the host's stderr is that file), so a host that ends says why.""" 1399try : 1400f" { time . strftime ( '%Y-%m-%dT%H:%M:%S' ) } [strata runtime] profile { self . name } : { line } " ,file = sys .stderr ,flush = True ) 1401except (OSError ,ValueError ): 1402pass 1403 1404def _husk (self )-> bool : 1405"""Whether this host has nothing left to supervise: its server ended, or the start failed before one existed.""" 1406child = self .child 1407if child is not None : 1408return child .poll ()is not None 1409return not self .starting and self .last_error is not None 1410 1411def _die_with_gone (self )-> bool : 1412"""Whether the process this instance lives for (the desktop app's host) is gone. A look that cannot read the process (the macOS 1413`ps` that timed out, a handle that was refused) is not an answer: the engine used to be stopped on it, cleanly and without a word, 1414hours into an idle session (#4973). A different start time is a later process with that number: gone at once. Nothing found is 1415confirmed against a plain liveness check, and has to repeat DIE_WITH_MISSES times.""" 1416pid ,token = self .die_with 1417found = procs .start_token (pid ) 1418if found == token : 1419self .die_misses = 0 1420return False 1421if found is not None : 1422return True 1423if _pid_exists (pid ): 1424self .die_misses = 0 1425return False 1426self .die_misses += 1 1427return self .die_misses >= DIE_WITH_MISSES 1428 1429def _startup (self )-> None : 1430"""The first launch, in a thread. Planning imports the server and asks the machine about its cards, which takes seconds on a slow 1431disk or a PC with a virus scanner; with it in the accept loop's way a status question went unanswered and `runtime start` gave up 1432with "runtime operation wait expired" while the engine loaded fine (#5177). Now the owner answers (phase "preparing", then 1433"launching", then the server's own "loading" and "verifying_generation") the whole time.""" 1434try : 1435self .phase = "preparing" 1436plan ,args ,source ,source_bytes = self ._plan () 1437if (self .expected_profile_revision is not None and 1438plan ["profile_revision" ]!= self .expected_profile_revision ): 1439raise ProfileError ("profile_changed_after_start_plan" ,6 ) 1440if (self .expected_source_sha256 is not None and 1441hashlib .sha256 (source_bytes ).hexdigest ()!= self .expected_source_sha256 ): 1442raise ProfileError ("source_changed_after_start_plan" ,6 ) 1443with self ._launch_lock : 1444if not self .running :# a stop (or a signal) came while the plan was made: nothing is started 1445return 1446self .phase = "launching" 1447self ._launch (args ,source ,source_bytes ,plan ["profile_revision" ]) 1448except (ProfileError ,OSError )as exc : 1449self .last_error = str (exc )if isinstance (exc ,ProfileError )else type (exc ).__name__ 1450except BaseException as exc :# noqa: BLE001 - a thread that dies silently would leave "preparing" forever 1451self .last_error = type (exc ).__name__ 1452finally : 1453self .starting = False 1454self .phase = None 1455 1456def serve (self )-> int : 1457activity_lease = acquire_activity_lease (shared = True ) 1458listener = owner_transport .Listener (self .socket_path ,timeout = 1.0 ) 1459try : 1460# `bind()` returns the address the client must use, which differs from the requested one 1461# on Windows (the OS assigns the port). 1462bound_address = listener .bind () 1463def shutdown (signum ,frame ): 1464self .running = False 1465signal .signal (signal .SIGTERM ,shutdown ) 1466signal .signal (signal .SIGINT ,shutdown ) 1467if hasattr (signal ,"SIGBREAK" ):# Windows: the signal a console Ctrl+Break / a closing console sends 1468signal .signal (signal .SIGBREAK ,shutdown ) 1469self ._mark_child ("no_child" )# (#4250) before the state exists: a host lost from here on, before it starts a server, is recoverable 1470self .state_fd = _write_new (self .state_path , (json .dumps ({"schema_version" :1 ,"profile" :self .name , 1471"socket" :bound_address ,"token" :self .token , 1472"host_pid" :os .getpid ()})+ "\n" ).encode ()) 1473self .starting = True 1474threading .Thread (target = self ._startup ,name = "strata-owner-startup" ,daemon = True ).start () 1475while self .running : 1476if self .die_with is not None and self ._die_with_gone (): 1477self ._say (f"the process this instance lives for (pid { self . die_with [ 0 ] } ) is gone: stopping the server and leaving" ) 1478self .running = False # the process this instance lives for is gone: stop (drained) and leave 1479break 1480if self .probe_result is not None and "error" in self .probe_result and \ 1481self .child is not None and self .child .poll ()is None : 1482self ._stop_child () 1483if self ._husk (): 1484# The server this host started has ended (or never started) and nothing is serving: a host that stays holds the profile's 1485# state and lease, and every later start refuses it until a person kills a pid that status does not point at (#4574 #4824). 1486# Status says "failed" and why for CHILD_EXIT_GRACE seconds, long enough for a client waiting for it; then the host leaves. 1487now = time .monotonic () 1488if self .gone_at is None : 1489self .gone_at = now 1490child = self .child 1491self ._say ("the server ended on its own" + (f" (exit code { child . returncode } )" if child is not None else 1492f" ( { self . last_error } )" )+ f"; this host leaves in { CHILD_EXIT_GRACE :.0f } s" ) 1493elif now - self .gone_at >= CHILD_EXIT_GRACE : 1494self .exit_status = 6 1495self .running = False 1496break 1497else : 1498self .gone_at = None 1499try : 1500connection = listener .accept () 1501except socket .timeout : 1502continue 1503if connection is None : 1504# A quiet timeout: the owner loops so it can still service its child. 1505continue 1506with connection : 1507connection .settimeout (5 ) 1508raw = bytearray () 1509try : 1510while len (raw )<= MAX_MESSAGE and b"\n" not in raw : 1511chunk = connection .recv (4096 ) 1512if not chunk : 1513break 1514raw .extend (chunk ) 1515if len (raw )> MAX_MESSAGE : 1516raise ValueError ("message too large" ) 1517request = json .loads (raw .split (b"\n" ,1 )[0 ]) 1518if not isinstance (request ,dict ): 1519raise ValueError ("request must be an object" ) 1520response = self ._handle (request ) 1521except (OSError ,ValueError ): 1522response = {"ok" :False ,"error" :"invalid_control_request" ,"exit_code" :2 } 1523try : 1524connection .sendall ((json .dumps (response ,ensure_ascii = False )+ "\n" ).encode ()) 1525except OSError : 1526pass 1527finally : 1528self .running = False 1529with self ._launch_lock :# no launch can begin after this, and one that is under way has finished 1530if self .child is not None and self .child .poll ()is None : 1531self ._stop_child () 1532self ._close_owner_pipe () 1533listener .close () 1534if WINDOWS and self .state_fd is not None : 1535# an open file cannot be deleted on Windows: the lease ends just before the state file does 1536_unlock_file (self .state_fd ) 1537os .close (self .state_fd ) 1538self .state_fd = None 1539try : 1540current = _read_state (self .name ) 1541if current and current .get ("token" )== self .token : 1542self .state_path .unlink (missing_ok = True ) 1543except ProfileError : 1544pass 1545if not owner_transport .WINDOWS : 1546# POSIX leaves a socket file behind; Windows leaves nothing (the listener's close 1547# releases the port). `Listener.close()` already unlinks the POSIX path, so this is 1548# a second, defensive attempt for the path the caller recorded. 1549Path (self .socket_path ).unlink (missing_ok = True ) 1550if self .ready_path is not None : 1551self .ready_path .unlink (missing_ok = True ) 1552_child_marker (self .name ,self .token ).unlink (missing_ok = True ) 1553for snapshot in tuple (self .rollback_snapshots ): 1554self ._retire_snapshot (snapshot ) 1555if self .state_fd is not None : 1556os .close (self .state_fd ) 1557_unlock_file (activity_lease ) 1558os .close (activity_lease ) 1559return self .exit_status 1560 1561 1562def main (argv :list [str ]| None = None )-> int : 1563quiet_crash_env ()# the host's children inherit it (strata_control/childenv.py) 1564parser = argparse .ArgumentParser (prog = "strata-runtime-host" ) 1565parser .add_argument ("--host" ,required = True ) 1566parser .add_argument ("--shutdown-timeout" ,type = float ,default = 30 ) 1567parser .add_argument ("--startup-wait" ,type = float ,default = 300 ) 1568parser .add_argument ("--expected-profile-revision" ) 1569parser .add_argument ("--expected-source-sha256" ) 1570parser .add_argument ("--die-with-pid" ,type = int ) 1571parser .add_argument ("--die-with-token" ) 1572args = parser .parse_args (argv ) 1573if not 0 <= args .shutdown_timeout <= 300 or not 1 <= args .startup_wait <= MAX_START_WAIT : 1574parser .error ("shutdown timeout must be 0..300" ) 1575if args .expected_profile_revision is not None and not re .fullmatch (r"[0-9a-f]{16}" ,args .expected_profile_revision ): 1576parser .error ("expected profile revision must be 16 lowercase hex characters" ) 1577if args .expected_source_sha256 is not None and not re .fullmatch (r"[0-9a-f]{64}" ,args .expected_source_sha256 ): 1578parser .error ("expected source digest must be 64 lowercase hex characters" ) 1579try : 1580die_with = (args .die_with_pid ,args .die_with_token )if args .die_with_pid and args .die_with_token else None 1581return Host (args .host ,args .shutdown_timeout ,args .startup_wait , 1582args .expected_profile_revision ,args .expected_source_sha256 ,die_with ).serve () 1583except (ProfileError ,OSError )as exc : 1584f"[strata runtime] host failed: { type ( exc ). __name__ } : { exc } " ,file = sys .stderr ) 1585return 6 1586 1587 1588if __name__ == "__main__" : 1589raise SystemExit (main ())