okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
64a91dcdc
main
1#!/usr/bin/env python3 2"""Headless Monitor soak against a bounded synthetic telemetry server. 3 4This is a client stability check, not model, GPU or serving performance evidence. 5Run for 1800 seconds to exercise reconnects, instance changes and bounded state. 6""" 7 8from __future__import annotations 9 10import argparse 11import asyncio 12import json 13import os 14import threading 15import time 16import tracemalloc 17from http .server import BaseHTTPRequestHandler ,ThreadingHTTPServer 18from pathlib import Path 19 20from strata_cli .client import Endpoint 21 22 23class SyntheticTelemetry : 24def __init__ (self ,* ,exercise_ui :bool = False ): 25self .lock = threading .Lock () 26self .instance = 0 27self .unavailable = False 28self .gets = 0 29self .failures = 0 30self .other_methods = 0 31self .bytes_sent = 0 32self .in_flight = 0 33self .max_in_flight = 0 34self .seq = 0 35self .exercise_ui = exercise_ui 36 37def snapshot (self )-> dict : 38with self .lock : 39self .seq += 1 40seq ,instance = self .seq ,self .instance 41now = time .time () 42events = [{"seq" :number ,"at" :now ,"request_id" :f" { number :012x } " ,"event" :"queued" } 43for number in range (max (1 ,seq - 63 ),seq + 1 )] 44devices = [{"index" :i ,"name" :f"Synthetic card { i } " }for i in range (4 )] 45topology = {} 46if self .exercise_ui : 47# Rotate an unrelated host card and intermittently lose or duplicate 48# a selected sensor. The Overview must retain only the four selected 49# card histories and mark current gaps unavailable. 50devices = [{"index" :100 + seq ,"name" :"Unselected host card" ,"util" :10 }] 51devices += [{"index" :i ,"name" :f"Selected card { i } " , 52"util" : (40 + i * 11 + seq )% 100 , 53"mem_used" : (12 + i )* 2 ** 30 ,"mem_total" :24 * 2 ** 30 } 54for i in range (4 )if not (i == 3 and seq % 5 == 0 )] 55if seq % 7 == 0 : 56devices .append ({"index" :1 ,"name" :"Ambiguous card 1" ,"util" :99 }) 57topology = {"mode" :"layer split" ,"selected_devices" : [0 ,1 ,2 ,3 ], 58"resolved" :False ,"stages" : []} 59return {"schema_version" :1 ,"source" :"synthetic-soak" ,"sampled_at" :now , 60"instance" : {"id" :f"synthetic- { instance } " ,"state" :"ready" ,"boot_time" :now - 60 }, 61"model" : {"id" :"synthetic-model" ,"loaded" :True ,"context" :4096 }, 62"rates" : {"output_tokens_server_counter" :seq * 12 }, 63"work" : {"active" :0 ,"queued" :seq % 5 ,"waiting" :0 ,"slots_requested" :8 , 64"slots_effective" :8 ,"groups" :4 , 65"batch_sample_windows" :4 ,"batch_sample_rows" :4 * (3 + seq % 4 ), 66"batch_sample_active_rows" :4 * min (3 ,2 + seq % 3 ), 67"batch_sample_span_s" :1.0 ,"batch_sample_age_s" :0.1 , 68"requests" : [{"id" :f"r { i :02d } " ,"state" :"queued" }for i in range (70 )]}, 69"topology" :topology ,"devices" :devices , 70"activity" : {"last_seq" :seq ,"events" :events }} 71 72def counters (self )-> dict : 73with self .lock : 74return {"gets" :self .gets ,"http_failures" :self .failures , 75"other_methods" :self .other_methods ,"bytes_sent" :self .bytes_sent , 76"max_in_flight" :self .max_in_flight ,"instance" :self .instance } 77 78 79def handler_for (service :SyntheticTelemetry ): 80class Handler (BaseHTTPRequestHandler ): 81def log_message (self ,* _args ): 82pass 83 84def do_GET (self ): 85with service .lock : 86service .in_flight += 1 87service .max_in_flight = max (service .max_in_flight ,service .in_flight ) 88service .gets += 1 89unavailable = service .unavailable 90try : 91if self .path != "/v1/telemetry" : 92self .send_error (404 ) 93return 94if unavailable : 95with service .lock : 96service .failures += 1 97self .send_error (503 ) 98return 99body = json .dumps (service .snapshot (),separators = ("," ,":" )).encode () 100self .send_response (200 ) 101self .send_header ("Content-Type" ,"application/json" ) 102self .send_header ("Content-Length" ,str (len (body ))) 103self .end_headers () 104self .wfile .write (body ) 105with service .lock : 106service .bytes_sent += len (body ) 107finally : 108with service .lock : 109service .in_flight -= 1 110 111def do_POST (self ): 112with service .lock : 113service .other_methods += 1 114self .send_error (405 ) 115 116return Handler 117 118 119async def soak (seconds :float ,interval :float ,* ,exercise_ui :bool = False )-> dict : 120try : 121from strata_cli .monitor import MonitorApp 122except ImportError as exc : 123raise RuntimeError ("the optional Textual monitor dependency is required" )from exc 124service = SyntheticTelemetry (exercise_ui = exercise_ui ) 125server = ThreadingHTTPServer (("127.0.0.1" ,0 ),handler_for (service )) 126thread = threading .Thread (target = server .serve_forever ,daemon = True ) 127thread .start () 128endpoint = Endpoint (f"http://127.0.0.1: { server . server_port } " ,timeout = 1 ) 129tracemalloc .start () 130started = time .monotonic () 131cpu_started = time .process_time () 132events :list [str ]= [] 133baseline = None 134max_output_rate_samples = 0 135max_batch_samples = 0 136max_pre_admit_samples = 0 137max_device_histories = 0 138max_device_samples = 0 139sensor_gap_observed = False 140max_vram_histories = 0 141max_vram_samples = 0 142vram_sensor_gap_observed = False 143resize_count = 0 144sizes_seen :set [tuple [int ,int ]]= set () 145resize_size_cycle = ((140 ,44 ), (110 ,30 ), (80 ,24 ), (60 ,16 ), (40 ,12 )) 146resize_step = max (1.0 ,min (5.0 ,seconds / 20 )) 147next_resize = 1.0 148next_progress = 60.0 149outage_length = min (5.0 ,max (1.0 ,seconds / 20 )) 150try : 151app = MonitorApp (endpoint ,None ,interval = interval ) 152observed_states = {app .connection_state } 153async with app .run_test (size = (80 ,24 ))as pilot : 154await pilot .press ("2" ) 155while True : 156elapsed = time .monotonic ()- started 157if elapsed >= seconds : 158break 159if baseline is None and elapsed >= min (5.0 ,seconds / 5 ): 160baseline = tracemalloc .get_traced_memory ()[0 ] 161if elapsed >= seconds * 0.25 and "disconnect" not in events : 162with service .lock : 163service .unavailable = True 164events .append ("disconnect" ) 165if elapsed >= seconds * 0.25 + outage_length and "reconnect" not in events : 166with service .lock : 167service .unavailable = False 168events .append ("reconnect" ) 169if elapsed >= seconds * 0.5 and "restart" not in events : 170with service .lock : 171service .instance += 1 172service .seq = 0 173events .append ("restart" ) 174if elapsed >= seconds * 0.75 and "second_disconnect" not in events : 175with service .lock : 176service .unavailable = True 177events .append ("second_disconnect" ) 178if elapsed >= seconds * 0.75 + outage_length and "second_reconnect" not in events : 179with service .lock : 180service .unavailable = False 181events .append ("second_reconnect" ) 182if elapsed >= next_progress : 183json .dumps ({"elapsed_s" :round (elapsed ,1 ),** service .counters ()}),flush = True ) 184next_progress += 60.0 185if exercise_ui and elapsed >= next_resize : 186size = resize_size_cycle [resize_count % len (resize_size_cycle )] 187await pilot .resize_terminal (* size ) 188sizes_seen .add (size ) 189resize_count += 1 190next_resize += resize_step 191observed_states .add (app .connection_state ) 192max_output_rate_samples = max (max_output_rate_samples ,len (app .history .output_rate )) 193max_batch_samples = max (max_batch_samples ,len (app .history .batch_rows )) 194max_pre_admit_samples = max (max_pre_admit_samples ,len (app .history .pre_admit )) 195max_device_histories = max (max_device_histories ,len (app .history .device_util )) 196max_device_samples = max (max_device_samples , 197* (len (rows )for rows in app .history .device_util .values ()),0 ) 198sensor_gap_observed |= any (rows and rows [- 1 ]is None 199for rows in app .history .device_util .values ()) 200max_vram_histories = max (max_vram_histories ,len (app .history .device_vram )) 201max_vram_samples = max (max_vram_samples , 202* (len (rows )for rows in app .history .device_vram .values ()),0 ) 203vram_sensor_gap_observed |= any (rows and rows [- 1 ]is None 204for rows in app .history .device_vram .values ()) 205await asyncio .sleep (min (0.5 ,max (0.01 ,seconds - elapsed ))) 206await pilot .press ("6" ) 207await pilot .pause (0.1 ) 208latest = app .latest 209final_instance = (latest .get ("instance" )or {}).get ("id" ) 210retained_activity = len ((latest .get ("activity" )or {}).get ("events" )or []) 211retained_requests = len ((latest .get ("work" )or {}).get ("requests" )or []) 212output_rate_samples = list (app .history .output_rate ) 213valid_output_rate_samples = sum (value is not None for value in output_rate_samples ) 214valid_batch_samples = sum (value is not None for value in app .history .batch_rows ) 215valid_pre_admit_samples = sum (value is not None for value in app .history .pre_admit ) 216output_rate_instance = app .history .instance 217monitor_recovered = app .error is None and app .failures == 0 218await pilot .press ("q" ) 219process_memory = tracemalloc .get_traced_memory ()[0 ] 220counters = service .counters () 221# A fresh read after detach proves the monitor did not shut down the server. 222detached_server_readable = endpoint .snapshot ()["instance" ]["id" ]== final_instance 223return {"schema_version" :1 ,"scope" :"synthetic_headless_monitor_soak" , 224"duration_s" :round (time .monotonic ()- started ,2 ),"poll_interval_s" :interval , 225"events" :events ,"final_instance_id" :final_instance , 226"monitor_states" :sorted (observed_states ), 227"retained_activity" :retained_activity ,"retained_requests" :retained_requests , 228"output_rate_samples_retained" :len (output_rate_samples ), 229"output_rate_valid_samples" :valid_output_rate_samples , 230"output_rate_history_max_samples" :max_output_rate_samples , 231"batch_history_max_samples" :max_batch_samples , 232"batch_history_valid_samples" :valid_batch_samples , 233"pre_admit_history_max_samples" :max_pre_admit_samples , 234"pre_admit_history_valid_samples" :valid_pre_admit_samples , 235"output_rate_history_instance" :list (output_rate_instance )if output_rate_instance else None , 236"exercise_ui" :exercise_ui , 237"resize_count" :resize_count , 238"terminal_sizes_seen" : [list (size )for size in sorted (sizes_seen )], 239"device_history_max_cards" :max_device_histories , 240"device_history_max_samples" :max_device_samples , 241"device_sensor_gap_observed" :sensor_gap_observed , 242"vram_history_max_cards" :max_vram_histories , 243"vram_history_max_samples" :max_vram_samples , 244"vram_sensor_gap_observed" :vram_sensor_gap_observed , 245"traced_memory_baseline_bytes" :baseline , 246"traced_memory_final_bytes" :process_memory , 247"traced_memory_growth_bytes" :process_memory - baseline if baseline is not None else None , 248"synthetic_memory_growth_budget_bytes" :20 * 1024 * 1024 , 249"combined_process_cpu_s" :round (time .process_time ()- cpu_started ,3 ), 250"monitor_recovered" :monitor_recovered , 251"detached_server_readable" :detached_server_readable , 252"http" : {** counters , 253"gets_per_s" :round (counters ["gets" ]/ max (0.1 ,time .monotonic ()- started ),3 ), 254"bytes_per_s" :round (counters ["bytes_sent" ]/ max (0.1 ,time .monotonic ()- started ),1 )}, 255"passed" : (set (events )== {"disconnect" ,"reconnect" ,"restart" , 256"second_disconnect" ,"second_reconnect" } 257and final_instance == "synthetic-1" and retained_activity <= 32 258and retained_requests <= 50 and 2 <= valid_output_rate_samples 259and max_output_rate_samples <= app .history .limit 260and 2 <= valid_batch_samples and max_batch_samples <= app .history .limit 261and 2 <= valid_pre_admit_samples and max_pre_admit_samples <= app .history .limit 262and output_rate_instance == ("id" ,final_instance ) 263and counters ["other_methods" ]== 0 264and counters ["max_in_flight" ]<= 1 and counters ["http_failures" ]>= 2 265and {"connecting" ,"connected" ,"stale" }<= observed_states 266and monitor_recovered and detached_server_readable and baseline is not None 267and process_memory - baseline <= 20 * 1024 * 1024 268and (not exercise_ui or 269 (sizes_seen == set (resize_size_cycle )and resize_count >= 4 270and max_device_histories <= 4 and max_device_samples <= app .history .limit 271and sensor_gap_observed 272and set (app .history .device_util )== {0 ,1 ,2 ,3 } 273and max_vram_histories <= 4 and max_vram_samples <= app .history .limit 274and vram_sensor_gap_observed 275and set (app .history .device_vram )== {0 ,1 ,2 ,3 })))} 276finally : 277server .shutdown () 278server .server_close () 279thread .join (timeout = 2 ) 280tracemalloc .stop () 281 282 283def main (argv :list [str ]| None = None )-> int : 284parser = argparse .ArgumentParser (description = "Headless synthetic Strata Monitor soak" ) 285parser .add_argument ("--seconds" ,type = float ,default = 1800 ) 286parser .add_argument ("--interval" ,type = float ,default = 0.5 ) 287parser .add_argument ("--exercise-ui" ,action = "store_true" , 288help = "resize across five terminal sizes and churn selected/host card sensors" ) 289parser .add_argument ("--report" ,type = Path ,required = True ,help = "new absolute JSON report path" ) 290args = parser .parse_args (argv ) 291if not 8 <= args .seconds <= 3600 or not 0.5 <= args .interval <= 30 : 292parser .error ("--seconds must be 8..3600 and --interval must be 0.5..30" ) 293if args .exercise_ui and args .seconds < 30 : 294parser .error ("--exercise-ui requires at least 30 seconds" ) 295report_path = args .report .expanduser () 296if not report_path .is_absolute ()or report_path .exists (): 297parser .error ("--report must be an absolute new file" ) 298result = asyncio .run (soak (args .seconds ,args .interval ,exercise_ui = args .exercise_ui )) 299report_path .parent .mkdir (parents = True ,exist_ok = True ) 300descriptor = os .open (report_path ,os .O_WRONLY | os .O_CREAT | os .O_EXCL ,0o600 ) 301with os .fdopen (descriptor ,"w" ,encoding = "utf-8" )as stream : 302json .dump (result ,stream ,indent = 2 ) 303stream .write ("\n" ) 304json .dumps ({"report" :str (report_path ),"passed" :result ["passed" ]}),flush = True ) 305return 0 if result ["passed" ]else 6 306 307 308if __name__ == "__main__" : 309raise SystemExit (main ())