okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3fa1b524d
main
1#!/usr/bin/env python3 2"""Exercise one portable Monitor bundle with a local fake server. 3 4Run this on each target OS/Python before release. It checks the client and the 5local bundle lifecycle. --interactive also checks packaged Textual rendering. 6Neither mode exercises the engine or GPU drivers. 7""" 8 9from __future__import annotations 10 11import argparse 12import hashlib 13import json 14import platform 15import subprocess 16import sys 17import tempfile 18import threading 19import time 20from http .server import BaseHTTPRequestHandler ,ThreadingHTTPServer 21from pathlib import Path 22 23 24BUILDER = Path (__file__ ).resolve ().parents [1 ]/ "packaging" / "monitor_bundle.py" 25INTERACTIVE_CODE = r''' 26import asyncio 27import io 28import json 29import sys 30 31sys.path.insert(0, sys.argv[1]) 32from rich.console import Console 33from textual.widgets import Static 34from strata_cli.client import Endpoint 35from strata_cli.monitor import MonitorApp 36from strata_cli.dashboard import render_dashboard 37from strata_cli.detail_dashboard import render_detail_dashboard 38import strata_cli.monitor as monitor_module 39 40async def main(): 41source = str(monitor_module.__file__).replace("\\", "/") 42bundle_path = sys.argv[1].replace("\\", "/") 43if not source.startswith(bundle_path + "/"): 44raise RuntimeError("interactive Monitor was not imported from the bundle") 45app = MonitorApp(Endpoint(sys.argv[2]), None, interval=0.5, 46theme="dark", color="never", glyphs="ascii") 47async with app.run_test(size=(110, 30)) as pilot: 48for _ in range(30): 49if app.connection_state == "connected": 50break 51await pilot.pause(0.1) 52if app.connection_state != "connected": 53raise RuntimeError("interactive Monitor did not connect") 54output = io.StringIO() 55Console(file=output, width=110, color_system=None).print( 56app.query_one("#content", Static).content) 57shown = output.getvalue() 58if not all(title in shown for title in 59("SERVING", "PERFORMANCE", "BATCHING / PARALLEL", 60"HARDWARE", "REQUESTS", "ACTIVITY")): 61raise RuntimeError("packaged one-screen Overview is incomplete") 62if (app.latest.get("model") or {}).get("id") != "portable-smoke-model": 63raise RuntimeError("interactive Monitor showed the wrong model") 64wide = io.StringIO() 65Console(file=wide, width=140, color_system=None).print(render_dashboard( 66app.latest, width=138, height=42, history=app.history, 67glyphs="ascii", color=False)) 68if not all(title in wide.getvalue() for title in 69("THROUGHPUT", "GPUS", "CONTEXT / BATCHING", "PARALLEL SLOTS", "REQUESTS")): 70raise RuntimeError("packaged wide visual Overview is incomplete") 71for view, title in (("serving", "REQUEST FLOW"), ("requests", "IN FLIGHT"), 72("engine", "STAGES / HOST SPAN"), ("hardware", "GPU CARDS"), 73("logs", "RECENT EVENT TIMELINE")): 74detail = io.StringIO() 75Console(file=detail, width=140, color_system=None).print(render_detail_dashboard( 76app.latest, view, width=138, height=42, history=app.history, 77glyphs="ascii", color=False)) 78if title not in detail.getvalue(): 79raise RuntimeError("packaged visual " + view + " page is incomplete") 80await pilot.press("q") 81print(json.dumps({"connected": True, "overview_panels": 6, 82"wide_visual": True, "visual_details": 5, 83"imported_from_bundle": True, "detached": True})) 84 85asyncio.run(main()) 86''' 87 88 89def _run (* argv :str )-> dict : 90result = subprocess .run ([sys .executable ,"-I" ,"-S" ,* argv ], 91capture_output = True ,text = True ,timeout = 20 ,check = False ) 92if result .returncode or result .stderr .strip (): 93raise RuntimeError (f"isolated command failed ( { result . returncode } ): { result . stderr . strip () } " ) 94try : 95return json .loads (result .stdout ) 96except json .JSONDecodeError as exc : 97raise RuntimeError ("isolated command did not return one JSON record" )from exc 98 99 100def _server ()-> tuple [ThreadingHTTPServer ,list [str ],threading .Event ]: 101paths :list [str ]= [] 102malformed = threading .Event () 103 104class TelemetryHandler (BaseHTTPRequestHandler ): 105def do_GET (self )-> None : 106paths .append ("GET " + self .path ) 107if self .path != "/v1/telemetry" : 108self .send_error (404 ) 109return 110body = json .dumps ({ 111"schema_version" :1 ,"sampled_at" :time .time (), 112"instance" : {"id" :"portable-smoke" ,"state" :"ready" }, 113"model" : {"id" :"portable-smoke-model" ,"loaded" :True }, 114"work" : {"active" :0 ,"queued" :0 ,"waiting" :0 , 115"slots_requested" :1 ,"slots_effective" :1 ,"groups" :1 , 116"slots" : [{"slot" :0 ,"state" :"idle" ,"group" :0 }]}, 117"topology" : {"mode" :"single" ,"selected_devices" : []}, 118"rates" : {"output_tokens_server_counter" :0 }, 119"devices" : [],"quality" : {"telemetry" :"available" }, 120 }).encode ()if not malformed .is_set ()else b"[" * 100000 + b"0" + b"]" * 100000 121self .send_response (200 ) 122self .send_header ("Content-Type" ,"application/json" ) 123self .send_header ("Content-Length" ,str (len (body ))) 124self .end_headers () 125self .wfile .write (body ) 126 127def _reject (self )-> None : 128paths .append (self .command + " " + self .path ) 129self .send_error (405 ) 130 131do_POST = do_PUT = do_PATCH = do_DELETE = do_HEAD = do_OPTIONS = do_TRACE = _reject 132 133def log_message (self ,* args :object )-> None : 134pass 135 136return ThreadingHTTPServer (("127.0.0.1" ,0 ),TelemetryHandler ),paths ,malformed 137 138 139def _malformed_response (bundle :Path ,url :str )-> None : 140result = subprocess .run ([sys .executable ,"-I" ,"-S" ,str (bundle ), 141"status" ,"--url" ,url ,"--json" ], 142capture_output = True ,text = True ,timeout = 20 ,check = False ) 143if result .returncode != 3 or result .stderr : 144raise RuntimeError ("deeply nested telemetry escaped the client error boundary" ) 145try : 146response = json .loads (result .stdout ) 147except json .JSONDecodeError as exc : 148raise RuntimeError ("malformed telemetry did not return one JSON error" )from exc 149if (response .get ("ok" )is not False or 150 (response .get ("error" )or {}).get ("message" )!= "server returned malformed JSON telemetry" ): 151raise RuntimeError ("deeply nested telemetry returned an unexpected error" ) 152 153 154def _interactive (bundle :Path ,url :str )-> dict : 155result = subprocess .run ([sys .executable ,"-I" ,"-c" ,INTERACTIVE_CODE ,str (bundle ),url ], 156capture_output = True ,text = True ,timeout = 20 ,check = False ) 157if result .returncode : 158raise RuntimeError (f"packaged interactive Monitor failed ( { result . returncode } ): " 159f" { result . stderr . strip ()[ - 2000 :] } " ) 160try : 161report = json .loads (result .stdout ) 162except json .JSONDecodeError as exc : 163raise RuntimeError ("interactive Monitor did not return one JSON record" )from exc 164if report != {"connected" :True ,"overview_panels" :6 ,"wide_visual" :True , 165"visual_details" :5 , 166"imported_from_bundle" :True ,"detached" :True }: 167raise RuntimeError ("packaged interactive Monitor smoke was incomplete" ) 168return report 169 170 171def smoke (bundle :Path ,* ,interactive :bool = False )-> dict : 172bundle = bundle .resolve (strict = True ) 173manifest = _run (str (BUILDER ),"verify" ,str (bundle )) 174expected_sha = hashlib .sha256 (bundle .read_bytes ()).hexdigest () 175if manifest .get ("sha256" )!= expected_sha : 176raise RuntimeError ("bundle digest changed after verification" ) 177 178server ,paths ,malformed = _server () 179worker = threading .Thread (target = server .serve_forever ,daemon = True ) 180worker .start () 181try : 182url = f"http://127.0.0.1: { server . server_port } " 183one_shot = _run (str (bundle ),"monitor" ,"--url" ,url ,"--once" ,"--json" ) 184if (one_shot .get ("ok" )is not True or 185 (one_shot .get ("snapshot" )or {}).get ("model" , {}).get ("id" )!= "portable-smoke-model" ): 186raise RuntimeError ("one-shot monitor returned the wrong model or failed" ) 187 188with tempfile .TemporaryDirectory (prefix = "strata-portable-smoke-" )as scratch : 189target = Path (scratch )/ "monitor" 190preview = _run (str (BUILDER ),"install" ,str (bundle ),"--target" ,str (target ),"--plan" ) 191if preview .get ("sha256" )!= expected_sha or preview .get ("would_install" )is not True : 192raise RuntimeError ("bundle install preview did not bind the candidate digest" ) 193installed = _run (str (BUILDER ),"install" ,str (bundle ),"--target" ,str (target ), 194"--if-candidate-sha256" ,expected_sha ) 195if installed .get ("installed" )is not True : 196raise RuntimeError ("bundle install did not complete" ) 197installed_bundle = target / bundle .name 198_run (str (BUILDER ),"verify" ,str (installed_bundle )) 199status = _run (str (installed_bundle ),"status" ,"--url" ,url ,"--json" ) 200if (status .get ("ok" )is not True or 201 (status .get ("snapshot" )or {}).get ("instance" , {}).get ("id" )!= "portable-smoke" ): 202raise RuntimeError ("installed client did not reach the fake server" ) 203removal = _run (str (BUILDER ),"uninstall" ,"--target" ,str (target ),"--plan" ) 204if removal .get ("sha256" )!= expected_sha or removal .get ("would_remove" )is not True : 205raise RuntimeError ("bundle removal preview did not bind the installed digest" ) 206removed = _run (str (BUILDER ),"uninstall" ,"--target" ,str (target ), 207"--if-active-sha256" ,expected_sha ) 208if removed .get ("removed" )is not True or target .exists (): 209raise RuntimeError ("bundle uninstall left an installed directory" ) 210malformed .set () 211_malformed_response (bundle ,url ) 212malformed .clear () 213interactive_report = _interactive (bundle ,url )if interactive else None 214finally : 215server .shutdown () 216server .server_close () 217worker .join (timeout = 5 ) 218 219if (paths [:2 ]!= ["GET /v1/telemetry" ,"GET /v1/telemetry" ]or 220any (path not in ("GET /v1/telemetry" ,"GET /metrics" )for path in paths )or # the interactive Overview also reads /metrics (404 here: it keeps the earlier Overview) 221 (interactive and len (paths )< 4 )or (not interactive and len (paths )!= 3 )): 222raise RuntimeError (f"unexpected client HTTP operations: { paths } " ) 223report = {"schema_version" :1 ,"scope" :"portable_monitor_stdlib_smoke" , 224"bundle_sha256" :expected_sha ,"python" :platform .python_version (), 225"platform" :platform .platform (),"isolated_no_site_packages" :True , 226"one_shot_monitor" :True ,"installed_status" :True , 227"digest_pinned_install_uninstall" :True , 228"deep_json_error" :True , 229"http_gets" :len (paths ), 230"other_http_methods" :0 ,"passed" :True } 231if interactive_report is not None : 232report ["interactive" ]= interactive_report 233return report 234 235 236def main ()-> int : 237ap = argparse .ArgumentParser (description = __doc__ ) 238ap .add_argument ("--bundle" ,type = Path ,required = True ) 239ap .add_argument ("--report" ,type = Path ,required = True , 240help = "new absolute JSON report file" ) 241ap .add_argument ("--interactive" ,action = "store_true" , 242help = "also load the packaged Textual Overview in a headless terminal" ) 243args = ap .parse_args () 244if not args .report .is_absolute ()or args .report .exists (): 245ap .error ("--report must be a new absolute file path" ) 246report = smoke (args .bundle ,interactive = args .interactive ) 247with args .report .open ("x" ,encoding = "utf-8" )as stream : 248json .dump (report ,stream ,indent = 2 ,sort_keys = True ) 249stream .write ("\n" ) 250json .dumps ({"report" :str (args .report ),"passed" :True })) 251return 0 252 253 254if __name__ == "__main__" : 255raise SystemExit (main ())