okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
326e39118
main
1"""The close-path matrix: every way a Strata server or app can end, and what must be true afterwards. 2 3After each case: no process of the tree that was running is left, the port is free, and the runtime's lease can be 4taken again (nothing holds it). With a real engine, `--vram` also checks that the GPU's memory came back. 5 6Run it directly (the pytest wrapper test_lifecycle_matrix.py runs the fake-engine cases on every platform): 7 8python tests/terminal/lifecycle_matrix.py --scenarios all --report matrix.json 9python tests/terminal/lifecycle_matrix.py --engine real --config /data/run.json --vram --scenarios serve-sigterm 10 11The engine is a small script behind the same manifest-declared entry point a real engine package has, unless 12`--engine real` names a run config. It never loads a model. 13""" 14from __future__import annotations 15 16import argparse 17import hashlib 18import json 19import os 20import signal 21import socket 22import subprocess 23import sys 24import tempfile 25import time 26import urllib .request 27from pathlib import Path 28 29ROOT = Path (__file__ ).resolve ().parents [2 ] 30sys .path .insert (0 ,str (ROOT )) 31 32import psutil # noqa: E402 33 34from strata_control import components ,engine_component as ec ,procs ,profiles ,runtime # noqa: E402 35 36WINDOWS = os .name == "nt" 37LINUX = sys .platform .startswith ("linux" ) 38BACKEND = "metal" if sys .platform == "darwin" else "cuda" # the family the fake package claims on this OS 39 40# Control words (STOP) are taken on a thread of their own, as the real engine does; everything else in order. 41FAKE_ENGINE = r''' 42import os, sys, threading, time 43from pathlib import Path 44mark = Path(os.environ["FAKE_ENGINE_MARK"]) 45(mark / "engine.pid").write_text(str(os.getpid())) 46stop = threading.Event() 47inbox = [] 48cv = threading.Condition() 49def note(name): (mark / name).write_text(str(time.time())) 50def reader(): 51for raw in sys.stdin: 52word = raw.split()[0] if raw.split() else "" 53if word == "STOP": 54stop.set(); note("stop"); continue 55with cv: 56inbox.append(raw); cv.notify() 57with cv: 58inbox.append(None); cv.notify() 59threading.Thread(target=reader, daemon=True).start() 60print("READY 4096 stop", flush=True) 61while True: 62with cv: 63while not inbox: cv.wait() 64line = inbox.pop(0) 65if line is None: # the server closed our stdin 66note("eof"); sys.exit(0) 67word = line.split()[0] if line.split() else "" 68if word == "QUIT": 69note("quit"); sys.exit(0) 70if word in ("GEN", "BGEN"): 71slow = int(os.environ.get("FAKE_ENGINE_SLOW_STEPS", "0")) 72slot = int(line.split()[1]) if word == "BGEN" else None 73steps = slow if (slow and not os.environ.get("FAKE_ENGINE_FAST_FIRST")) else 1 74stop.clear() 75note("busy") 76for _ in range(steps): 77print("T 97", flush=True) 78if stop.wait(0.2): 79break 80print("DONE 1 1 1.0 1.0 length 0 0 0", flush=True) 81if slot is not None: print(f"BADM {slot} 0", flush=True) 82''' 83 84 85if WINDOWS :# a parent that ignores Ctrl+C hands that to its children; the matrix must start servers that do not 86import ctypes 87ctypes .windll .kernel32 .SetConsoleCtrlHandler (None ,False ) 88 89 90def free_port ()-> int : 91with socket .socket ()as s : 92s .bind (("127.0.0.1" ,0 )) 93return s .getsockname ()[1 ] 94 95 96def port_open (port :int )-> bool : 97with socket .socket ()as s : 98s .settimeout (0.5 ) 99return s .connect_ex (("127.0.0.1" ,port ))== 0 100 101 102def install_fake_engine (components_dir :Path )-> Path : 103folder = components_dir / "engine" / f"0.1.45- { components . host_platform () } - { BACKEND } " 104folder .mkdir (parents = True ) 105 (folder / "engine_main.py" ).write_text (FAKE_ENGINE ,encoding = "utf-8" ) 106if WINDOWS : 107entry = "engine.cmd" 108 (folder / entry ).write_bytes (f'@echo off\r\n" { sys . executable } " "%~dp0engine_main.py" %*\r\n' .encode ()) 109else : 110entry = "engine" 111 (folder / entry ).write_text (f'#!/bin/sh\nexec " { sys . executable } " "$(dirname "$0")/engine_main.py" "$@"\n' ) 112 (folder / entry ).chmod (0o755 ) 113files = [{"path" :name ,"sha256" :hashlib .sha256 ((folder / name ).read_bytes ()).hexdigest (), 114"bytes" : (folder / name ).stat ().st_size }for name in (entry ,"engine_main.py" )] 115 (folder / ec .MANIFEST ).write_text (json .dumps ({ 116"schema_version" :1 ,"id" :"strata-engine" ,"version" :"0.1.45" ,"platform" :components .host_platform (), 117"backend" :BACKEND ,"entrypoint" :entry ,"files" :files }),encoding = "utf-8" ) 118return folder 119 120 121def vram_used_mib ()-> int | None : 122try : 123out = subprocess .run (["nvidia-smi" ,"--query-gpu=memory.used" ,"--format=csv,noheader,nounits" ], 124capture_output = True ,text = True ,timeout = 20 ).stdout .split () 125return sum (int (v )for v in out ) 126except (OSError ,ValueError ,subprocess .SubprocessError ): 127return None 128 129 130class Rig : 131"""A throwaway Strata home: state, runtime, profile and (fake or real) engine config.""" 132 133def __init__ (self ,root :Path ,* ,real_config :Path | None = None ,real_components :Path | None = None , 134slow_steps :int = 0 ): 135self .root = root 136self .real = real_config is not None 137self .port = free_port () 138self .components = root / "components" 139self .components .mkdir () 140self .mark = root / "mark" 141self .mark .mkdir () 142self .state = root / "state" 143self .state .mkdir () 144self .env = {** os .environ ,"STRATA_PROFILE_DIR" :str (root / "profiles" ),"STRATA_RUNTIME_DIR" :str (root / "runtime" ), 145"STRATA_COMPONENTS_DIR" :str (self .components ),"STRATA_ENGINE_BACKEND" :BACKEND , 146"STRATA_NO_ACQUIRE" :"1" ,"FAKE_ENGINE_MARK" :str (self .mark ),"LOCALAPPDATA" :str (self .state ), 147"XDG_STATE_HOME" :str (self .state ),"PYTHONPATH" :str (ROOT ),"PYTHONUNBUFFERED" :"1" , 148"FAKE_ENGINE_SLOW_STEPS" :str (slow_steps )} 149self .env .pop ("STRATA_API_KEY" ,None ) 150for key in ("STRATA_PROFILE_DIR" ,"STRATA_RUNTIME_DIR" ,"LOCALAPPDATA" ,"XDG_STATE_HOME" ,"STRATA_COMPONENTS_DIR" , 151"STRATA_NO_ACQUIRE" ,"STRATA_ENGINE_BACKEND" ,"FAKE_ENGINE_MARK" ,"FAKE_ENGINE_SLOW_STEPS" ): 152os .environ [key ]= self .env [key ]# this process reads the same folders (profiles, runtime) 153if real_components is not None : 154self .env ["STRATA_COMPONENTS_DIR" ]= os .environ ["STRATA_COMPONENTS_DIR" ]= str (real_components ) 155if real_config is not None : 156cfg = json .loads (real_config .read_text (encoding = "utf-8" )) 157cfg .update ({"host" :"127.0.0.1" ,"port" :self .port }) 158if cfg .get ("log" ): 159cfg ["log" ]= str (root / "engine.log" )# never the real install's log 160self .config = root / "run.json" 161self .config .write_text (json .dumps (cfg ),encoding = "utf-8" ) 162else : 163install_fake_engine (self .components ) 164from tools .strata_tokenizer import BYTE_TO_UNICODE 165tokenizer = root / "tokenizer" 166tokenizer .mkdir () 167tokens = [BYTE_TO_UNICODE [i ]for i in range (256 )]+ ["ab" ,"<|im_start|>" ,"<|im_end|>" ,"<|endoftext|>" ] 168 (tokenizer / "vocab.json" ).write_text (json .dumps ({token :i for i ,token in enumerate (tokens )})) 169 (tokenizer / "merges.txt" ).write_text ("a b" ) 170 (tokenizer / "token_type.json" ).write_text (json .dumps ([0 ]* 257 + [3 ,3 ,3 ])) 171self .config = root / "run.json" 172self .config .write_text (json .dumps ({"exe" :"component:strata-engine" ,"backend" :BACKEND , 173"tokenizer" :str (tokenizer ),"args" : [],"cwd" :str (root ), 174"model_name" :"fake" ,"host" :"127.0.0.1" ,"port" :self .port }), 175encoding = "utf-8" ) 176profiles .create ("app" ,str (self .config )) 177 178# ------------------------------------------------------------------------------------- starting 179def serve_argv (self )-> list [str ]: 180return [sys .executable ,str (ROOT / "strata.py" ),"serve" ,"--profile" ,"app" ,"--port" ,str (self .port ), 181"--host" ,"127.0.0.1" ,"--shutdown-timeout" ,"5" ] 182 183def wait_ready (self ,proc = None ,seconds = None )-> None : 184seconds = seconds or (480 if self .real else 120 ) 185deadline = time .monotonic ()+ seconds 186while time .monotonic ()< deadline : 187if proc is not None and proc .poll ()is not None : 188raise RuntimeError (f"the server exited with { proc . returncode } before it was ready" ) 189if port_open (self .port ): 190try : 191urllib .request .urlopen (f"http://127.0.0.1: { self . port } /health" ,timeout = 3 ).read () 192return 193except OSError : 194pass 195time .sleep (0.25 ) 196raise RuntimeError ("the server was not ready in time" ) 197 198def tree (self ,pid :int )-> list [procs .Ident ]: 199"""The process and everything below it, with the facts that tell them from a later process.""" 200found = [] 201try : 202family = [psutil .Process (pid ),* psutil .Process (pid ).children (recursive = True )] 203except psutil .Error : 204return found 205for p in family : 206token = procs .start_token (p .pid ) 207if token : 208found .append (procs .Ident (p .pid ,token ,tuple (procs .command_line (p .pid )or []))) 209return found 210 211def engine_idents (self )-> list [procs .Ident ]: 212"""Every live process that is this run's engine (found by its recorded launch, not by a name).""" 213return [procs .Ident (r ["pid" ],r ["token" ],tuple (r ["cmd" ]))for r in procs .records () 214if r .get ("role" )in ("engine" ,"server" )and procs .start_token (r ["pid" ])== r ["token" ]] 215 216# ------------------------------------------------------------------------------------- checking 217def survivors (self ,idents )-> list [str ]: 218return [f" { i . pid } { ' ' . join ( i . cmd )[: 90 ] } " for i in idents if procs .start_token (i .pid )== i .token ] 219 220def wait_gone (self ,idents ,seconds = 45 )-> list [str ]: 221deadline = time .monotonic ()+ seconds 222left = self .survivors (idents ) 223while left and time .monotonic ()< deadline : 224time .sleep (0.25 ) 225left = self .survivors (idents ) 226return left 227 228def lease_free (self )-> bool : 229try : 230fd = runtime .acquire_activity_lease (shared = False ) 231except Exception :# noqa: BLE001 232return False 233runtime ._unlock_file (fd ) 234os .close (fd ) 235return True 236 237def marks (self )-> list [str ]: 238return sorted (p .name for p in self .mark .iterdir ()) 239 240def clear_marks (self )-> None : 241for p in self .mark .iterdir (): 242p .unlink () 243 244 245# ------------------------------------------------------------------------------------------- actions 246 247def _default_signals ()-> None : 248for sig in (signal .SIGINT ,signal .SIGHUP ,signal .SIGTERM ): 249signal .signal (sig ,signal .SIG_DFL ) 250 251 252def spawn_serve (rig :Rig ,* ,new_console :bool = False ,session :bool = True )-> subprocess .Popen : 253log = open (rig .root / "serve.log" ,"ab" ) 254kw :dict = {} 255if WINDOWS : 256kw ["creationflags" ]= subprocess .CREATE_NEW_CONSOLE if new_console else subprocess .CREATE_NEW_PROCESS_GROUP 257if new_console : 258info = subprocess .STARTUPINFO () 259info .dwFlags |= subprocess .STARTF_USESHOWWINDOW 260info .wShowWindow = 7 # minimized, not activated 261kw ["startupinfo" ]= info 262elif session : 263kw ["start_new_session" ]= True # its own process group, like a job in a shell 264kw ["preexec_fn" ]= _default_signals # a harness started in the background inherits "ignore" 265proc = subprocess .Popen (rig .serve_argv (),cwd = ROOT ,env = rig .env ,stdin = subprocess .DEVNULL ,stdout = log , 266stderr = subprocess .STDOUT ,** kw ) 267log .close () 268return proc 269 270 271def windows_console_event (pid :int ,kind :str )-> None : 272"""Ctrl+C ('ctrl-c') or the window's close box ('close') on the console `pid` is attached to.""" 273code = ( 274"import ctypes, sys, time\n" 275"k = ctypes.windll.kernel32\n" 276"k.FreeConsole()\n" 277f"assert k.AttachConsole( { pid } ), 'AttachConsole failed'\n" 278"if sys.argv[1] == 'ctrl-c':\n" 279" k.SetConsoleCtrlHandler(None, 1)\n" 280" k.GenerateConsoleCtrlEvent(0, 0)\n" 281" time.sleep(1.5)\n" 282"else:\n" 283" hwnd = k.GetConsoleWindow()\n" 284" assert hwnd, 'no console window'\n" 285" ctypes.windll.user32.PostMessageW(hwnd, 0x0010, 0, 0)\n" 286" time.sleep(1.0)\n" 287 ) 288# for "close" the helper is attached to the console that is closing, so the system ends it too: that exit is expected 289done = subprocess .run ([sys .executable ,"-c" ,code ,kind ],creationflags = subprocess .DETACHED_PROCESS ,timeout = 30 ) 290if kind == "ctrl-c" and done .returncode != 0 : 291raise RuntimeError (f"could not send Ctrl+C (helper exit { done . returncode } )" ) 292 293 294def kill_hard (pid :int )-> None : 295if WINDOWS : 296subprocess .run (["taskkill" ,"/F" ,"/PID" ,str (pid )],capture_output = True )# this one process, not its tree 297else : 298os .kill (pid ,signal .SIGKILL ) 299 300 301def pty_close (rig :Rig ): 302"""A terminal: the server runs as the session leader of a pseudo-terminal; closing the master is the window closing.""" 303import pty 304pid ,master = pty .fork () 305if pid == 0 : 306os .chdir (ROOT ) 307_default_signals () 308os .execve (sys .executable ,rig .serve_argv (),rig .env ) 309return pid ,master 310 311 312# ------------------------------------------------------------------------------------------ scenarios 313 314class Result (dict ): 315pass 316 317 318def finish (rig :Rig ,name :str ,idents ,* ,expect_graceful :bool | None ,note :str = "" ,vram_before = None , 319vram :bool = False ,wait :float = 45 ,stopped_text :str | None = None ,vram_during = None )-> Result : 320left = rig .wait_gone (idents ,wait ) 321problems = [] 322if left : 323problems .append (f"processes left: { left } " ) 324deadline = time .monotonic ()+ 10 # a closing process's sockets go a moment after it 325while port_open (rig .port )and time .monotonic ()< deadline : 326time .sleep (0.2 ) 327if port_open (rig .port ): 328problems .append ("port still open" ) 329if not rig .lease_free (): 330problems .append ("lease still held" ) 331marks = rig .marks () 332if expect_graceful is True and not rig .real and not ({"quit" ,"eof" }& set (marks )): 333problems .append (f"engine was not asked to quit (marks { marks } )" ) 334if vram and vram_before is not None : 335deadline = time .monotonic ()+ 30 336used = vram_used_mib () 337while used is not None and used > vram_before + 300 and time .monotonic ()< deadline : 338time .sleep (1 ) 339used = vram_used_mib () 340if used is not None and used > vram_before + 300 : 341problems .append (f"VRAM not freed: { used } MiB used, { vram_before } before" ) 342note += f" vram { vram_before } -> { vram_during } -> { used } MiB" 343if vram_during is not None and vram_during <= vram_before + 500 : 344problems .append (f"the engine never held GPU memory ( { vram_during } MiB while running), so the check proves nothing" ) 345return Result (name = name ,ok =not problems ,problems = problems ,graceful = ("quit" in marks or "eof" in marks ), 346marks = marks ,note = note .strip (),stopped = stopped_text ) 347 348 349def serve_case (rig :Rig ,name :str ,action ,* ,graceful :bool | None ,vram :bool = False , 350new_console :bool = False ,wait :float = 45 )-> Result : 351rig .clear_marks () 352before = vram_used_mib ()if vram else None 353proc = spawn_serve (rig ,new_console = new_console ) 354try : 355rig .wait_ready (proc ) 356idents = rig .tree (proc .pid ) 357idents += [i for i in rig .engine_idents ()if i .pid not in {x .pid for x in idents }] 358if not any ("engine" in " " .join (i .cmd )or "--serve" in " " .join (i .cmd )for i in idents ): 359raise RuntimeError (f"no engine in the tree: { [ ' ' . join ( i . cmd )[: 60 ] for i in idents ] } " ) 360during = vram_used_mib ()if vram else None 361t0 = time .monotonic () 362action (rig ,proc ) 363out = finish (rig ,name ,idents ,expect_graceful = graceful ,vram_before = before ,vram = vram ,wait = wait , 364vram_during = during ) 365out ["seconds" ]= round (time .monotonic ()- t0 ,1 ) 366text = (rig .root / "serve.log" ).read_text (errors = "replace" )if (rig .root / "serve.log" ).exists ()else "" 367out ["stopped" ]= "[strata] stopped" in text 368if graceful is True and not out ["stopped" ]: 369out ["problems" ].append ("the server did not print its clean-stop line" );out ["ok" ]= False 370return out 371finally : 372if proc .poll ()is None : 373proc .kill () 374try : 375proc .wait (timeout = 10 ) 376except subprocess .TimeoutExpired : 377pass 378for i in rig .tree (proc .pid ): 379if procs .start_token (i .pid )== i .token : 380try : 381psutil .Process (i .pid ).kill () 382except psutil .Error : 383pass 384keep = os .environ .get ("STRATA_MATRIX_LOGS" )# keep the server's and engine's logs as evidence 385if keep : 386Path (keep ).mkdir (parents = True ,exist_ok = True ) 387for log in ("serve.log" ,"engine.log" ): 388if (rig .root / log ).exists (): 389 (Path (keep )/ f" { name } . { log } " ).write_bytes ((rig .root / log ).read_bytes ()) 390 (rig .root / "serve.log" ).write_bytes (b"" ) 391 392 393def sigint_group (rig ,proc ):# Ctrl+C in a terminal: SIGINT to the whole foreground group 394os .killpg (proc .pid ,signal .SIGINT ) 395 396 397def sigterm (rig ,proc ): 398os .kill (proc .pid ,signal .SIGTERM ) 399 400 401def sighup (rig ,proc ):# what ssh dropping the connection does to the shell's job 402os .killpg (proc .pid ,signal .SIGHUP ) 403 404 405def kill9_parent (rig ,proc ): 406kill_hard (proc .pid ) 407 408 409def win_ctrl_break (rig ,proc ): 410os .kill (proc .pid ,signal .CTRL_BREAK_EVENT ) 411 412 413def win_ctrl_c (rig ,proc ): 414windows_console_event (proc .pid ,"ctrl-c" ) 415 416 417def win_console_close (rig ,proc ): 418windows_console_event (proc .pid ,"close" ) 419 420 421def busy_sigterm (rig ,proc ): 422"""A request is running when the stop arrives: it must be cancelled, not waited for.""" 423import threading 424started = threading .Event () 425 426def ask (): 427try : 428body = json .dumps ({"model" :"fake" ,"messages" : [{"role" :"user" ,"content" :"hi" }],"max_tokens" :4000 if rig .real else 200 , 429"stream" :True }).encode () 430req = urllib .request .Request (f"http://127.0.0.1: { rig . port } /v1/chat/completions" ,data = body , 431headers = {"content-type" :"application/json" }) 432started .set () 433urllib .request .urlopen (req ,timeout = 60 ).read () 434except OSError : 435pass 436threading .Thread (target = ask ,daemon = True ).start () 437started .wait (5 ) 438deadline = time .monotonic ()+ 10 439while not rig .real and "busy" not in rig .marks ()and time .monotonic ()< deadline : 440time .sleep (0.1 ) 441if rig .real : 442time .sleep (4 )# the real engine is reading the prompt / generating by now 443 (sigterm if not WINDOWS else win_ctrl_break )(rig ,proc ) 444 445 446def nohup_case (rig :Rig ,name :str = "serve-nohup-keeps-serving" ,* ,vram :bool = False )-> Result : 447"""`nohup strata serve &` asks to outlive its terminal: a hangup that was ignored at start is still ignored, and the 448server stops on SIGTERM as usual. (An ordinary server stops on SIGHUP: serve-sighup.)""" 449rig .clear_marks () 450before = vram_used_mib ()if vram else None 451log = open (rig .root / "serve.log" ,"ab" ) 452 453def ignore_hangup (): 454_default_signals () 455signal .signal (signal .SIGHUP ,signal .SIG_IGN ) 456proc = subprocess .Popen (rig .serve_argv (),cwd = ROOT ,env = rig .env ,stdin = subprocess .DEVNULL ,stdout = log , 457stderr = subprocess .STDOUT ,start_new_session = True ,preexec_fn = ignore_hangup ) 458log .close () 459try : 460rig .wait_ready (proc ) 461idents = rig .tree (proc .pid ) 462idents += [i for i in rig .engine_idents ()if i .pid not in {x .pid for x in idents }] 463during = vram_used_mib ()if vram else None 464os .killpg (proc .pid ,signal .SIGHUP )# the terminal closes 465time .sleep (3 ) 466problems = [] 467if proc .poll ()is not None or not port_open (rig .port ): 468problems .append ("the server stopped on a hangup it was told to ignore" ) 469t0 = time .monotonic () 470os .kill (proc .pid ,signal .SIGTERM ) 471out = finish (rig ,name ,idents ,expect_graceful = True ,vram_before = before ,vram = vram ,vram_during = during ) 472out ["seconds" ]= round (time .monotonic ()- t0 ,1 ) 473out ["problems" ]= problems + out ["problems" ] 474out ["ok" ]= not out ["problems" ] 475return out 476finally : 477if proc .poll ()is None : 478proc .kill () 479for i in rig .tree (proc .pid ): 480if procs .start_token (i .pid )== i .token : 481try : 482psutil .Process (i .pid ).kill () 483except psutil .Error : 484pass 485 486 487def pty_close_case (rig :Rig ,name :str = "serve-terminal-closed" ,* ,vram :bool = False )-> Result : 488rig .clear_marks () 489before = vram_used_mib ()if vram else None 490pid ,master = pty_close (rig ) 491try : 492class _P :# just enough of Popen for wait_ready 493returncode = None 494 495def poll (self_inner ): 496done ,_ = os .waitpid (pid ,os .WNOHANG ) 497self_inner .returncode = 0 if done else None 498return 0 if done else None 499rig .wait_ready (_P ()) 500idents = rig .tree (pid ) 501idents += [i for i in rig .engine_idents ()if i .pid not in {x .pid for x in idents }] 502during = vram_used_mib ()if vram else None 503t0 = time .monotonic () 504os .close (master )# the window is closed 505out = finish (rig ,name ,idents ,expect_graceful = True ,vram_before = before ,vram = vram ,vram_during = during ) 506out ["seconds" ]= round (time .monotonic ()- t0 ,1 ) 507return out 508finally : 509try : 510os .kill (pid ,signal .SIGKILL ) 511except OSError : 512pass 513try : 514os .waitpid (pid ,0 ) 515except OSError : 516pass 517 518 519# --- the detached service (`strata runtime start`) ------------------------------------------------ 520 521def runtime_start (rig :Rig ,die_with :int | None = None )-> dict : 522argv = [sys .executable ,str (ROOT / "strata.py" ),"runtime" ,"start" ,"--profile" ,"app" ,"--wait" ,"400" if rig .real else "240" , 523"--shutdown-timeout" ,"5" ,"--output" ,"json" ] 524if die_with : 525argv += ["--die-with-pid" ,str (die_with )] 526out = subprocess .run (argv ,cwd = ROOT ,env = rig .env ,capture_output = True ,text = True ,timeout = 500 ) 527try : 528return json .loads (out .stdout ) 529except ValueError : 530raise RuntimeError (f"runtime start gave { out . returncode } : { out . stdout [ - 300 :] } { out . stderr [ - 300 :] } " )from None 531 532 533def runtime_stop (rig :Rig )-> dict : 534out = subprocess .run ([sys .executable ,str (ROOT / "strata.py" ),"runtime" ,"stop" ,"--profile" ,"app" ,"--wait" ,"60" , 535"--output" ,"json" ],cwd = ROOT ,env = rig .env ,capture_output = True ,text = True ,timeout = 120 ) 536try : 537return json .loads (out .stdout ) 538except ValueError : 539return {"ok" :False ,"raw" :out .stdout [- 300 :]+ out .stderr [- 300 :]} 540 541 542def owner_pid (rig :Rig )-> int : 543return runtime ._read_state ("app" )["host_pid" ] 544 545 546def sleeper_process ()-> subprocess .Popen : 547return subprocess .Popen ([sys .executable ,"-c" ,"import time; time.sleep(600)" ], 548creationflags = getattr (subprocess ,"CREATE_NO_WINDOW" ,0 )) 549 550 551def runtime_case (rig :Rig ,name :str ,what :str ,* ,vram :bool = False )-> Result : 552rig .clear_marks () 553before = vram_used_mib ()if vram else None 554holder = sleeper_process ()if what == "die-with" else None 555try : 556started = runtime_start (rig ,die_with = holder .pid if holder else None ) 557if started .get ("state" )!= "ready" : 558raise RuntimeError (f"not ready: { started } " ) 559owner = owner_pid (rig ) 560idents = rig .tree (owner ) 561during = vram_used_mib ()if vram else None 562t0 = time .monotonic () 563graceful = True 564note = "" 565if what == "stop" : 566res = runtime_stop (rig ) 567note = f"stop -> { res . get ( 'state' ) } " 568elif what == "terminal-gone" : 569# the command that started it is long gone; the service must still be serving 570time .sleep (1.5 ) 571note = "still serving: " + str (port_open (rig .port )) 572if not port_open (rig .port ): 573raise RuntimeError ("the background service died with its terminal" ) 574res = runtime_stop (rig ) 575elif what == "owner-killed" : 576kill_hard (owner ) 577graceful = None 578elif what == "server-killed" : 579server = next (i for i in idents if "serve.server" in " " .join (i .cmd )) 580kill_hard (server .pid ) 581graceful = None 582note = "server killed, owner left alive" 583idents = [i for i in idents if "strata_control.runtime" not in " " .join (i .cmd )and "conhost" not in " " .join (i .cmd )] 584elif what == "die-with" : 585holder .kill ();holder .wait (timeout = 10 ) 586if what == "server-killed" : 587# the server and engine are gone; the owner host stays to report the failure until it is told to stop 588out = finish (rig ,name ,idents ,expect_graceful = graceful ,vram_before = before ,vram = vram ,note = note ,wait = 60 , 589vram_during = during ) 590out ["problems" ]= [p for p in out ["problems" ]if p != "lease still held" ] 591res = runtime_stop (rig ) 592out ["stop_after" ]= res .get ("state" ) 593left = rig .wait_gone (rig .tree (owner )or [],30 ) 594if left or not rig .lease_free (): 595out ["problems" ].append (f"after runtime stop: { left } lease_free= { rig . lease_free () } " ) 596out ["ok" ]= not out ["problems" ] 597return out 598out = finish (rig ,name ,idents ,expect_graceful = graceful ,vram_before = before ,vram = vram ,note = note ,wait = 60 , 599vram_during = during ) 600out ["seconds" ]= round (time .monotonic ()- t0 ,1 ) 601if what == "owner-killed" : 602res = runtime_stop (rig )# the next stop clears the private state of a lost owner 603out ["stop_after" ]= res .get ("state" ) 604if runtime ._read_state ("app" )is not None : 605out ["problems" ].append ("state file left after stop" );out ["ok" ]= False 606return out 607finally : 608if holder and holder .poll ()is None : 609holder .kill () 610try : 611if runtime ._read_state ("app" )is not None : 612runtime_stop (rig ) 613except Exception :# noqa: BLE001 614pass 615for i in rig .engine_idents (): 616try : 617psutil .Process (i .pid ).kill () 618except psutil .Error : 619pass 620 621 622def windows_press (pid :int ,text :str )-> None : 623"""Type `text` into the console `pid` is attached to (what a person at the keyboard does).""" 624code = ( 625"import ctypes, sys\n" 626"from ctypes import wintypes\n" 627"k = ctypes.windll.kernel32\n" 628"class Key(ctypes.Structure):\n" 629" _fields_ = [('down', wintypes.BOOL), ('repeat', wintypes.WORD), ('vk', wintypes.WORD), ('scan', wintypes.WORD),\n" 630" ('char', wintypes.WCHAR), ('state', wintypes.DWORD)]\n" 631"class Rec(ctypes.Structure):\n" 632" _fields_ = [('kind', wintypes.WORD), ('pad', wintypes.WORD), ('key', Key)]\n" 633"k.FreeConsole()\n" 634f"assert k.AttachConsole( { pid } ), 'AttachConsole failed'\n" 635"k.CreateFileW.restype = wintypes.HANDLE\n" 636"h = k.CreateFileW('CONIN$', 0xC0000000, 3, None, 3, 0, None)\n" 637"recs = []\n" 638"for ch in sys.argv[1]:\n" 639" for down in (1, 0):\n" 640" recs.append(Rec(1, 0, Key(down, 1, ord(ch.upper()), 0, ch, 0)))\n" 641"arr = (Rec * len(recs))(*recs)\n" 642"n = wintypes.DWORD()\n" 643"assert k.WriteConsoleInputW(h, arr, len(recs), ctypes.byref(n)), 'WriteConsoleInput failed'\n" 644 ) 645subprocess .run ([sys .executable ,"-c" ,code ,text ],creationflags = subprocess .DETACHED_PROCESS ,check = True ,timeout = 30 ) 646 647 648def monitor_case (rig :Rig ,how :str )-> Result : 649"""The Textual monitor starts no engine. Quitting it (`q`) or killing it ends the monitor and leaves a service 650started elsewhere untouched; nothing of the monitor is left behind.""" 651rig .clear_marks () 652started = runtime_start (rig ) 653if started .get ("state" )!= "ready" : 654raise RuntimeError (f"not ready: { started } " ) 655owner = owner_pid (rig ) 656service = rig .tree (owner ) 657argv = [sys .executable ,str (ROOT / "strata.py" ),"monitor" ,"--url" ,f"http://127.0.0.1: { rig . port } " ] 658env = {** rig .env ,"TERM" :"xterm-256color" ,"COLUMNS" :"120" ,"LINES" :"40" } 659master = child = None 660if WINDOWS : 661info = subprocess .STARTUPINFO () 662info .dwFlags |= subprocess .STARTF_USESHOWWINDOW 663info .wShowWindow = 7 664monitor = subprocess .Popen (argv ,cwd = ROOT ,env = env ,creationflags = subprocess .CREATE_NEW_CONSOLE ,startupinfo = info ) 665pid ,alive = monitor .pid ,lambda :monitor .poll ()is None 666else : 667import fcntl ,pty ,struct ,termios 668child ,master = pty .fork () 669if child == 0 : 670os .chdir (ROOT ) 671_default_signals () 672fcntl .ioctl (0 ,termios .TIOCSWINSZ ,struct .pack ("HHHH" ,40 ,120 ,0 ,0 ))# a terminal that has a size 673os .execve (sys .executable ,argv ,env ) 674pid = child 675gone = [] 676 677def drain ():# a TUI paints without pause; a full pty buffer would freeze it 678while True : 679try : 680if not os .read (master ,65536 ): 681return 682except OSError : 683return 684import threading 685threading .Thread (target = drain ,daemon = True ).start () 686 687def alive (): 688if gone : 689return False 690try : 691done ,_ = os .waitpid (child ,os .WNOHANG ) 692except ChildProcessError : 693done = child 694if done : 695gone .append (True ) 696return not done 697problems = [] 698time .sleep (4 ) 699if not alive (): 700problems .append ("the monitor did not stay up (is Textual installed here?)" ) 701mine = rig .tree (pid ) 702if how == "quit" : 703if WINDOWS : 704windows_press (pid ,"q" ) 705else : 706os .write (master ,b"q" ) 707else : 708kill_hard (pid ) 709deadline = time .monotonic ()+ 15 710while alive ()and time .monotonic ()< deadline : 711time .sleep (0.2 ) 712if alive (): 713problems .append (f"the monitor did not end on ' { how } '" ) 714if master is not None : 715os .close (master ) 716left = rig .wait_gone (mine ,15 ) 717if left : 718problems .append (f"monitor processes left: { left } " ) 719if not port_open (rig .port )or rig .survivors (service )!= [f" { i . pid } { ' ' . join ( i . cmd )[: 90 ] } " for i in service 720if procs .start_token (i .pid )== i .token ]: 721problems .append ("the monitor's end disturbed the service" ) 722runtime_stop (rig ) 723left = rig .wait_gone (service ,45 ) 724if left : 725problems .append (f"service left after stop: { left } " ) 726return Result (name = f"monitor- { how } -leaves-service-alone" ,ok =not problems ,problems = problems ,marks = rig .marks (),note = "" ) 727 728 729SCENARIOS = { 730# foreground `strata serve` 731"serve-ctrl-c" :lambda rig ,v :serve_case (rig ,"serve-ctrl-c" ,win_ctrl_c if WINDOWS else sigint_group , 732graceful = True ,vram = v ,new_console = WINDOWS ), 733"serve-sigterm" :lambda rig ,v :serve_case (rig ,"serve-sigterm" ,sigterm ,graceful = True ,vram = v ), 734"serve-sighup" :lambda rig ,v :serve_case (rig ,"serve-sighup" ,sighup ,graceful = True ,vram = v ), 735"serve-ctrl-break" :lambda rig ,v :serve_case (rig ,"serve-ctrl-break" ,win_ctrl_break ,graceful = True ,vram = v ), 736"serve-console-close" :lambda rig ,v :serve_case (rig ,"serve-console-close" ,win_console_close ,graceful = None , 737vram = v ,new_console = True ), 738"serve-kill-parent" :lambda rig ,v :serve_case (rig ,"serve-kill-parent" ,kill9_parent ,graceful = None ,vram = v ), 739"serve-busy-stop" :lambda rig ,v :serve_case (rig ,"serve-busy-stop" ,busy_sigterm ,graceful = True ,vram = v ), 740"serve-terminal-closed" :lambda rig ,v :pty_close_case (rig ,vram = v ), 741"serve-nohup-keeps-serving" :lambda rig ,v :nohup_case (rig ,vram = v ), 742# `strata runtime start` (a background service by design) 743"runtime-stop" :lambda rig ,v :runtime_case (rig ,"runtime-stop" ,"stop" ,vram = v ), 744"runtime-survives-terminal" :lambda rig ,v :runtime_case (rig ,"runtime-survives-terminal" ,"terminal-gone" ,vram = v ), 745"runtime-owner-killed" :lambda rig ,v :runtime_case (rig ,"runtime-owner-killed" ,"owner-killed" ,vram = v ), 746"runtime-server-killed" :lambda rig ,v :runtime_case (rig ,"runtime-server-killed" ,"server-killed" ,vram = v ), 747"runtime-die-with" :lambda rig ,v :runtime_case (rig ,"runtime-die-with" ,"die-with" ,vram = v ), 748# the TUI 749"monitor-quit" :lambda rig ,v :monitor_case (rig ,"quit" ), 750"monitor-killed" :lambda rig ,v :monitor_case (rig ,"kill" ), 751} 752POSIX_ONLY = {"serve-sigterm" ,"serve-sighup" ,"serve-terminal-closed" ,"serve-nohup-keeps-serving" } 753WINDOWS_ONLY = {"serve-ctrl-break" ,"serve-console-close" } 754 755 756def applicable (name :str )-> bool : 757if WINDOWS : 758return name not in POSIX_ONLY 759return name not in WINDOWS_ONLY 760 761 762def run (names :list [str ],* ,real_config :Path | None = None ,real_components :Path | None = None , 763vram :bool = False ,slow_steps :int = 600 )-> list [Result ]: 764results = [] 765for name in names : 766saved = dict (os .environ )# a Rig points this process at its own folders; give them back 767with tempfile .TemporaryDirectory (prefix = "strata-matrix-" )as tmp : 768rig = Rig (Path (tmp ),real_config = real_config ,real_components = real_components ,slow_steps = slow_steps if name == "serve-busy-stop" else 0 ) 769try : 770result = SCENARIOS [name ](rig ,vram ) 771except Exception as exc :# noqa: BLE001 772result = Result (name = name ,ok = False ,problems = [f" { type ( exc ). __name__ } : { exc } " ],marks = []) 773results .append (result ) 774"PASS " if result ["ok" ]else "FAIL " )+ name ,result .get ("seconds" ,"" ),result .get ("problems" )or "" , 775result .get ("note" ,"" ),flush = True ) 776try : 777runtime_stop (rig ) 778except Exception :# noqa: BLE001 779pass 780for ident in rig .engine_idents (): 781try : 782psutil .Process (ident .pid ).kill () 783except psutil .Error : 784pass 785os .environ .clear () 786os .environ .update (saved ) 787return results 788 789 790def main (argv = None )-> int : 791ap = argparse .ArgumentParser () 792ap .add_argument ("--scenarios" ,default = "all" ) 793ap .add_argument ("--config" ,help = "a real engine's run config (then no fake engine is used)" ) 794ap .add_argument ("--components" ,help = "the engine component folder for --config (STRATA_COMPONENTS_DIR)" ) 795ap .add_argument ("--vram" ,action = "store_true" ,help = "check nvidia-smi memory returns" ) 796ap .add_argument ("--report" ) 797a = ap .parse_args (argv ) 798names = [n for n in SCENARIOS if applicable (n )]if a .scenarios == "all" else a .scenarios .split ("," ) 799results = run (names ,real_config = Path (a .config )if a .config else None , 800real_components = Path (a .components )if a .components else None ,vram = a .vram ) 801if a .report : 802Path (a .report ).write_text (json .dumps ({"platform" :sys .platform ,"engine" :"real" if a .config else "fake" , 803"results" :results },indent = 1 ),encoding = "utf-8" ) 804return 0 if all (r ["ok" ]for r in results )else 1 805 806 807if __name__ == "__main__" : 808raise SystemExit (main ())