okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0c53372a0
main
1#!/usr/bin/env python3 2"""Smoke-test a terminal archive in a clean environment. 3 4python packaging/smoke_terminal.py release/artifacts/strata-terminal-0.1.45-windows-x86_64.zip [--json out.json] 5 6The archive is extracted into a fresh folder whose name has a space in it (so a moved or awkward path is part of 7the test), and every command runs with a PATH that holds no Python (Windows: System32 only; POSIX: a folder with 8dirname/readlink/cat and nothing else), no PYTHON* variables, a private user profile, and a dead HTTP proxy so that 9anything reaching for the internet fails loudly. It then checks, through the bundled launcher: 10 11strata --version must name the interpreter inside the extracted folder 12strata doctor read-only inventory 13strata profile list saved profiles (none in a clean profile) 14strata serve --engine mock the server on the scripted engine: /health, /v1/models and a chat answer 15strata install must refuse (no installer in the archive) with exit 5, not fetch anything 16 17The script is one foreground run: the mock server it starts is a child that is stopped (whole tree) before it exits. 18""" 19 20from __future__import annotations 21 22import argparse 23import json 24import os 25import shutil 26import socket 27import subprocess 28import sys 29import tarfile 30import tempfile 31import time 32import urllib .request 33import zipfile 34from pathlib import Path 35 36 37def free_port ()-> int : 38with socket .socket ()as s : 39s .bind (("127.0.0.1" ,0 )) 40return s .getsockname ()[1 ] 41 42 43def extract (archive :Path ,dest :Path )-> Path : 44if archive .suffix == ".zip" : 45with zipfile .ZipFile (archive )as zf : 46zf .extractall (dest ) 47else : 48with tarfile .open (archive )as tf : 49tf .extractall (dest ) 50roots = [p for p in dest .iterdir ()if p .is_dir ()] 51if len (roots )!= 1 : 52raise SystemExit (f"expected one folder in the archive, found { [ p . name for p in roots ] } " ) 53return roots [0 ] 54 55 56def clean_env (sandbox :Path )-> tuple [dict ,list [str ]]: 57home = sandbox / "home" 58home .mkdir (parents = True ,exist_ok = True ) 59if os .name == "nt" : 60system32 = str (Path (os .environ .get ("SystemRoot" ,r"C:\Windows" ))/ "System32" ) 61env = {"PATH" :system32 ,"SystemRoot" :os .environ .get ("SystemRoot" ,r"C:\Windows" ), 62"SystemDrive" :os .environ .get ("SystemDrive" ,"C:" ),"COMSPEC" :os .environ .get ("COMSPEC" ,"" ), 63"TEMP" :str (sandbox / "tmp" ),"TMP" :str (sandbox / "tmp" ),"USERPROFILE" :str (home ), 64"APPDATA" :str (home / "AppData" / "Roaming" ),"LOCALAPPDATA" :str (home / "AppData" / "Local" ), 65"HOMEDRIVE" :"C:" ,"HOMEPATH" :str (home )[2 :],"PATHEXT" :".COM;.EXE;.BAT;.CMD" } 66shell = ["cmd" ,"/c" ] 67else : 68minimal = sandbox / "minbin" 69minimal .mkdir (parents = True ,exist_ok = True ) 70for tool in ("dirname" ,"readlink" ,"cat" ,"uname" ,"basename" ): 71found = shutil .which (tool ) 72if found and not (minimal / tool ).exists (): 73 (minimal / tool ).symlink_to (found ) 74env = {"PATH" :str (minimal ),"HOME" :str (home ),"TMPDIR" :str (sandbox / "tmp" ), 75"XDG_CONFIG_HOME" :str (home / ".config" ),"LANG" :"C.UTF-8" } 76shell = [] 77 (sandbox / "tmp" ).mkdir (parents = True ,exist_ok = True ) 78# anything that reaches for the internet fails loudly; the loopback server is unaffected 79env .update ({"HTTP_PROXY" :"http://127.0.0.1:9" ,"HTTPS_PROXY" :"http://127.0.0.1:9" , 80"NO_PROXY" :"127.0.0.1,localhost" ,"PIP_NO_INDEX" :"1" }) 81return env ,shell 82 83 84def launcher (root :Path )-> list [str ]: 85return [str (root / "bin" / "strata.cmd" )]if os .name == "nt" else [str (root / "bin" / "strata" )] 86 87 88def as_command (args :list [str ]): 89"""What to hand to subprocess. A .cmd launcher in a folder with a space needs cmd's /s rule (strip only the outer 90pair of quotes), the way a user's shell does it.""" 91if os .name != "nt" : 92return args 93return 'cmd.exe /d /s /c "' + subprocess .list2cmdline (args )+ '"' 94 95 96def run (cmd :list [str ],env :dict ,cwd :Path ,timeout :int = 120 )-> dict : 97t = time .time () 98r = subprocess .run (as_command (cmd ),env = env ,cwd = str (cwd ),capture_output = True ,text = True ,timeout = timeout ) 99return {"cmd" :" " .join (cmd ),"rc" :r .returncode ,"seconds" :round (time .time ()- t ,2 ), 100"stdout" :r .stdout ,"stderr" :r .stderr } 101 102 103def inside_archive (root :Path ,text :str )-> bool : 104"""The interpreter the launcher reported is the one in the extracted folder (8.3 and long forms of a path both).""" 105tail = (root .name + os .sep + ("python" + os .sep + "python.exe" if os .name == "nt" else "python/bin/python3" )).lower () 106return tail in text .lower ().replace ("/" ,os .sep ) 107 108 109def kill_tree (proc :subprocess .Popen )-> None : 110if proc .poll ()is not None : 111return 112if os .name == "nt" : 113subprocess .run (["taskkill" ,"/T" ,"/F" ,"/PID" ,str (proc .pid )],capture_output = True ) 114else : 115proc .terminate () 116try : 117proc .wait (timeout = 20 ) 118except subprocess .TimeoutExpired : 119proc .kill () 120 121 122def http (url :str ,body :dict | None = None ,timeout :float = 20 )-> tuple [int ,str ]: 123# the dead proxy is for the child processes; this client talks to loopback directly 124opener = urllib .request .build_opener (urllib .request .ProxyHandler ({})) 125req = urllib .request .Request (url ,data = json .dumps (body ).encode ()if body is not None else None , 126headers = {"Content-Type" :"application/json" }) 127with opener .open (req ,timeout = timeout )as resp : 128return resp .status ,resp .read ().decode ("utf-8" ,"replace" ) 129 130 131def main ()-> int : 132ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 133ap .add_argument ("archive" ) 134ap .add_argument ("--json" ,help = "write the full results here" ) 135ap .add_argument ("--keep" ,action = "store_true" ,help = "keep the extracted folder" ) 136a = ap .parse_args () 137archive = Path (a .archive ).resolve () 138sandbox = Path (tempfile .mkdtemp (prefix = "strata smoke " )) 139results :dict = {"archive" :archive .name ,"sandbox_has_space" :" " in str (sandbox ),"checks" : {}} 140ok = True 141proc = None 142try : 143root = extract (archive ,sandbox / "extract" ) 144env ,_ = clean_env (sandbox ) 145results ["root" ]= str (root ) 146strata = launcher (root ) 147 148# no other Python can be found from this environment 149if os .name == "nt" : 150found = {"rc" :1 ,"stdout" :"" ,"stderr" :"" } 151for name in ("python" ,"py" ,"python3" ): 152w = subprocess .run (["where" ,name ],env = env ,capture_output = True ,text = True ) 153if w .returncode == 0 and w .stdout .strip (): 154found = {"rc" :0 ,"stdout" :w .stdout ,"stderr" :"" } 155else : 156found = {"rc" :1 ,"stdout" :"" ,"stderr" :"" } 157for name in ("python" ,"python3" ,"py" ): 158if shutil .which (name ,path = env ["PATH" ]): 159found = {"rc" :0 ,"stdout" :name ,"stderr" :"" } 160results ["other_python_on_path" ]= found ["rc" ]== 0 and bool (found ["stdout" ].strip ()) 161ok &= not results ["other_python_on_path" ] 162 163def check (name :str ,cond :bool ,** info )-> None : 164nonlocal ok 165results ["checks" ][name ]= {"ok" :bool (cond ),** info } 166ok &= bool (cond ) 167"PASS " if cond else "FAIL " )+ name ) 168 169r = run ([* strata ,"--version" ],env ,root ) 170inside = inside_archive (root ,r ["stdout" ]) 171check ("version" ,r ["rc" ]== 0 and r ["stdout" ].startswith ("strata " )and inside , 172rc = r ["rc" ],output = r ["stdout" ].strip (),interpreter_inside_archive = inside ) 173 174if os .name == "nt" : 175ps = Path (env ["SystemRoot" ])/ "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe" 176r = run ([str (ps ),"-NoProfile" ,"-ExecutionPolicy" ,"Bypass" ,"-File" ,str (root / "bin" / "strata.ps1" ), 177"--version" ],env ,root ) 178check ("version (strata.ps1)" ,r ["rc" ]== 0 and inside_archive (root ,r ["stdout" ]), 179rc = r ["rc" ],output = r ["stdout" ].strip (),stderr = r ["stderr" ].strip ()[:200 ]) 180 181r = run ([* strata ,"doctor" ],env ,root ) 182check ("doctor" ,r ["rc" ]== 0 ,rc = r ["rc" ],output = r ["stdout" ].strip ()[:600 ]) 183 184r = run ([* strata ,"profile" ,"list" ],env ,root ) 185check ("profile list" ,r ["rc" ]== 0 ,rc = r ["rc" ],output = r ["stdout" ].strip ()[:300 ]) 186 187r = run ([* strata ,"install" ],env ,root ) 188# since 0.2.4 the Terminal carries setup.py: with no keyboard it stops at the first question, in plain words and with a non-zero code 189# (an older Terminal without the installer answers rc 5 "no installer") 190stopped = r ["rc" ]not in (0 ,None )and ("no installer" in r ["stderr" ]or "setup stopped" in (r ["stdout" ]+ r ["stderr" ]).lower ()) 191check ("install stops without a keyboard (or without an installer)" ,stopped ,rc = r ["rc" ],stderr = r ["stderr" ].strip ()[:300 ], 192output = r ["stdout" ].strip ()[- 300 :]) 193 194# serve on the mock engine: a fake run config (the mock never loads it), a free port, a chat answer 195cfg_dir = sandbox / "cfg" 196cfg_dir .mkdir () 197 (cfg_dir / "engine.exe" ).write_bytes (b"not an engine" ) 198 (cfg_dir / "tokenizer.json" ).write_text ("{}" ,encoding = "utf-8" ) 199cfg = cfg_dir / "strata-mock.json" 200cfg .write_text (json .dumps ({"exe" :str (cfg_dir / "engine.exe" ),"tokenizer" :str (cfg_dir / "tokenizer.json" ), 201"args" : [],"model_name" :"mock" }),encoding = "utf-8" ) 202port = free_port () 203log = sandbox / "serve.log" 204with log .open ("wb" )as lf : 205proc = subprocess .Popen (as_command ([* strata ,"serve" ,"--profile" ,str (cfg ),"--engine" ,"mock" , 206"--port" ,str (port ),"--host" ,"127.0.0.1" ]), 207env = env ,cwd = str (root ),stdout = lf ,stderr = subprocess .STDOUT , 208stdin = subprocess .DEVNULL ) 209health = None 210deadline = time .time ()+ 60 211while time .time ()< deadline and proc .poll ()is None : 212try : 213status ,body = http (f"http://127.0.0.1: { port } /health" ,timeout = 3 ) 214if status == 200 : 215health = body 216break 217except OSError : 218time .sleep (0.5 ) 219check ("serve: /health" ,health is not None ,port = port ,body = (health or "" )[:200 ], 220exited = proc .poll (),log = log .read_text (errors = "replace" )[- 600 :]if health is None else "" ) 221if health is not None : 222status ,models = http (f"http://127.0.0.1: { port } /v1/models" ) 223check ("serve: /v1/models" ,status == 200 ,body = models [:200 ]) 224status ,chat = http (f"http://127.0.0.1: { port } /v1/chat/completions" , 225 {"model" :"mock" ,"messages" : [{"role" :"user" ,"content" :"hello" }], 226"max_tokens" :16 }) 227text = "" 228try : 229msg = json .loads (chat )["choices" ][0 ]["message" ] 230text = (msg .get ("content" )or "" )+ (msg .get ("reasoning_content" )or "" ) 231except (ValueError ,KeyError ,IndexError ,TypeError ): 232pass 233check ("serve: chat answer" ,status == 200 and bool (text .strip ()),answer = text [:200 ],body = chat [:400 ]) 234finally : 235if proc is not None : 236kill_tree (proc ) 237if not a .keep : 238shutil .rmtree (sandbox ,ignore_errors = True ) 239results ["ok" ]= ok 240if a .json : 241Path (a .json ).write_text (json .dumps (results ,indent = 2 ),encoding = "utf-8" ) 242"SMOKE " + ("OK" if ok else "FAILED" )) 243return 0 if ok else 1 244 245 246if __name__ == "__main__" : 247sys .exit (main ())