okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
326e39118
main
1#!/usr/bin/env python3 2"""The installed Windows app, closed every way, with a stub engine: nothing may be left running. 3 4python apps/desktop/scripts/app-close-matrix.py --install <folder the installer wrote> [--scenarios all] [--report out.json] 5 6For each case it starts the REAL installed `strata-desktop.exe` (its window opens), loads a stub engine through the host's API 7(profile + `runtime start` under Control's owner runtime, exactly the app's path), records every process of the tree (the app, 8the host, Control, the owner host, the server, the engine), ends the app one way, and asserts: 9* no process of the tree is left, the engine's port is free, the runtime lease can be taken again; 10* the engine got the clean stop where the way of closing allows one (normal close, window X); 11* the next load of the same slot works (a lost owner's state is cleaned, not a blocker). 12It also proves a second launch focuses the open window and starts nothing, and that one app runs two engines and closes both. 13Everything per-user lives under a scratch folder; the stub engine is a script. No real engine ever runs. 14""" 15from __future__import annotations 16 17import argparse 18import ctypes 19import json 20import os 21import subprocess 22import sys 23import tempfile 24import time 25import urllib .error 26import urllib .request 27from ctypes import wintypes 28from pathlib import Path 29 30ROOT = Path (__file__ ).resolve ().parents [3 ] 31sys .path .insert (0 ,str (ROOT )) 32 33import psutil # noqa: E402 34 35from strata_control import procs ,runtime # noqa: E402 36from tests .terminal .lifecycle_matrix import install_fake_engine ,port_open # noqa: E402 37 38if os .name != "nt" : 39raise SystemExit ("this matrix drives the Windows installer's app" ) 40 41user32 = ctypes .WinDLL ("user32" ,use_last_error = True ) 42WM_CLOSE = 0x0010 43 44 45def main_window (pid :int )-> int | None : 46found = [] 47 48@ ctypes . WINFUNCTYPE ( wintypes . BOOL , wintypes . HWND , wintypes . LPARAM ) 49def visit (hwnd ,_ ): 50owner = wintypes .DWORD () 51user32 .GetWindowThreadProcessId (hwnd ,ctypes .byref (owner )) 52if owner .value == pid and user32 .IsWindowVisible (hwnd ): 53buf = ctypes .create_unicode_buffer (256 ) 54user32 .GetWindowTextW (hwnd ,buf ,256 ) 55if buf .value .strip ()== "Strata" : 56found .append (hwnd ) 57return True 58user32 .EnumWindows (visit ,0 ) 59return found [0 ]if found else None 60 61 62class Scratch : 63def __init__ (self ,root :Path ,install :Path ): 64self .root ,self .install = root ,install 65self .components = root / "components" 66self .models = root / "models" 67self .mark = root / "mark" 68for d in (self .components ,self .models ,self .mark ,root / "local" ,root / "home" ,root / "appdata" ,root / "webview" ): 69d .mkdir (parents = True ,exist_ok = True ) 70install_fake_engine (self .components ) 71from tools .strata_tokenizer import BYTE_TO_UNICODE 72tok = self .models / "tokenizer" 73tok .mkdir () 74tokens = [BYTE_TO_UNICODE [i ]for i in range (256 )]+ ["ab" ,"<|im_start|>" ,"<|im_end|>" ,"<|endoftext|>" ] 75 (tok / "vocab.json" ).write_text (json .dumps ({t :i for i ,t in enumerate (tokens )})) 76 (tok / "merges.txt" ).write_text ("a b" ) 77 (tok / "token_type.json" ).write_text (json .dumps ([0 ]* 257 + [3 ,3 ,3 ])) 78for name in ("stub" ,"stub2" ): 79 (self .models / f"strata- { name } .json" ).write_text (json .dumps ({ 80"exe" :"component:strata-engine" ,"backend" :"cuda" ,"tokenizer" :str (tok ),"args" : [],"cwd" :str (root ), 81"model_name" :name ,"host" :"127.0.0.1" ,"port" :0 })) 82self .env = {** os .environ ,"STRATA_COMPONENTS_DIR" :str (self .components ),"STRATA_PROFILE_DIR" :str (root / "profiles" ), 83"STRATA_RUNTIME_DIR" :str (root / "runtime" ),"STRATA_INSTALL_DIR" :str (self .models ), 84"STRATA_MODELS_DIR" :str (root / "models-unused" ),"STRATA_ENGINE_BACKEND" :"cuda" , 85"STRATA_HOME" :str (root / "home" ),"APPDATA" :str (root / "appdata" ),"LOCALAPPDATA" :str (root / "local" ), 86"WEBVIEW2_USER_DATA_FOLDER" :str (root / "webview" ),"FAKE_ENGINE_MARK" :str (self .mark ), 87"FAKE_ENGINE_SLOW_STEPS" :"0" ,"PYTHONDONTWRITEBYTECODE" :"1" } 88self .env .pop ("STRATA_API_KEY" ,None ) 89for key in ("STRATA_COMPONENTS_DIR" ,"STRATA_PROFILE_DIR" ,"STRATA_RUNTIME_DIR" ,"LOCALAPPDATA" ,"STRATA_ENGINE_BACKEND" , 90"STRATA_NO_ACQUIRE" ,"FAKE_ENGINE_MARK" ): 91os .environ [key ]= self .env .get (key ,"1" )# this process reads the same runtime and records folders 92 93 94class App : 95def __init__ (self ,scratch :Scratch ): 96self .s = scratch 97self .proc = subprocess .Popen ([str (scratch .install / "strata-desktop.exe" )],cwd = scratch .install ,env = scratch .env , 98stdout = subprocess .DEVNULL ,stderr = subprocess .DEVNULL ) 99self .base = None 100 101def host (self ): 102for child in psutil .Process (self .proc .pid ).children (recursive = True ): 103if child .name ().lower ()== "node.exe" : 104return child 105return None 106 107def wait_up (self ,seconds = 90 ): 108deadline = time .monotonic ()+ seconds 109while time .monotonic ()< deadline : 110if self .proc .poll ()is not None : 111raise RuntimeError (f"the app exited with { self . proc . returncode } " ) 112try : 113host = self .host () 114if host : 115for c in host .net_connections (kind = "tcp" ): 116if c .status == "LISTEN" and c .laddr .ip == "127.0.0.1" : 117base = f"http://127.0.0.1: { c . laddr . port } " 118try : 119if urllib .request .urlopen (base + "/api/health" ,timeout = 2 ).status == 200 and main_window (self .proc .pid ): 120self .base = base 121return 122except OSError : 123pass 124except psutil .Error : 125pass 126time .sleep (0.5 ) 127raise RuntimeError ("the app did not come up" ) 128 129def call (self ,path ,method = "GET" ,body = None ): 130req = urllib .request .Request (self .base + path ,method = method ,data = None if body is None else json .dumps (body ).encode (), 131headers = {"content-type" :"application/json" }) 132try : 133with urllib .request .urlopen (req ,timeout = 120 )as r : 134return json .loads (r .read ()or b"null" ) 135except urllib .error .HTTPError as exc : 136raise RuntimeError (f" { method } { path } -> { exc . code } { exc . read ()[: 300 ]!r } " )from None 137 138def load (self ,model ,multiple = False ): 139self .call ("/api/native?refresh=1" ) 140started = self .call ("/api/native/operations" ,"POST" , {"kind" :"load" ,"args" : {"model" :model ,** ({"multiple" :True }if multiple else {})}}) 141deadline = time .monotonic ()+ 180 142while time .monotonic ()< deadline : 143state = self .call ("/api/native" ) 144job = next ((j for j in state ["jobs" ]if j ["id" ]== started ["id" ]),None ) 145if job and job ["state" ]!= "running" : 146if job ["state" ]!= "done" : 147raise RuntimeError (f"load { model } : { job [ 'state' ] } { job . get ( 'error' ) } " ) 148return state 149time .sleep (0.3 ) 150raise RuntimeError ("load did not finish" ) 151 152 153def tree_of (app :App ,slots = ("app-1" ,))-> tuple [list [procs .Ident ],list [int ]]: 154idents ,ports = [], [] 155members = [psutil .Process (app .proc .pid ),* psutil .Process (app .proc .pid ).children (recursive = True )] 156pids = {p .pid for p in members } 157for slot in slots : 158state = runtime ._read_state (slot ) 159if state : 160pids .add (state ["host_pid" ]) 161for r in procs .records (): 162if r .get ("profile" )in slots :# the app's own slots; a Terminal service is not part of the app's tree 163pids .add (r ["pid" ]) 164for pid in pids : 165token = procs .start_token (pid ) 166if token : 167idents .append (procs .Ident (pid ,token ,tuple (procs .command_line (pid )or []))) 168return idents ,ports 169 170 171def survivors (idents ): 172return [f" { i . pid } { ' ' . join ( i . cmd )[: 80 ] } " for i in idents if procs .start_token (i .pid )== i .token ] 173 174 175def wait_gone (idents ,seconds ): 176deadline = time .monotonic ()+ seconds 177left = survivors (idents ) 178while left and time .monotonic ()< deadline : 179time .sleep (0.25 ) 180left = survivors (idents ) 181return left 182 183 184def lease_free ()-> bool : 185try : 186fd = runtime .acquire_activity_lease (shared = False ) 187except Exception :# noqa: BLE001 188return False 189runtime ._unlock_file (fd ) 190os .close (fd ) 191return True 192 193 194def control (scratch :Scratch ,* argv :str ,timeout :int = 300 )-> dict : 195py = scratch .install / "control" / "python" / "python.exe" 196out = subprocess .run ([str (py ),str (scratch .install / "control" / "strata.py" ),* argv ,"--output" ,"json" ], 197env = {** scratch .env ,"PYTHONNOUSERSITE" :"1" ,"STRATA_NO_ACQUIRE" :"1" }, 198capture_output = True ,text = True ,timeout = timeout ) 199try : 200return json .loads (out .stdout ) 201except ValueError : 202return {"ok" :False ,"raw" :out .stdout [- 300 :]+ out .stderr [- 300 :]} 203 204 205def stop_cli (scratch :Scratch ,slot :str )-> dict : 206py = scratch .install / "control" / "python" / "python.exe" 207out = subprocess .run ([str (py ),str (scratch .install / "control" / "strata.py" ),"runtime" ,"stop" ,"--profile" ,slot ,"--wait" ,"30" , 208"--output" ,"json" ],env = {** scratch .env ,"PYTHONNOUSERSITE" :"1" ,"STRATA_NO_ACQUIRE" :"1" }, 209capture_output = True ,text = True ,timeout = 120 ) 210try : 211return json .loads (out .stdout ) 212except ValueError : 213return {"state" :"?" ,"raw" :out .stdout [- 200 :]+ out .stderr [- 200 :]} 214 215 216def case (name :str ,install :Path ,how :str )-> dict : 217with tempfile .TemporaryDirectory (prefix = "strata-app-matrix-" ,ignore_cleanup_errors = True )as tmp : 218saved = dict (os .environ ) 219scratch = Scratch (Path (tmp ),install ) 220app = App (scratch ) 221problems ,note = [],"" 222try : 223app .wait_up () 224slots = ("app-1" ,"app-2" )if how == "two-engines" else ("app-1" ,) 225terminal = None 226if how == "window-x-terminal-engine" : 227# an engine the Terminal started (its own profile, no tie to the app) must survive the app's close 228control (scratch ,"profile" ,"create" ,"terminal-1" ,"--from-config" ,str (scratch .models / "strata-stub2.json" )) 229terminal = control (scratch ,"runtime" ,"start" ,"--profile" ,"terminal-1" ,"--wait" ,"60" ) 230if terminal .get ("state" )!= "ready" : 231raise RuntimeError (f"the Terminal's service did not start: { terminal } " ) 232terminal_pids = {r ["pid" ]for r in procs .records (profile = "terminal-1" )}| {runtime ._read_state ("terminal-1" )["host_pid" ]} 233state = app .load ("stub" ) 234if how == "two-engines" : 235state = app .load ("stub2" ,multiple = True ) 236engine_ports = [i ["port" ]for i in state ["instances" ]] 237idents ,_ = tree_of (app ,slots ) 238kinds = sorted ({("engine" if "engine" in " " .join (i .cmd )else "server" if "serve.server" in " " .join (i .cmd )else 239"owner" if "strata_control.runtime" in " " .join (i .cmd )else "app" if "strata-desktop" in i .cmd [0 ].lower () 240else "host" if "node" in i .cmd [0 ].lower ()else "other" )for i in idents }) 241note = f"tree { len ( idents ) } processes: { ', ' . join ( kinds ) } ; engine ports { engine_ports } " 242t0 = time .monotonic () 243if how == "normal-close" : 244subprocess .run (["taskkill" ,"/PID" ,str (app .proc .pid )],capture_output = True ) 245elif how in ("window-x" ,"two-engines" ,"window-x-terminal-engine" ): 246hwnd = main_window (app .proc .pid ) 247if not hwnd : 248raise RuntimeError ("no main window" ) 249user32 .PostMessageW (hwnd ,WM_CLOSE ,0 ,0 ) 250elif how == "kill-app" : 251subprocess .run (["taskkill" ,"/F" ,"/PID" ,str (app .proc .pid )],capture_output = True ) 252elif how == "host-crash" : 253host = app .host () 254subprocess .run (["taskkill" ,"/F" ,"/PID" ,str (host .pid )],capture_output = True ) 255elif how == "second-launch" : 256second = subprocess .Popen ([str (install / "strata-desktop.exe" )],cwd = install ,env = scratch .env , 257stdout = subprocess .DEVNULL ,stderr = subprocess .DEVNULL ) 258try : 259code = second .wait (timeout = 30 ) 260except subprocess .TimeoutExpired : 261second .kill () 262problems .append ("the second launch did not exit" ) 263code = None 264time .sleep (2 ) 265hosts = [p for p in psutil .process_iter (["name" ,"pid" ])if p .info ["name" ].lower ()== "node.exe" 266and (p .parent ()and p .parent ().pid == app .proc .pid )] 267apps = [p for p in psutil .process_iter (["name" ])if p .info ["name" ].lower ()== "strata-desktop.exe" ] 268if app .proc .poll ()is not None : 269problems .append ("the first app went away" ) 270if len (apps )!= 1 : 271problems .append (f" { len ( apps ) } app processes (want 1)" ) 272if len (hosts )!= 1 : 273problems .append (f" { len ( hosts ) } hosts under the first app (want 1)" ) 274after ,_ = tree_of (app ,slots ) 275new = [i for i in after if i .pid not in {x .pid for x in idents }] 276if new : 277problems .append (f"the second launch started: { [ ' ' . join ( i . cmd )[: 60 ] for i in new ] } " ) 278note += f"; second launch exit code { code } , app processes { len ( apps ) } , hosts { len ( hosts ) } " 279subprocess .run (["taskkill" ,"/PID" ,str (app .proc .pid )],capture_output = True ) 280if how == "host-crash" : 281# the shell and its window stay (nothing here restarts a dead host); the host, Control's owner, the server and 282# the engine must not 283idents = [i for i in idents if any (k in " " .join (i .cmd )for k in ("strata_control.runtime" ,"serve.server" ,"engine" ,"node.exe" ))] 284left = wait_gone (idents ,90 ) 285if left : 286problems .append (f"processes left: { left } " ) 287for port in engine_ports : 288deadline = time .monotonic ()+ 10 289while port_open (port )and time .monotonic ()< deadline : 290time .sleep (0.2 ) 291if port_open (port ): 292problems .append (f"engine port { port } still open" ) 293if terminal is None and not lease_free (): 294problems .append ("lease still held" ) 295marks = sorted (p .name for p in scratch .mark .iterdir ()) 296if terminal is not None : 297status = control (scratch ,"runtime" ,"status" ,"--profile" ,"terminal-1" ) 298alive_pids = [p for p in terminal_pids if procs .start_token (p )] 299if status .get ("state" )!= "ready" or len (alive_pids )!= len (terminal_pids ): 300problems .append (f"closing the app disturbed the Terminal's service: { status . get ( 'state' ) } , alive { alive_pids } of { sorted ( terminal_pids ) } " ) 301note += f"; the Terminal's service is { status . get ( 'state' ) } after the app closed" 302stopped = control (scratch ,"runtime" ,"stop" ,"--profile" ,"terminal-1" ,"--wait" ,"30" ) 303if stopped .get ("state" )!= "stopped" or [p for p in terminal_pids if procs .start_token (p )]: 304problems .append (f"the Terminal's service did not stop on request: { stopped } " ) 305time .sleep (1 ) 306if not lease_free (): 307problems .append ("lease still held after the Terminal's service stopped" ) 308if how in ("normal-close" ,"window-x" ,"two-engines" ,"second-launch" ,"window-x-terminal-engine" )and not ({"quit" ,"eof" }& set (marks )): 309problems .append (f"the engine was not stopped the clean way (marks { marks } )" ) 310seconds = round (time .monotonic ()- t0 ,1 ) 311if how == "host-crash" : 312subprocess .run (["taskkill" ,"/PID" ,str (app .proc .pid )],capture_output = True ) 313note += "; the app shell stays open after a host crash (by design today)" 314# the slot must be usable again: stopping a lost owner's slot cleans its state; nothing blocks the next load 315for slot in slots : 316res = stop_cli (scratch ,slot ) 317already = "not managed or is stopped" in json .dumps (res )# nothing was left to stop: the clean outcome 318if res .get ("state" )not in ("stopped" ,)and not already : 319problems .append (f"runtime stop { slot } after the close: { res } " ) 320if runtime ._read_state (slot )is not None : 321problems .append (f"state of { slot } left behind" ) 322return {"name" :f"app- { how } " ,"ok" :not problems ,"problems" :problems ,"seconds" :seconds ,"marks" :marks ,"note" :note } 323except Exception as exc :# noqa: BLE001 324return {"name" :f"app- { how } " ,"ok" :False ,"problems" : [f" { type ( exc ). __name__ } : { exc } " ]+ problems ,"note" :note } 325finally : 326for p in psutil .process_iter (["name" ,"exe" ]): 327try : 328if (p .info ["exe" ]or "" ).lower ().startswith (str (install ).lower ()): 329p .kill () 330except psutil .Error : 331pass 332for r in procs .records (): 333try : 334psutil .Process (r ["pid" ]).kill () 335except psutil .Error : 336pass 337os .environ .clear ();os .environ .update (saved ) 338 339 340SCENARIOS = ["normal-close" ,"window-x" ,"window-x-terminal-engine" ,"kill-app" ,"host-crash" ,"second-launch" ,"two-engines" ] 341 342 343def main ()-> int : 344ap = argparse .ArgumentParser () 345ap .add_argument ("--install" ,required = True ) 346ap .add_argument ("--scenarios" ,default = "all" ) 347ap .add_argument ("--report" ) 348a = ap .parse_args () 349names = SCENARIOS if a .scenarios == "all" else a .scenarios .split ("," ) 350results = [] 351for how in names : 352r = case (how ,Path (a .install ),how ) 353results .append (r ) 354"PASS " if r ["ok" ]else "FAIL " )+ r ["name" ],r .get ("seconds" ,"" ),r .get ("problems" )or "" ,r .get ("note" ,"" ),flush = True ) 355if a .report : 356Path (a .report ).write_text (json .dumps ({"platform" :"windows" ,"engine" :"fake" ,"results" :results },indent = 1 ),encoding = "utf-8" ) 357return 0 if all (r ["ok" ]for r in results )else 1 358 359 360if __name__ == "__main__" : 361raise SystemExit (main ())