okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cc500be1c
main
1"""Terminal contract checks that run without model weights or a GPU.""" 2 3import asyncio 4import copy 5import contextlib 6import io 7import json 8import os 9import tempfile 10import time 11import unittest 12from contextlib import redirect_stdout 13from pathlib import Path 14from unittest import mock 15 16from strata_cli .cli import main 17from strata_cli .client import (ClientError ,Endpoint ,normalize_legacy ,normalize_status_only , 18sanitize_telemetry ,server_url ) 19from strata_cli .render import display_width ,field ,render_view ,safe 20from serve .server import (configure_batch_telemetry_env ,parse_batch_window_sample , 21parse_stage_in_flight_sample ,parse_engine_stage_line , 22read_engine_stage_log ,visible_device_order ) 23 24 25def four_gpu_snapshot (): 26metrics = { 27"time" :1_790_000_000.0 , 28"engine" : {"model" :"test-model" ,"batch_groups" :4 }, 29"live" : {"parallel" :8 ,"running" :6 ,"queued" :5 ,"waiting" :2 , 30"slots" : [{"slot" :i ,"group" :i // 2 ,"state" :"decoding" if i < 6 else "idle" , 31"prompt_tokens" :400 + i ,"generated" :i * 10 }for i in range (8 )]}, 32"hardware_static" : {"gpu_count" :4 ,"gpu_name" :"aggregate" }, 33"hardware" : {"gpu_mem_used" :1000 , 34"gpus" : [{"index" :i ,"name" :f"GPU- { i } " ,"mem_used" :12 * 2 ** 30 , 35"mem_total" :24 * 2 ** 30 ,"util" :50 + i ,"temp" :60 + i , 36"power" :200 + i }for i in range (4 )]}, 37"requests" : [{"finish" :"stop" ,"prompt_tokens" :100 ,"output_tokens" :20 }], 38"totals" : {"requests" :1 ,"output_tokens" :20 }, 39 } 40status = {"service" :"strata" ,"model" :"test-model" ,"loaded" :True , 41"concurrency" : {"serving" :8 },"started" :1_789_999_000 } 42return normalize_legacy (metrics ,status ) 43 44 45class ContractTests (unittest .TestCase ): 46def test_replica_slots_and_requests_keep_identity_without_aggregate_batch_claim (self ): 47sample = four_gpu_snapshot () 48sample ["topology" ]["mode" ]= "replicas (configured)" 49sample ["topology" ]["replica_devices" ]= [{"replica" :0 ,"devices" : [0 ,1 ]}, 50 {"replica" :1 ,"devices" : [2 ,3 ]}] 51sample ["sampled_at" ]= time .time () 52sample ["work" ]["groups" ]= 2 53sample ["work" ]["effective_rows_window" ]= None 54for slot in sample ["work" ]["slots" ]: 55slot ["replica" ]= slot ["slot" ]// 4 56slot ["group" ]= slot ["replica" ] 57sample ["work" ]["requests" ]= [{"id" :"abcdef012345" ,"state" :"reading" ,"slot" :5 , 58"group" :1 ,"replica" :1 ,"prompt_tokens" :100 ,"prompt_read" :12 }] 59clean = sanitize_telemetry (sample ) 60self .assertEqual (clean ["work" ]["slots" ][5 ]["replica" ],1 ) 61self .assertEqual (clean ["work" ]["requests" ][0 ]["replica" ],1 ) 62self .assertEqual (clean ["topology" ]["replica_devices" ][1 ]["devices" ], [2 ,3 ]) 63from rich .console import Console 64from strata_cli .dashboard import MonitorHistory ,render_dashboard 65output = io .StringIO () 66Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 67clean ,width = 108 ,height = 28 ,history = MonitorHistory (),color = False )) 68self .assertIn ("replicas 2" ,output .getvalue ()) 69self .assertIn ("R1 G1" ,output .getvalue ()) 70self .assertRegex (output .getvalue (),r"GPU 2 R1" ) 71sample ["work" ]["replica_batches" ]= [ 72 {"replica" :0 ,"batch_sample_windows" :2 ,"batch_sample_rows" :8 , 73"batch_sample_active_rows" :4 ,"batch_sample_span_s" :1.0 ,"batch_sample_age_s" :0.5 }, 74 {"replica" :1 ,"batch_sample_windows" :2 ,"batch_sample_rows" :6 , 75"batch_sample_active_rows" :4 ,"batch_sample_span_s" :1.0 ,"batch_sample_age_s" :0.7 }] 76sample ["work" ].update (batch_sample_windows = 2 ,batch_sample_rows = 8 , 77batch_sample_active_rows = 4 ,batch_sample_span_s = 1.0 , 78batch_sample_age_s = 0.5 ) 79clean = sanitize_telemetry (sample ) 80self .assertIsNone (clean ["work" ]["effective_rows_window" ]) 81self .assertEqual ([row .get ("effective_rows_window" )for row in clean ["work" ]["replica_batches" ]], 82 [4.0 ,3.0 ]) 83output = io .StringIO () 84Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 85clean ,width = 108 ,height = 28 ,history = MonitorHistory (),color = False )) 86self .assertIn ("R0 4.0/2.0" ,output .getvalue ()) 87self .assertIn ("R1 3.0/2.0" ,output .getvalue ()) 88self .assertIn ("R1 3.0/2.0" ,render_view (clean ,"serving" ,110 ,30 )) 89self .assertIn ("Replica 1" ,render_view (clean ,"serving" ,80 ,24 , 90serving_pane = "groups" ,selected = 5 ,detail = True )) 91self .assertIn ("Replica 1" ,render_view (clean ,"requests" ,80 ,24 ,selected = 0 ,detail = True )) 92self .assertIn ("Replica R1 [configured cards 2,3" ,render_view ( 93clean ,"hardware" ,80 ,24 ,selected = 2 ,detail = True )) 94sample ["topology" ]["replica_stages" ]= [ 95 {"replica" :replica ,"stages" : [ 96 {"stage" :stage ,"layer_start" :stage * 20 ,"layer_end" :stage * 20 + 19 , 97"engine_ordinal" :stage ,"device_index" :replica * 2 + stage } 98for stage in range (2 )]}for replica in range (2 )] 99sample ["work" ]["replica_stage_samples" ]= [ 100 {"replica" :0 ,"stage_sample_elapsed_us" :1_000_000 , 101"stage_in_flight_us" : [800_000 ,600_000 ],"stage_sample_age_s" :0.5 }, 102 {"replica" :1 ,"stage_sample_elapsed_us" :1_000_000 , 103"stage_in_flight_us" : [700_000 ,500_000 ],"stage_sample_age_s" :0.7 }] 104clean = sanitize_telemetry (sample ) 105self .assertTrue (clean ["topology" ]["replica_stages" ][1 ]["resolved" ]) 106self .assertEqual (clean ["quality" ]["stage_in_flight" ],"unavailable" ) 107self .assertEqual (clean ["quality" ]["replica_stage_in_flight" ],"measured_host_span" ) 108self .assertEqual ([row ["stage_in_flight" ][0 ]["percent" ]for row in 109clean ["work" ]["replica_stage_samples" ]], [80.0 ,70.0 ]) 110self .assertIn ("R1 Stage 1 Device 3 Layers 20-39 In-flight 50%" , 111render_view (clean ,"engine" ,80 ,24 )) 112self .assertIn ("Replica host span R0 S0 80% S1 60% R1 S0 70% S1 50%" ,render_view ( 113clean ,"serving" ,110 ,30 )) 114self .assertIn ("Replica R1 stage/layers 1:20-39 [engine log]" ,render_view ( 115clean ,"hardware" ,80 ,24 ,selected = 3 ,detail = True )) 116output = io .StringIO () 117Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 118clean ,width = 108 ,height = 28 ,history = MonitorHistory (),color = False )) 119self .assertIn ("Host span R1 S0 70%" ,output .getvalue ()) 120self .assertIn ("GPU 2 R1/S0" ,output .getvalue ()) 121old_stage = copy .deepcopy (clean ) 122old_stage ["work" ]["replica_stage_samples" ][1 ]["stage_sample_age_s" ]= 5.1 123output = io .StringIO () 124Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 125old_stage ,width = 108 ,height = 28 ,history = MonitorHistory (),color = False )) 126self .assertIn ("Host span R1 --" ,output .getvalue ()) 127self .assertNotIn ("Host span R1 S0 70%" ,output .getvalue ()) 128compact_output = io .StringIO () 129Console (file = compact_output ,width = 80 ,color_system = None ).render_dashboard ( 130clean ,width = 78 ,height = 24 ,history = MonitorHistory (),color = False )) 131self .assertIn ("GPU 3 R1/S1" ,compact_output .getvalue ()) 132shared_card = copy .deepcopy (clean ) 133shared_card ["topology" ]["replica_stages" ][1 ]["stages" ][0 ]["device_index" ]= 3 134shared_output = io .StringIO () 135Console (file = shared_output ,width = 80 ,color_system = None ).render_dashboard ( 136shared_card ,width = 78 ,height = 24 ,history = MonitorHistory (),color = False )) 137self .assertIn ("GPU 3 R1 " ,shared_output .getvalue ()) 138self .assertNotIn ("GPU 3 R1/S" ,shared_output .getvalue ()) 139partial = copy .deepcopy (sample ) 140partial ["work" ]["slots" ]= partial ["work" ]["slots" ][:2 ] 141output = io .StringIO () 142Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 143sanitize_telemetry (partial ),width = 108 ,height = 28 ,history = MonitorHistory (),color = False )) 144self .assertIn ("replicas 2" ,output .getvalue ()) 145self .assertIn ("R0 4.0/2.0" ,output .getvalue ()) 146self .assertIn ("Group occupancy --" ,output .getvalue ()) 147sample ["work" ]["slots" ][5 ]["replica" ]= 1.5 148sample ["work" ]["requests" ][0 ]["replica" ]= True 149sample ["work" ]["replica_batches" ][1 ]["batch_sample_rows" ]= 99 150sample ["work" ]["replica_stage_samples" ][1 ]["stage_in_flight_us" ]= [700_000 ] 151sample ["topology" ]["replica_stages" ][1 ]["stages" ][1 ]["device_index" ]= 9 152sample ["topology" ]["replica_devices" ].append ({"replica" :2 ,"devices" : [3 ]}) 153rejected = sanitize_telemetry (sample ) 154self .assertIsNone (rejected ["work" ]["slots" ][5 ]["replica" ]) 155self .assertIsNone (rejected ["work" ]["requests" ][0 ]["replica" ]) 156self .assertIsNone (rejected ["work" ]["replica_batches" ][1 ].get ("effective_rows_window" )) 157self .assertNotIn ("stage_in_flight" ,rejected ["work" ]["replica_stage_samples" ][1 ]) 158self .assertEqual (rejected ["work" ]["replica_stage_samples" ][0 ]["stage_in_flight" ][0 ]["percent" ],80.0 ) 159self .assertEqual (rejected ["quality" ]["replica_stage_in_flight" ],"measured_host_span" ) 160self .assertEqual (len (rejected ["topology" ]["replica_devices" ]),2 ) 161self .assertIsNone (rejected ["topology" ]["replica_stages" ][1 ]["stages" ][1 ]["device_index" ]) 162self .assertFalse (rejected ["topology" ]["replica_stages" ][1 ]["resolved" ]) 163output = io .StringIO () 164Console (file = output ,width = 80 ,color_system = None ).render_dashboard ( 165rejected ,width = 78 ,height = 24 ,history = MonitorHistory (),color = False )) 166self .assertIn ("GPU 3 R1 " ,output .getvalue ()) 167self .assertNotIn ("GPU 3 R1/S1" ,output .getvalue ()) 168 169def test_display_cells_preserve_wide_and_combining_clusters (self ): 170self .assertEqual (safe ("漢字" ,3 ),"漢" ) 171self .assertEqual (display_width (safe ("漢字" ,3 )),2 ) 172self .assertEqual (safe ("x\u0338Y" ,1 ),"x\u0338" ) 173self .assertEqual (display_width (safe ("x\u0338Y" ,1 )),1 ) 174self .assertEqual (safe ("🇭🇷next" ,1 ),"" ) 175self .assertEqual (safe ("🇭🇷next" ,2 ),"🇭🇷" ) 176self .assertEqual (safe ("👩💻next" ,2 ),"👩💻" ) 177self .assertEqual (safe ("\u202e漢" ,2 ),"漢" ) 178self .assertEqual (display_width (field ("漢A" ,4 )),4 ) 179self .assertEqual (field ("漢A" ,4 ),"漢A " ) 180snapshot = four_gpu_snapshot () 181snapshot ["devices" ][0 ]["name" ]= "漢字GPUx\u0338" 182snapshot ["work" ]["requests" ]= [{"id" :"漢字reqx\u0338" ,"state" :"decoding" , 183"slot" :0 ,"group" :0 ,"generated" :3 }] 184for width ,height in ((110 ,30 ), (80 ,24 ), (60 ,16 ), (40 ,12 )): 185with self .subTest (width = width ): 186for name in ("hardware" ,"serving" ,"requests" ): 187view = render_view (snapshot ,name ,width ,height ) 188self .assertTrue (all (display_width (line )<= width for line in view .splitlines ()),name ) 189 190def test_batch_telemetry_opt_in_and_explicit_disable_are_reversible (self ): 191env = {"STRATA_BATCH_TELEMETRY" :"1" } 192configure_batch_telemetry_env (env , {},None ) 193self .assertEqual (env ["STRATA_BATCH_TELEMETRY" ],"1" ) 194configure_batch_telemetry_env (env , {"batch_telemetry" :False },None ) 195self .assertNotIn ("STRATA_BATCH_TELEMETRY" ,env ) 196configure_batch_telemetry_env (env , {"batch_telemetry" :False },True ) 197self .assertEqual (env ["STRATA_BATCH_TELEMETRY" ],"1" ) 198configure_batch_telemetry_env (env , {"batch_telemetry" :True },False ) 199self .assertNotIn ("STRATA_BATCH_TELEMETRY" ,env ) 200 201def test_batch_window_sample_distinguishes_processed_rows_from_active_slots (self ): 202self .assertEqual (parse_batch_window_sample ("BSTAT 3 18 9 1000\n" ), 203 {"windows" :3 ,"processed_rows" :18 ,"active_rows" :9 ,"elapsed_ms" :1000 }) 204for invalid in ("BSTAT 0 2 1 100" ,"BSTAT 1 9 1 100" ,"BSTAT 1 4 5 100" ,"BSTAT 2 2 0 100" , 205"BSTAT 1 1 1 0" ,"BSTAT 1 1 1 extra" ,"BSTAT " + "9" * 100 ): 206self .assertIsNone (parse_batch_window_sample (invalid )) 207sample = four_gpu_snapshot () 208sample ["work" ].update (batch_sample_windows = 3 ,batch_sample_rows = 18 , 209batch_sample_active_rows = 9 ,batch_sample_span_s = 1.0 , 210batch_sample_age_s = 1.5 , 211effective_rows_window = 999 ) 212sample ["quality" ]["batch_window_rows" ]= "measured" 213clean = sanitize_telemetry (sample ) 214self .assertEqual (clean ["work" ]["effective_rows_window" ],6.0 ) 215self .assertEqual (clean ["work" ]["batch_active_rows_window" ],3.0 ) 216self .assertEqual (clean ["quality" ]["batch_window_rows" ],"measured" ) 217self .assertEqual (clean ["quality" ]["batch_window_source" ],"engine_bstat" ) 218serving = render_view (clean ,"serving" ,110 ,30 ) 219self .assertIn ("6.0 processed / 3.0 active" ,serving ) 220sample ["work" ]["batch_sample_rows" ]= 25 221rejected = sanitize_telemetry (sample ) 222self .assertIsNone (rejected ["work" ]["effective_rows_window" ]) 223self .assertEqual (rejected ["quality" ]["batch_window_rows" ],"unavailable" ) 224 225def test_pipeline_stage_in_flight_sample_is_bounded_and_labelled_host_time (self ): 226self .assertEqual (parse_stage_in_flight_sample ("PSTAT 4 20000 16000 14000 12000 10000\n" ), 227 {"elapsed_us" :20000 ,"in_flight_us" : [16000 ,14000 ,12000 ,10000 ]}) 228for invalid in ("PSTAT 1 20000 10000" ,"PSTAT 4 20000 16000 14000 12000" , 229"PSTAT 4 20000 16000 14000 12000 21000" ,"PSTAT 2 0 0 0" , 230"PSTAT 2 100 1 -1" ,"PSTAT 2 100 1 1 extra" ,"PSTAT " + "9" * 300 ): 231self .assertIsNone (parse_stage_in_flight_sample (invalid )) 232sample = four_gpu_snapshot () 233sample ["work" ].update (stage_sample_elapsed_us = 1_000_000 , 234stage_in_flight_us = [800000 ,700000 ,600000 ,500000 ], 235stage_sample_age_s = 0.2 ) 236clean = sanitize_telemetry (sample ) 237self .assertEqual ([row ["percent" ]for row in clean ["work" ]["stage_in_flight" ]], 238 [80.0 ,70.0 ,60.0 ,50.0 ]) 239self .assertEqual (clean ["quality" ]["stage_in_flight_source" ],"engine_pstat_host_span" ) 240self .assertIn ("S3 50%" ,render_view (clean ,"serving" ,110 ,30 )) 241self .assertIn ("80/70/60/50%" ,render_view (clean ,"engine" ,40 ,12 )) 242self .assertIn ("GPU kernel occupancy unavailable" ,render_view (clean ,"engine" ,80 ,24 )) 243from rich .console import Console 244from strata_cli .dashboard import MonitorHistory ,render_dashboard 245old_stage = copy .deepcopy (clean ) 246old_stage ["work" ]["stage_sample_age_s" ]= 5.1 247output = io .StringIO () 248Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 249old_stage ,width = 108 ,height = 28 ,history = MonitorHistory (),color = False )) 250self .assertIn ("Stage host span --" ,output .getvalue ()) 251detail = render_view (clean ,"serving" ,80 ,24 ,serving_pane = "groups" ,selected = 7 ,detail = True ) 252self .assertIn ("group 3" ,detail ) 253self .assertIn ("q quit" ,detail ) 254sample ["topology" ]= {"mode" :"layer split" ,"resolved" :True ,"source" :"engine_start_log" , 255"stages" : [{"stage" :i ,"layer_start" :i * 12 ,"layer_end" :i * 12 + 11 , 256"engine_ordinal" :i ,"device_index" :i }for i in range (4 )]} 257mapped = sanitize_telemetry (sample ) 258engine = render_view (mapped ,"engine" ,80 ,24 ) 259self .assertIn ("Stage 3 Engine GPU 3 Device 3 Layers 36-47 In-flight 50%" ,engine ) 260self .assertIn ("q quit" ,engine ) 261sample ["work" ]["stage_in_flight_us" ]= [800000 ,700000 ,600000 ] 262self .assertEqual (sanitize_telemetry (sample )["quality" ]["stage_in_flight" ],"unavailable" ) 263sample ["work" ]["stage_in_flight_us" ]= [800000 ,700000 ,600000 ,500000 ] 264sample ["work" ]["stage_in_flight_us" ][1 ]= 1_000_001 265rejected = sanitize_telemetry (sample ) 266self .assertEqual (rejected ["work" ]["stage_in_flight" ], []) 267self .assertEqual (rejected ["quality" ]["stage_in_flight" ],"unavailable" ) 268 269def test_engine_stage_log_is_bounded_and_reports_only_valid_final_ranges (self ): 270line = ("strata serve: layer split: layers 0-11 (CUDA0), 12-23 (CUDA1), " 271"24-35 (CUDA2), 36-47 (CUDA3), one hand-off per window" ) 272self .assertEqual ([row ["layer_start" ]for row in parse_engine_stage_line (line )], [0 ,12 ,24 ,36 ]) 273for bad in (line .replace ("12-23" ,"13-23" ),line .replace ("CUDA3" ,"CUDA99" ), 274line .replace ("0-11" ,"0" * 6000 + "-11" ), 275line .replace ("one hand-off per window" ,"unverified" )): 276self .assertIsNone (parse_engine_stage_line (bad )) 277with tempfile .TemporaryDirectory ()as directory : 278path = Path (directory )/ "engine.log" 279path .write_text (line + "\n" ,encoding = "utf-8" ) 280offset = path .stat ().st_size 281self .assertEqual (read_engine_stage_log (str (path ),offset ), []) 282with path .open ("a" ,encoding = "utf-8" )as target : 283target .write ("INFO engine=0.1.42\n" + line + "\nREADY 4096 stop\n" ) 284self .assertEqual (len (read_engine_stage_log (str (path ),offset )),4 ) 285self .assertEqual (read_engine_stage_log (str (path ),offset ,limit = 12 ), []) 286cuda_env = {"CUDA_VISIBLE_DEVICES" :"2,0,3,1" ,"CUDA_DEVICE_ORDER" :"PCI_BUS_ID" } 287self .assertEqual (visible_device_order (cuda_env ,"cuda" ), [2 ,0 ,3 ,1 ]) 288self .assertEqual (visible_device_order ({"CUDA_VISIBLE_DEVICES" :"2,0,3,1" },"cuda" ), []) 289self .assertEqual (visible_device_order ({"HIP_VISIBLE_DEVICES" :"1,0" },"hip" ), [1 ,0 ]) 290self .assertEqual (visible_device_order ({** cuda_env ,"CUDA_VISIBLE_DEVICES" :"2,2" },"cuda" ), []) 291self .assertEqual (visible_device_order ({** cuda_env ,"CUDA_VISIBLE_DEVICES" :"9" * 6000 },"cuda" ), []) 292self .assertEqual (visible_device_order ({"CUDA_VISIBLE_DEVICES" :"2,0" },"sycl" ), []) 293 294def test_reported_stage_ranges_render_and_invalid_remote_map_is_rejected (self ): 295s = four_gpu_snapshot () 296s ["topology" ]= {"mode" :"layer split (engine reported)" ,"resolved" :True , 297"source" :"engine_start_log" ,"stages" : [ 298 {"stage" :i ,"layer_start" :i * 12 ,"layer_end" :i * 12 + 11 , 299"engine_ordinal" :i ,"device_index" :i }for i in range (4 )]} 300clean = sanitize_telemetry (s ) 301self .assertTrue (clean ["topology" ]["resolved" ]) 302engine = render_view (clean ,"engine" ,80 ,24 ) 303device = render_view (clean ,"hardware" ,80 ,24 ,selected = 3 ,detail = True ) 304wide = render_view (clean ,"serving" ,110 ,30 ) 305self .assertIn ("Stage 3 Engine GPU 3 Device 3 Layers 36-47" ,engine ) 306self .assertIn ("Stage/layers 3:36-47 [engine log]" ,device ) 307self .assertIn ("GPU 3: 36-47" ,wide ) 308s ["topology" ]["stages" ][1 ]["layer_start" ]= 13 309rejected = sanitize_telemetry (s ) 310self .assertEqual (rejected ["topology" ]["stages" ], []) 311self .assertFalse (rejected ["topology" ]["resolved" ]) 312self .assertEqual (rejected ["quality" ]["placement" ],"unavailable" ) 313 314def test_remote_url_requires_tls_and_no_embedded_credentials (self ): 315for url in ("http://example.com:8080" ,"https://key@example.com" ,"https://example.com/v1" , 316"https://example.com/#fragment" ): 317with self .assertRaises (ValueError ,msg = url ): 318server_url (url ) 319self .assertEqual (server_url ("http://127.0.0.1:8080/" ),"http://127.0.0.1:8080" ) 320 321def test_parallel_fields_do_not_invent_window_metrics (self ): 322s = four_gpu_snapshot () 323self .assertEqual (len (s ["devices" ]),4 ) 324self .assertEqual (s ["work" ]["groups" ],4 ) 325self .assertEqual (s ["work" ]["active" ],6 ) 326self .assertEqual (s ["work" ]["occupied_slots" ],6 ) 327self .assertEqual (s ["work" ]["queued" ],5 ) 328self .assertIsNone (s ["work" ]["effective_rows_window" ]) 329self .assertIsNone (s ["work" ]["slots_requested" ]) 330self .assertIsNone (s ["topology" ]["mode" ]) 331serving = render_view (s ,"serving" ,110 ,30 ) 332self .assertIn ("GPU 3" ,serving ) 333self .assertIn ("group 3" ,serving ) 334self .assertIn ("rows/window --" ,serving ) 335self .assertIn ("Engine waiting 2" ,serving ) 336self .assertIn ("Slots occupied 6/8" ,serving ) 337self .assertIn ("Stage/layer mapping unavailable" ,serving ) 338self .assertNotIn ("aggregate" ,serving ) 339s ["work" ]["requests" ]= [{"id" :"queued-1" ,"state" :"queued" ,"queued_at" :1_790_000_000.0 , 340"slot" :None ,"group" :None ,"prompt_tokens" :512 }] 341requests = render_view (s ,"serving" ,80 ,24 ,serving_pane = "requests" ) 342groups = render_view (s ,"serving" ,80 ,24 ,serving_pane = "groups" ) 343request_view = render_view (s ,"requests" ,80 ,24 ) 344self .assertIn ("queued-1" ,requests ) 345self .assertIn ("group 3" ,groups ) 346last_group = render_view (s ,"serving" ,80 ,24 ,serving_pane = "groups" ,selected = 7 ) 347self .assertIn ("slot 7" ,last_group ) 348self .assertIn ("group 3" ,last_group ) 349self .assertIn ("queued-1" ,request_view ) 350s ["work" ]["requests" ]= [{"id" :f"r { i :02d } " ,"state" :"queued" if i > 5 else "decoding" , 351"queued_at" :1_790_000_000.0 }for i in range (11 )] 352scrolled = render_view (s ,"serving" ,80 ,24 ,serving_pane = "requests" ,selected = 10 ) 353self .assertIn ("r10" ,scrolled ) 354self .assertIn ("queued" ,scrolled ) 355 356def test_occupied_slot_count_requires_complete_report (self ): 357metrics = {"live" : {"slots" : [{"slot" :i ,"state" :"decoding" if i < 6 else "idle" } 358for i in range (8 )]}} 359status = {"concurrency" : {"serving" :8 }} 360complete = normalize_legacy (metrics ,status ) 361self .assertEqual (complete ["work" ]["occupied_slots" ],6 ) 362complete ["work" ]["occupied_slots" ]= 99 363self .assertEqual (sanitize_telemetry (complete )["work" ]["occupied_slots" ],6 ) 364metrics ["live" ]["slots" ]= metrics ["live" ]["slots" ][:- 1 ] 365partial = normalize_legacy (metrics ,status ) 366self .assertIsNone (partial ["work" ]["occupied_slots" ]) 367partial ["work" ]["occupied_slots" ]= 6 368self .assertIsNone (sanitize_telemetry (partial )["work" ]["occupied_slots" ]) 369metrics ["live" ]["slots" ].append ({"slot" :0 ,"state" :"decoding" }) 370self .assertIsNone (normalize_legacy (metrics ,status )["work" ]["occupied_slots" ]) 371metrics ["live" ]["slots" ]= [{"slot" :i ,"state" :"decoding" }for i in range (70 )] 372status ["concurrency" ]["serving" ]= 70 373self .assertEqual (len (normalize_legacy (metrics ,status )["work" ]["slots" ]),64 ) 374self .assertIsNone (normalize_legacy (metrics ,status )["work" ]["occupied_slots" ]) 375 376def test_admission_pressure_is_preserved_in_monitor_contract (self ): 377s = four_gpu_snapshot () 378s ["work" ].update (admission_reserved = 8 ,admission_limit = 8 ,max_queue = 0 , 379admission_rejected = 3 ,oldest_queue_s = 0 ,client_disconnect_cancels = 2 ) 380clean = sanitize_telemetry (s ) 381self .assertEqual (clean ["work" ]["max_queue" ],0 ) 382display = render_view (clean ,"serving" ,110 ,30 ) 383self .assertIn ("Admission 8/8" ,display ) 384self .assertIn ("Queue cap 0" ,display ) 385self .assertIn ("Rejected 3" ,display ) 386self .assertIn ("Disconnect cancels 2" ,display ) 387 388def test_wide_parallel_layout_keeps_no_slot_requests_visible (self ): 389s = four_gpu_snapshot () 390s ["work" ]["requests" ]= [ 391 {"id" :f"r { i :02d } " ,"state" :"decoding" if i < 8 else "admitted" , 392"slot" :i if i < 8 else None ,"group" :i // 2 if i < 8 else None } 393for i in range (12 )] 394display = render_view (s ,"serving" ,110 ,30 ) 395self .assertIn ("r11" ,display ) 396self .assertIn ("more requests" ,display ) 397 398def test_parallel_prompt_progress_and_frozen_queue_age (self ): 399s = four_gpu_snapshot () 400s ["work" ]["requests" ]= [ 401 {"id" :"reading-1" ,"state" :"reading" ,"slot" :0 ,"group" :0 , 402"queued_at" :1_789_999_998.0 ,"admitted_at" :1_789_999_999.0 , 403"prompt_tokens" :1000 ,"prompt_read" :250 ,"generated" :0 }, 404 {"id" :"queued-2" ,"state" :"queued" ,"slot" :None ,"group" :None , 405"queued_at" :1_789_999_995.0 ,"admitted_at" :None , 406"prompt_tokens" :900 ,"prompt_read" :None ,"generated" :None }, 407 ] 408for width ,height ,pane in ((110 ,30 ,"devices" ), (80 ,24 ,"requests" ), (40 ,12 ,"requests" )): 409shown = render_view (s ,"serving" ,width ,height ,serving_pane = pane ) 410self .assertIn ("read 250 new" ,shown ) 411self .assertLessEqual (len (shown .splitlines ()),height ) 412self .assertTrue (all (len (line )<= width for line in shown .splitlines ())) 413with mock .patch ("strata_cli.render.time.time" ,return_value = 1_800_000_000.0 ): 414shown = render_view (s ,"serving" ,80 ,24 ,serving_pane = "requests" ) 415self .assertIn ("wait 5.0 s" ,shown ) 416self .assertIn ("wait 1.0 s" ,shown ) 417small = render_view (s ,"requests" ,40 ,12 ,selected = 1 ) 418self .assertIn ("queued-2" ,small ) 419self .assertIn ("Pre-admit 5" ,small ) 420detail = render_view (s ,"serving" ,80 ,24 ,serving_pane = "requests" ,detail = True ) 421self .assertIn ("REQUEST DETAIL" ,detail ) 422self .assertIn ("Prompt 1,000 tokens" ,detail ) 423self .assertIn ("First engine token --" ,detail ) 424self .assertNotIn ("prompt body" ,detail .lower ()) 425fitted = render_view (s ,"serving" ,78 ,22 ,serving_pane = "requests" ,detail = True ) 426self .assertIn ("First engine token --" ,fitted ) 427self .assertIn ("Sample age" ,fitted ) 428self .assertIn ("q quit" ,fitted ) 429filtered = render_view (s ,"serving" ,110 ,30 ,filter_text = "queued-2" ) 430self .assertIn ("queued-2" ,filtered ) 431self .assertNotIn ("reading-1" ,filtered ) 432compact_detail = render_view (s ,"serving" ,60 ,16 ,serving_pane = "requests" ,selected = 1 ,detail = True ) 433self .assertIn ("queued-2" ,compact_detail ) 434self .assertIn ("Wait 5.0 s" ,compact_detail ) 435s ["work" ]["requests" ][0 ]["first_engine_token_s" ]= 1.234 436self .assertIn ("First engine token 1.234 s" ,render_view (s ,"serving" ,80 ,24 , 437serving_pane = "requests" ,detail = True )) 438s ["recent" ]= [{"finish" :"stop" ,"first_engine_token_s" :1.234 }] 439self .assertIn ("First engine token 1.234 s" ,render_view (s ,"overview" ,80 ,24 )) 440self .assertIn ("First engine token 1.234 s" ,render_view (s ,"serving" ,110 ,30 )) 441 442def test_small_layout_and_untrusted_text (self ): 443s = four_gpu_snapshot () 444s ["model" ]["id" ]= "\x1b[2Jfake\u202emodel" 445for width ,height in ((110 ,30 ), (80 ,24 ), (60 ,16 ), (40 ,12 )): 446output = render_view (s ,"overview" ,width ,height ) 447self .assertNotIn ("\x1b" ,output ) 448self .assertNotIn ("\u202e" ,output ) 449self .assertLessEqual (len (output .splitlines ()),height ) 450self .assertTrue (all (len (line )<= width for line in output .splitlines ())) 451if (width ,height )== (40 ,12 ): 452self .assertEqual (output .count ("More: strata status --json" ),1 ) 453 454def test_recent_request_detail_scrolls_and_wide_serving_tabs_select_panes (self ): 455s = four_gpu_snapshot () 456s ["work" ]["requests" ]= [{"id" :"live-1" ,"state" :"decoding" ,"slot" :0 ,"group" :0 }] 457s ["recent" ]= [{"id" :f"done- { i :02d } " ,"finish" :"stop" ,"prompt_tokens" :100 + i , 458"reused" :i ,"output_tokens" :12 ,"duration_s" :1.25 , 459"prompt_ms" :200 ,"decode_ms" :400 ,"first_engine_token_s" :0.7 } 460for i in range (20 )] 461wide_requests = render_view (s ,"serving" ,110 ,30 ,serving_pane = "requests" ) 462wide_groups = render_view (s ,"serving" ,110 ,30 ,serving_pane = "groups" ,selected = 7 ) 463self .assertIn ("Pane: Requests" ,wide_requests ) 464self .assertIn ("live-1" ,wide_requests ) 465self .assertIn ("Pane: Groups" ,wide_groups ) 466self .assertIn ("slot 7" ,wide_groups ) 467for width ,height in ((60 ,16 ), (40 ,12 )): 468devices = render_view (s ,"serving" ,width ,height ,serving_pane = "devices" ) 469requests = render_view (s ,"serving" ,width ,height ,serving_pane = "requests" ) 470groups = render_view (s ,"serving" ,width ,height ,serving_pane = "groups" ,selected = 7 ) 471self .assertIn ("GPU 0" ,devices ) 472self .assertIn ("live-1" ,requests ) 473self .assertIn ("slot 7" ,groups ) 474detail = render_view (s ,"requests" ,80 ,24 ,selected = 17 ,detail = True ) 475self .assertIn ("done-16" ,detail ) 476self .assertIn ("RECENT REQUEST DETAIL" ,detail ) 477self .assertIn ("First engine token 0.700 s" ,detail ) 478self .assertIn ("Sample age" ,detail ) 479self .assertLessEqual (len (detail .splitlines ()),24 ) 480self .assertTrue (all (len (line )<= 80 for line in detail .splitlines ())) 481small = render_view (s ,"requests" ,40 ,12 ,selected = 17 ,detail = True ) 482self .assertIn ("done-16" ,small ) 483self .assertIn ("Engine first 0.70 s" ,small ) 484self .assertIn ("Prompt 116" ,small ) 485s ["work" ]["requests" ]= [] 486only_recent = render_view (s ,"requests" ,40 ,12 ,selected = 0 ,detail = True ) 487self .assertIn ("done-00" ,only_recent ) 488self .assertIn ("Engine first 0.70 s" ,only_recent ) 489 490def test_device_and_slot_details_fit_standard_and_compact_views (self ): 491s = four_gpu_snapshot () 492s ["work" ]["slots" ][7 ]["request_id" ]= "request-7" 493for view ,pane ,width ,height ,selected ,marker in ( 494 ("serving" ,"devices" ,80 ,24 ,3 ,"GPU 3" ), 495 ("serving" ,"groups" ,80 ,24 ,7 ,"Slot 7" ), 496 ("hardware" ,"devices" ,80 ,24 ,3 ,"GPU 3" ), 497 ("serving" ,"devices" ,60 ,16 ,3 ,"GPU 3" ), 498 ("serving" ,"groups" ,40 ,12 ,7 ,"slot 7" ), 499 ("hardware" ,"devices" ,40 ,12 ,3 ,"GPU 3" ), 500 ): 501with self .subTest (view = view ,pane = pane ,width = width ): 502display = render_view (s ,view ,width ,height ,serving_pane = pane , 503selected = selected ,detail = True ) 504self .assertIn (marker ,display ) 505self .assertLessEqual (len (display .splitlines ()),height ) 506self .assertTrue (all (len (line )<= width for line in display .splitlines ())) 507self .assertIn ("q quit" ,display ) 508if width == 80 : 509self .assertIn ("DETAIL (read only)" ,display ) 510self .assertIn ("Sample age" ,display ) 511device = render_view (s ,"serving" ,80 ,24 ,serving_pane = "devices" ,selected = 3 ,detail = True ) 512slot = render_view (s ,"serving" ,80 ,24 ,serving_pane = "groups" ,selected = 7 ,detail = True ) 513self .assertIn ("Stage/layer mapping unavailable" ,device ) 514self .assertIn ("Request request-7" ,slot ) 515self .assertIn ("not a GPU assignment" ,slot ) 516 517def test_wide_serving_scrolls_to_selected_device (self ): 518s = four_gpu_snapshot () 519s ["devices" ]= [{"index" :i ,"name" :f"Card- { i } " ,"mem_used" :8 * 2 ** 30 , 520"mem_total" :24 * 2 ** 30 ,"util" :i ,"temp" :40 + i , 521"power" :100 + i }for i in range (16 )] 522display = render_view (s ,"serving" ,110 ,30 ,selected = 15 ) 523self .assertIn ("> GPU 15" ,display ) 524self .assertIn ("GPU SENSORS (" ,display ) 525self .assertIn ("q quit" ,display ) 526self .assertLessEqual (len (display .splitlines ()),30 ) 527 528def test_zero_is_not_unknown (self ): 529s = normalize_legacy ({"live" : {"queued" :0 ,"tok_s" :0 },"hardware" : {}, 530"totals" : {"requests" :0 }}, {"concurrency" : {"serving" :1 }}) 531self .assertEqual (s ["work" ]["queued" ],0 ) 532self .assertEqual (s ["rates" ]["answer_tok_s" ],0 ) 533self .assertIsNone (s ["rates" ]["prefill_tok_s" ]) 534 535def test_v1_snapshot_excludes_unknown_and_untrusted_content (self ): 536clean = sanitize_telemetry ({"schema_version" :1 ,"secret" :"do not render" , 537"model" : {"id" :"\x1b[2Jmodel" ,"prompt" :"private" }, 538"work" : {"slots" : [{"slot" :0 ,"state" :"decoding" , 539"prompt" :"private" }], 540"requests" : [{"id" :"req-1" ,"state" :"queued" , 541"first_engine_token_s" :float ("nan" ), 542"input" :"private" }]}, 543"rates" : {"answer_tok_s" :float ("nan" )}}) 544serialized = json .dumps (clean ) 545self .assertNotIn ("private" ,serialized ) 546self .assertNotIn ("do not render" ,serialized ) 547self .assertNotIn ("\x1b" ,serialized ) 548self .assertIsNone (clean ["rates" ]["answer_tok_s" ]) 549self .assertIsNone (clean ["work" ]["requests" ][0 ]["first_engine_token_s" ]) 550 551def test_activity_feed_is_bounded_redacted_and_visible_at_terminal_sizes (self ): 552raw = four_gpu_snapshot () 553raw ["activity" ]= {"last_seq" :70 ,"events" : [ 554 {"seq" :i ,"at" :1_790_000_000.0 ,"request_id" :f" { i :012x } " , 555"event" :"finished" ,"outcome" :"stop" ,"prompt" :"private" } 556for i in range (1 ,71 ) 557 ]} 558raw ["activity" ]["events" ][- 1 ]["event" ]= "\x1b[2Jforged" 559clean = sanitize_telemetry (raw ) 560self .assertTrue (clean ["activity" ]["available" ]) 561self .assertLessEqual (len (clean ["activity" ]["events" ]),32 ) 562self .assertNotIn ("private" ,json .dumps (clean )) 563self .assertNotIn ("forged" ,json .dumps (clean )) 564self .assertEqual (clean ["activity" ]["events" ][- 1 ]["seq" ],69 ) 565for width ,height in ((110 ,30 ), (80 ,24 ), (60 ,16 ), (40 ,12 )): 566display = render_view (clean ,"logs" ,width ,height ) 567self .assertIn ("activity" ,display ) 568self .assertIn ("finished" ,display ) 569self .assertNotIn ("private" ,display ) 570self .assertNotIn ("\x1b" ,display ) 571self .assertLessEqual (len (display .splitlines ()),height ) 572self .assertTrue (all (len (line )<= width for line in display .splitlines ())) 573legacy = render_view (four_gpu_snapshot (),"logs" ,80 ,24 ) 574self .assertIn ("unavailable" ,legacy ) 575raw ["activity" ]= {"last_seq" : [],"events" : [{"event" : []}]} 576self .assertFalse (sanitize_telemetry (raw )["activity" ]["available" ]) 577 578def test_cli_rejects_invalid_serve_flags_before_loading_engine (self ): 579with redirect_stdout (io .StringIO ()): 580self .assertEqual (main (["serve" ,"--profile" ,"missing.json" ,"--parallel" ,"0" ]),2 ) 581 582def test_offline_server_rejects_remote_image_before_fetch (self ): 583from serve .server import ByteTokenizer ,ChatTemplate ,MockEngine ,Service 584tok = ByteTokenizer () 585svc = Service (MockEngine (tok ,"ok" ),tok , 586ChatTemplate (Path (__file__ ).resolve ().parents [2 ]/ "serve/chat_template.jinja" )) 587svc .offline = True 588messages = [{"role" :"user" ,"content" : [{"type" :"image" ,"source" :"https://example.com/p.png" }]}] 589with self .assertRaisesRegex (ValueError ,"offline mode cannot download" ): 590svc .prepare (messages , [], {}) 591 592def test_direct_server_remote_bind_without_key_reaches_engine_load (self ): 593# no early exit over the key any more: every way of saying "no key" gets past the key check 594import serve .server as server 595cases = [('{"args":[]}' , []), ('{"args":[],"api_key":"none"}' , []), ('{"args":[]}' , ["--no-api-key" ]), 596 ('{"args":[]}' , ["--api-key" ,"none" ])] 597for body ,extra in cases : 598with tempfile .TemporaryDirectory ()as directory : 599profile = Path (directory )/ "model.json" 600profile .write_text (body ,encoding = "utf-8" ) 601err = io .StringIO () 602with mock .patch .dict (os .environ , {},clear = True ),contextlib .redirect_stderr (err ): 603with self .assertRaises (SystemExit ): 604server .main (["--engine" ,"strata" ,"--config" ,str (profile ), 605"--host" ,"0.0.0.0" ,"--port" ,"0" ,* extra ]) 606self .assertIn ("tokenizer is missing" ,err .getvalue (), (body ,extra ))# past the key check, stopped later 607 608def test_code_run_uses_missing_component_exit_until_shared_harness_arrives (self ): 609output = io .StringIO () 610with redirect_stdout (output ): 611code = main (["code" ,"run" ,"--prompt-file" ,"task.md" ,"--policy" ,"policy.json" , 612"--output" ,"jsonl" ]) 613self .assertEqual (code ,5 ) 614self .assertEqual (json .loads (output .getvalue ())["error" ]["code" ],5 ) 615 616 617try : 618from strata_cli .monitor import MonitorApp ,with_aggregate_rate 619except ImportError : 620MonitorApp = None 621 622 623@ unittest . skipIf ( MonitorApp is None , "optional Textual dependency absent" ) 624class HeadlessMonitorTests (unittest .TestCase ): 625def test_live_monitor_marks_activity_gaps_after_freeze_and_resets_on_restart (self ): 626from rich .console import Console 627 628def snapshot (instance ,last ,seqs ): 629value = four_gpu_snapshot () 630value ["sampled_at" ]= time .time () 631value ["instance" ]["id" ]= instance 632value ["activity" ]= {"available" :True ,"last_seq" :last ,"events" : [ 633 {"seq" :seq ,"at" :value ["sampled_at" ],"request_id" :f" { seq :012x } " , 634"event" :"queued" ,"outcome" :None }for seq in seqs ]} 635return value 636 637class Source : 638root = "http://127.0.0.1:8095" 639 640def snapshot (self ): 641return self .snapshots .pop (0 ) 642 643Source .snapshots = [snapshot ("a" ,5 , [2 ,4 ,5 ]),snapshot ("b" ,2 , [1 ,2 ])] 644 645async def exercise (): 646app = MonitorApp (Source (),snapshot ("a" ,2 , [1 ,2 ]),interval = 30 ) 647async with app .run_test (size = (80 ,24 ))as pilot : 648app .view = 5 649app .action_freeze () 650app ._schedule_poll (force = True ) 651await pilot .pause (0.1 ) 652self .assertIsNone (app .displayed_activity_continuity ["gap" ]) 653app .action_freeze () 654await pilot .pause () 655self .assertEqual (app .displayed_activity_continuity ["gap" ], 656 {"from_seq" :3 ,"to_seq" :3 }) 657shown = str (app .query_one ("#content" ).render ()) 658self .assertIn ("Missed activity #3-3" ,shown ) 659app .view = 0 660app ._paint () 661await pilot .pause () 662output = io .StringIO () 663Console (file = output ,width = 80 ,color_system = None ).app .query_one ("#content" ).content ) 664self .assertIn ("Missed activity #3-3" ,output .getvalue ()) 665app ._schedule_poll (force = True ) 666await pilot .pause (0.1 ) 667self .assertIsNone (app .displayed_activity_continuity ["gap" ]) 668self .assertTrue (app .displayed_activity_continuity ["restarted" ]) 669app .view = 5 670app ._paint () 671await pilot .pause () 672self .assertIn ("Serving restarted" ,str (app .query_one ("#content" ).render ())) 673await pilot .press ("q" ) 674 675asyncio .run (exercise ()) 676 677def test_live_compact_screen_replaces_cached_work_on_disconnect (self ): 678from rich .console import Console 679 680sample = four_gpu_snapshot () 681sample ["sampled_at" ]= time .time () 682sample ["model" ]["id" ]= "cached-model" 683sample ["work" ]["requests" ]= [{"id" :"cached-request" ,"state" :"decoding" ,"slot" :0 }] 684 685class Source : 686root = "http://127.0.0.1:8095" 687 688def snapshot (self ): 689return sample 690 691async def exercise (width ,height ,view ): 692app = MonitorApp (Source (),sample ,interval = 30 ) 693async with app .run_test (size = (width ,height ))as pilot : 694app .view = view 695app .connection_state = "disconnected" 696app ._paint () 697await pilot .pause (0.05 ) 698output = io .StringIO () 699Console (file = output ,width = width ,color_system = None ).app .query_one ("#content" ).content ) 700shown = output .getvalue () 701self .assertIn ("CONNECTION LOST" ,shown ) 702self .assertNotIn ("cached-model" ,shown ) 703self .assertNotIn ("cached-request" ,shown ) 704self .assertNotIn ("GPU-0" ,shown ) 705await pilot .press ("q" ) 706 707asyncio .run (exercise (40 ,12 ,0 )) 708asyncio .run (exercise (80 ,24 ,1 )) 709 710def test_overview_uses_selected_cards_and_marks_missing_sensors (self ): 711from rich .console import Console 712from strata_cli .dashboard import MonitorHistory ,render_dashboard 713 714sample = four_gpu_snapshot () 715sample ["sampled_at" ]= time .time () 716sample ["topology" ]["selected_devices" ]= [2 ,0 ,3 ,1 ,2 ,- 1 ,1.5 ,True ] 717extra = {** sample ["devices" ][0 ],"index" :5 ,"name" :"unselected GPU" } 718sample ["devices" ]= [extra ,sample ["devices" ][1 ],sample ["devices" ][2 ],sample ["devices" ][0 ]] 719sample = sanitize_telemetry (sample ) 720self .assertEqual (sample ["topology" ]["selected_devices" ], [2 ,0 ,3 ,1 ]) 721history = MonitorHistory () 722complete = four_gpu_snapshot () 723history .add (complete , ("id" ,"selected-cards" )) 724history .add (sample , ("id" ,"selected-cards" )) 725self .assertEqual (list (history .device_util [3 ]), [complete ["devices" ][3 ]["util" ],None ]) 726self .assertEqual (list (history .device_vram [3 ]), [50.0 ,None ]) 727self .assertNotIn (5 ,history .device_util ) 728self .assertNotIn (5 ,history .device_vram ) 729for width ,height in ((110 ,30 ), (80 ,24 )): 730with self .subTest (width = width ): 731output = io .StringIO () 732Console (file = output ,width = width ,color_system = None ).render_dashboard ( 733sample ,width = width - 2 ,height = height - 2 ,history = history , 734color = False )) 735shown = output .getvalue () 736positions = [shown .index (f"GPU { index } " )for index in (2 ,0 ,3 ,1 )] 737self .assertEqual (positions ,sorted (positions )) 738self .assertRegex (shown ,r"GPU 3[^\n]*--/--G" ) 739if width == 80 : 740self .assertRegex (shown ,r"GPU 3[^\n]*--/--G[^\n]*--\s+--" ) 741self .assertNotIn ("vram" ,shown ) 742else : 743self .assertRegex (shown ,r"GPU 2[^\n]*vram [^\s-]+" ) 744self .assertRegex (shown ,r"GPU 3[^\n]*vram --" ) 745self .assertNotIn ("GPU 5" ,shown ) 746self .assertEqual (len (shown .splitlines ()),height - 1 ) 747 748duplicate = {** sample ,"devices" :sample ["devices" ]+ [dict (sample ["devices" ][- 1 ])]} 749history .add (duplicate , ("id" ,"selected-cards" )) 750self .assertIsNone (history .device_util [0 ][- 1 ]) 751self .assertIsNone (history .device_vram [0 ][- 1 ]) 752output = io .StringIO () 753Console (file = output ,width = 80 ,color_system = None ).render_dashboard ( 754duplicate ,width = 78 ,height = 22 ,history = history ,color = False )) 755self .assertRegex (output .getvalue (),r"GPU 0[^\n]*--/--G" ) 756self .assertRegex (output .getvalue (),r"GPU 0[^\n]*--/--G[^\n]*--\s+--" ) 757 758def test_monitor_history_bounds_device_indices_across_snapshots (self ): 759from strata_cli .dashboard import MonitorHistory ,_output_trend 760 761history = MonitorHistory () 762for start in (0 ,16 ,32 ): 763history .add ({"devices" : [{"index" :index ,"util" :20 } 764for index in range (start ,start + 16 )], 765"rates" : {"aggregate_output_tok_s" :42.0 }}, ("id" ,"same" )) 766self .assertEqual (set (history .device_util ),set (range (start ,start + 16 ))) 767self .assertEqual (set (history .device_vram ),set (range (start ,start + 16 ))) 768history .add ({"devices" : [{"index" :32 ,"util" :40 }]}, ("id" ,"same" )) 769self .assertEqual (set (history .device_util ), {32 }) 770self .assertEqual (set (history .device_vram ), {32 }) 771self .assertIsNone (history .device_vram [32 ][- 1 ]) 772self .assertEqual (list (history .output_rate )[- 1 ],None ) 773self .assertEqual (_output_trend (history .output_rate ,"ascii" ,False ),"Output trend --" ) 774 775def test_vram_history_is_per_card_and_missing_values_are_not_zero (self ): 776from rich .console import Console 777from strata_cli .dashboard import MonitorHistory ,render_dashboard 778 779sample = four_gpu_snapshot () 780sample ["sampled_at" ]= time .time () 781sample ["devices" ][0 ]["mem_used" ]= 6 * 2 ** 30 782sample ["devices" ][1 ]["mem_used" ]= 18 * 2 ** 30 783history = MonitorHistory () 784history .add (sample , ("id" ,"memory-samples" )) 785self .assertEqual (history .device_vram [0 ][- 1 ],25.0 ) 786self .assertEqual (history .device_vram [1 ][- 1 ],75.0 ) 787output = io .StringIO () 788Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 789sample ,width = 108 ,height = 28 ,history = history ,glyphs = "ascii" ,color = False )) 790self .assertRegex (output .getvalue (),r"GPU 0[^\n]*vram :" ) 791self .assertRegex (output .getvalue (),r"GPU 1[^\n]*vram \*" ) 792 793sample ["devices" ][0 ]["mem_total" ]= 0 794sample ["devices" ][1 ]["mem_used" ]= 30 * 2 ** 30 795history .add (sample , ("id" ,"memory-samples" )) 796self .assertIsNone (history .device_vram [0 ][- 1 ]) 797self .assertIsNone (history .device_vram [1 ][- 1 ]) 798history .gap () 799self .assertIsNone (history .device_vram [0 ][- 1 ]) 800history .add (sample , ("id" ,"new-instance" )) 801self .assertEqual (len (history .device_vram [0 ]),1 ) 802self .assertIsNone (history .device_vram [0 ][- 1 ]) 803 804sample ["devices" ][0 ]["mem_used" ]= 1e308 805sample ["devices" ][0 ]["mem_total" ]= 1e308 806history .add (sample , ("id" ,"new-instance" )) 807self .assertEqual (history .device_vram [0 ][- 1 ],100.0 ) 808output = io .StringIO () 809Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 810sample ,width = 108 ,height = 28 ,history = history ,glyphs = "ascii" ,color = False )) 811self .assertRegex (output .getvalue (),r"GPU 0[^\n]*vram\s+@" ) 812 813def test_overview_output_trend_is_bounded_and_resets_with_instance (self ): 814from rich .console import Console 815from strata_cli .dashboard import MonitorHistory ,_output_trend ,render_dashboard 816 817sample = four_gpu_snapshot () 818sample ["sampled_at" ]= time .time () 819history = MonitorHistory () 820for value in (100.0 ,120.0 ,110.0 ): 821sample ["rates" ]["aggregate_output_tok_s" ]= value 822history .add (sample , ("id" ,"first" )) 823for width ,height in ((110 ,30 ), (80 ,24 ), (110 ,42 )): 824with self .subTest (width = width ): 825output = io .StringIO () 826Console (file = output ,width = width ,color_system = None ).render_dashboard ( 827sample ,width = width - 2 ,height = height - 2 ,history = history , 828glyphs = "ascii" ,color = False )) 829shown = output .getvalue () 830self .assertIn ("100-120 tok/s" ,shown ) 831self .assertLessEqual (len (shown .splitlines ()),height - 1 ) 832self .assertTrue (all (display_width (line )<= width for line in shown .splitlines ())) 833 834stale = {** sample ,"sampled_at" :time .time ()- 6 } 835output = io .StringIO () 836Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 837stale ,width = 108 ,height = 28 ,history = history ,glyphs = "ascii" ,color = False )) 838self .assertIn ("Output trend --" ,output .getvalue ()) 839self .assertNotIn ("100-120 tok/s" ,output .getvalue ()) 840 841sample ["rates" ]["aggregate_output_tok_s" ]= None 842history .add (sample , ("id" ,"first" )) 843self .assertEqual (_output_trend (history .output_rate ,"ascii" ,False ),"Output trend --" ) 844sample ["rates" ]["aggregate_output_tok_s" ]= 90.0 845history .add (sample , ("id" ,"second" )) 846self .assertEqual (list (history .output_rate ), [90.0 ]) 847self .assertIn ("▁▁ 0 tok/s" ,_output_trend ([0.0 ,0.0 ],"unicode" ,True )) 848 849def test_batch_and_queue_histories_keep_replica_windows_separate (self ): 850from rich .console import Console 851from strata_cli .dashboard import MonitorHistory ,render_dashboard 852 853sample = four_gpu_snapshot () 854sample ["sampled_at" ]= time .time () 855history = MonitorHistory (limit = 3 ) 856for rows ,queued in ((4.0 ,1 ), (6.0 ,5 )): 857sample ["work" ].update (effective_rows_window = rows ,batch_sample_age_s = 0.5 , 858queued = queued ) 859history .add (sample , ("id" ,"one" )) 860output = io .StringIO () 861Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 862sample ,width = 108 ,height = 28 ,history = history ,glyphs = "ascii" ,color = False )) 863shown = output .getvalue () 864self .assertIn ("Rows trend" ,shown ) 865self .assertIn ("4.0-6.0/win" ,shown ) 866self .assertIn ("Pre-admit" ,shown ) 867self .assertIn ("1-5 req" ,shown ) 868self .assertEqual (len (shown .splitlines ()),29 ) 869compact = io .StringIO () 870Console (file = compact ,width = 80 ,color_system = None ).render_dashboard ( 871sample ,width = 78 ,height = 22 ,history = history ,glyphs = "ascii" ,color = False )) 872self .assertNotIn ("Rows trend" ,compact .getvalue ()) 873self .assertIn ("1 Over" ,compact .getvalue ()) 874history .gap () 875self .assertIsNone (history .batch_rows [- 1 ]) 876self .assertIsNone (history .pre_admit [- 1 ]) 877self .assertIsNone (history .device_util [0 ][- 1 ]) 878after_gap = io .StringIO () 879Console (file = after_gap ,width = 110 ,color_system = None ).render_dashboard ( 880sample ,width = 108 ,height = 28 ,history = history ,glyphs = "ascii" ,color = False )) 881self .assertNotIn ("Rows trend" ,after_gap .getvalue ()) 882self .assertNotIn ("Pre-admit " ,after_gap .getvalue ()) 883 884sample ["work" ]["batch_sample_age_s" ]= 5.1 885history .add (sample , ("id" ,"one" )) 886old_single = io .StringIO () 887Console (file = old_single ,width = 110 ,color_system = None ).render_dashboard ( 888sample ,width = 108 ,height = 28 ,history = history ,glyphs = "ascii" ,color = False )) 889self .assertIsNone (history .batch_rows [- 1 ]) 890self .assertIn ("Rows/win -- processed" ,old_single .getvalue ()) 891self .assertNotIn ("Rows trend" ,old_single .getvalue ()) 892 893replica = copy .deepcopy (sample ) 894replica ["topology" ]["mode" ]= "replicas (configured)" 895replica ["topology" ]["replica_devices" ]= [{"replica" :0 ,"devices" : [0 ,1 ]}, 896 {"replica" :1 ,"devices" : [2 ,3 ]}] 897replica ["work" ]["effective_rows_window" ]= None 898for first ,second in ((4.0 ,3.0 ), (5.0 ,4.0 )): 899replica ["work" ]["replica_batches" ]= [ 900 {"replica" :0 ,"effective_rows_window" :first ,"batch_active_rows_window" :2.0 , 901"batch_sample_age_s" :0.5 }, 902 {"replica" :1 ,"effective_rows_window" :second ,"batch_active_rows_window" :2.0 , 903"batch_sample_age_s" :0.5 }] 904history .add (replica , ("id" ,"two" )) 905output = io .StringIO () 906Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 907replica ,width = 108 ,height = 28 ,history = history ,glyphs = "ascii" ,color = False )) 908shown = output .getvalue () 909self .assertIn ("R0 rows" ,shown ) 910self .assertIn ("4.0-5.0/win" ,shown ) 911self .assertIn ("R1 rows" ,shown ) 912self .assertIn ("3.0-4.0/win" ,shown ) 913self .assertNotIn ("Rows trend" ,shown ) 914 915replica ["work" ]["replica_batches" ][1 ]["batch_sample_age_s" ]= 5.1 916history .add (replica , ("id" ,"two" )) 917self .assertIsNone (history .replica_batch_rows [1 ][- 1 ]) 918old_sample = io .StringIO () 919Console (file = old_sample ,width = 110 ,color_system = None ).render_dashboard ( 920replica ,width = 108 ,height = 28 ,history = history ,glyphs = "ascii" ,color = False )) 921self .assertIn ("R1 --/--" ,old_sample .getvalue ()) 922self .assertNotIn ("R1 rows" ,old_sample .getvalue ()) 923 924replica ["work" ]["replica_batches" ]= [replica ["work" ]["replica_batches" ][0 ]] 925history .add (replica , ("id" ,"two" )) 926self .assertIsNone (history .replica_batch_rows [1 ][- 1 ]) 927self .assertEqual (len (history .replica_batch_rows [0 ]),3 ) 928history .add (replica , ("id" ,"three" )) 929self .assertEqual (len (history .batch_rows ),1 ) 930self .assertEqual (len (history .replica_batch_rows [0 ]),1 ) 931 932def test_overview_slot_phases_require_complete_slot_report (self ): 933from rich .console import Console 934from strata_cli .dashboard import MonitorHistory ,render_dashboard 935 936sample = four_gpu_snapshot () 937sample ["sampled_at" ]= time .time () 938sample ["work" ]["slots" ][0 ]["state" ]= "reading" 939self .assertIn ("Occupied slots by group G0 2/2" ,render_view (sample ,"serving" ,110 ,30 )) 940for width ,height in ((110 ,30 ), (80 ,24 )): 941with self .subTest (width = width ): 942output = io .StringIO () 943Console (file = output ,width = width ,color_system = None ).render_dashboard ( 944sample ,width = width - 2 ,height = height - 2 ,history = MonitorHistory (), 945color = False )) 946shown = output .getvalue () 947self .assertIn ("read 1 decode 5 idle 2" ,shown ) 948self .assertLessEqual (len (shown .splitlines ()),height - 1 ) 949self .assertTrue (all (display_width (line )<= width for line in shown .splitlines ())) 950 951incomplete = dict (sample ["work" ]) 952incomplete ["slots" ]= incomplete ["slots" ][:- 1 ] 953output = io .StringIO () 954Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 955 {** sample ,"work" :incomplete },width = 108 ,height = 28 ,history = MonitorHistory (),color = False )) 956self .assertNotIn ("Slot phases" ,output .getvalue ()) 957self .assertIn ("Group occupancy --" ,output .getvalue ()) 958self .assertIn ("Occupied slots by group -- (slot report incomplete)" , 959render_view ({** sample ,"work" :incomplete },"serving" ,110 ,30 )) 960 961duplicated = dict (sample ["work" ]) 962duplicated ["slots" ]= [dict (row )for row in sample ["work" ]["slots" ]] 963duplicated ["slots" ][1 ]["slot" ]= duplicated ["slots" ][0 ]["slot" ] 964output = io .StringIO () 965Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 966 {** sample ,"work" :duplicated },width = 108 ,height = 28 ,history = MonitorHistory (),color = False )) 967self .assertNotIn ("Slot phases" ,output .getvalue ()) 968self .assertIn ("Group occupancy --" ,output .getvalue ()) 969 970invalid_group = dict (sample ["work" ]) 971invalid_group ["slots" ]= [dict (row )for row in sample ["work" ]["slots" ]] 972invalid_group ["slots" ][1 ]["group" ]= None 973output = io .StringIO () 974Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 975 {** sample ,"work" :invalid_group },width = 108 ,height = 28 ,history = MonitorHistory (),color = False )) 976self .assertIn ("Slot phases" ,output .getvalue ()) 977self .assertIn ("Group occupancy --" ,output .getvalue ()) 978 979invalid_group ["slots" ][1 ]["group" ]= 9 980self .assertIn ("Occupied slots by group -- (slot report incomplete)" , 981render_view ({** sample ,"work" :invalid_group },"serving" ,110 ,30 )) 982invalid_group ["slots" ][1 ]["group" ]= 0 983invalid_group ["slots" ][1 ]["slot" ]= 99 984output = io .StringIO () 985Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 986 {** sample ,"work" :invalid_group },width = 108 ,height = 28 ,history = MonitorHistory (),color = False )) 987self .assertNotIn ("Slot phases" ,output .getvalue ()) 988self .assertIn ("Group occupancy --" ,output .getvalue ()) 989 990def test_connection_panel_hides_cached_work_until_recovery (self ): 991from rich .console import Console 992from strata_cli .dashboard import MonitorHistory ,render_dashboard 993 994sample = four_gpu_snapshot () 995sample ["sampled_at" ]= time .time ()- 4 996sample ["rates" ]["answer_tok_s" ]= 42.5 997sample ["work" ]["requests" ]= [{"id" :"cached-request" ,"state" :"decoding" ,"slot" :0 }] 998expected = {"connecting" :"CONNECTING" ,"disconnected" :"CONNECTION LOST" , 999"auth_required" :"AUTHORIZATION REQUIRED" ,"incompatible" :"INCOMPATIBLE SERVER" } 1000for width ,height in ((110 ,30 ), (80 ,24 )): 1001for state ,title in expected .items (): 1002with self .subTest (width = width ,state = state ): 1003output = io .StringIO () 1004Console (file = output ,width = width ,color_system = None ).render_dashboard ( 1005sample ,width = width - 2 ,height = height - 2 ,history = MonitorHistory (), 1006connection_state = state ,color = False )) 1007shown = output .getvalue () 1008self .assertIn (title ,shown ) 1009self .assertNotIn ("cached-request" ,shown ) 1010self .assertNotIn ("42.5 tok/s" ,shown ) 1011self .assertNotIn ("GPU 0" ,shown ) 1012self .assertLessEqual (len (shown .splitlines ()),height - 1 ) 1013self .assertTrue (all (display_width (line )<= width for line in shown .splitlines ())) 1014 1015def test_compact_connection_panel_hides_cached_work_across_views (self ): 1016sample = four_gpu_snapshot () 1017sample ["sampled_at" ]= time .time ()- 4 1018sample ["model" ]["id" ]= "cached-model" 1019sample ["rates" ]["answer_tok_s" ]= 42.5 1020sample ["work" ]["requests" ]= [{"id" :"cached-request" ,"state" :"decoding" ,"slot" :0 }] 1021titles = {"connecting" :"CONNECTING" ,"disconnected" :"CONNECTION LOST" , 1022"auth_required" :"AUTHORIZATION REQUIRED" ,"incompatible" :"INCOMPATIBLE SERVER" } 1023for width ,height in ((80 ,24 ), (60 ,16 ), (40 ,12 )): 1024for view in ("overview" ,"serving" ,"requests" ,"engine" ,"hardware" ,"logs" ): 1025for state ,title in titles .items (): 1026with self .subTest (width = width ,view = view ,state = state ): 1027shown = render_view (sample ,view ,width ,height ,connection_state = state ) 1028self .assertIn (title ,shown ) 1029for cached in ("cached-model" ,"cached-request" ,"42.5 tok/s" ,"GPU-0" ): 1030self .assertNotIn (cached ,shown ) 1031self .assertLessEqual (len (shown .splitlines ()),height ) 1032self .assertTrue (all (display_width (line )<= width for line in shown .splitlines ())) 1033 1034def test_overview_dashboard_keeps_parallel_work_and_four_devices_on_one_screen (self ): 1035from rich .console import Console 1036from strata_cli .dashboard import MonitorHistory ,_spark ,render_dashboard 1037from strata_cli .monitor import choose_glyphs 1038 1039self .assertEqual (choose_glyphs ("auto" ,"utf-8" ,"xterm-256color" ),"unicode" ) 1040self .assertEqual (choose_glyphs ("auto" ,"ascii" ,"xterm-256color" ),"ascii" ) 1041self .assertEqual (choose_glyphs ("auto" ,"utf-8" ,"dumb" ),"ascii" ) 1042self .assertEqual (choose_glyphs ("braille" ,"ascii" ,"dumb" ),"braille" ) 1043 1044sample = four_gpu_snapshot () 1045sample ["sampled_at" ]= time .time () 1046sample ["instance" ]["id" ]= "fixture-instance" 1047sample ["rates" ].update (answer_tok_s = 42.5 ,prefill_tok_s = 180.0 , 1048aggregate_output_tok_s = 126.0 ) 1049sample ["work" ].update (effective_rows_window = 5.0 ,batch_active_rows_window = 3.0 , 1050batch_sample_age_s = 0.5 , 1051requests = [{"id" :"queued-1" ,"state" :"queued" ,"slot" :None , 1052"group" :None ,"queued_at" :sample ["sampled_at" ]- 2 }, 1053 {"id" :"running-1" ,"state" :"decoding" ,"slot" :0 , 1054"group" :0 ,"generated" :18 }]) 1055sample ["activity" ]= {"available" :True ,"events" : [ 1056 {"seq" :1 ,"at" :sample ["sampled_at" ],"request_id" :"running-1" ,"event" :"admitted" }]} 1057history = MonitorHistory () 1058history .add (sample , ("id" ,"fixture-instance" )) 1059for width ,height in ((110 ,30 ), (80 ,24 ), (110 ,42 )): 1060with self .subTest (width = width ): 1061output = io .StringIO () 1062Console (file = output ,width = width ,color_system = None ).render_dashboard ( 1063sample ,width = width - 2 ,height = height - 2 ,history = history , 1064connection_state = "connected" ,glyphs = "ascii" ,color = False )) 1065shown = output .getvalue () 1066self .assertLessEqual (len (shown .splitlines ()),height - 1 ) 1067self .assertTrue (all (display_width (line )<= width for line in shown .splitlines ())) 1068for expected in ("BATCHING / PARALLEL" ,"HARDWARE" ,"REQUESTS" ,"ACTIVITY" , 1069"5.0" ,"queued-1" ,"GPU 0" ,"GPU 1" ,"GPU 2" ,"GPU 3" , 1070"G0" ,"G3" ,"42.5 tok/s" ): 1071self .assertIn (expected ,shown ) 1072if width == 110 : 1073self .assertIn ("Stage host span" ,shown ) 1074if height == 42 : 1075self .assertIn ("SESSION" ,shown ) 1076self .assertIn ("ENGINE" ,shown ) 1077if width == 80 : 1078self .assertIn ("1 Over" ,shown ) 1079self .assertRegex (shown ,r"queued-1[^\n]*wait" ) 1080self .assertNotRegex (shown ,r"queued-1[^\n]*out" ) 1081 1082history .add ({"devices" : [{"index" :0 ,"util" :90 }]}, ("id" ,"restarted" )) 1083self .assertEqual (list (history .device_util [0 ]), [90 ]) 1084self .assertNotIn (1 ,history .device_util ) 1085self .assertTrue (all ("\u2800" <= char <= "\u28ff" for char in _spark ([25 ,75 ,50 ,100 ],"braille" ))) 1086self .assertEqual (_spark ([None ,None ],"braille" ),"--" ) 1087self .assertEqual (len (_spark ([25 ,75 ,50 ,100 ],"unicode" )),4 ) 1088sample ["devices" ][0 ]["name" ]= "漢字 RTX 6000" 1089sample ["work" ]["requests" ][0 ]["id" ]= "\x1b[2J漢字-queued\u202e" 1090sample ["work" ]["slots" ][0 ]["state" ]= None 1091output = io .StringIO () 1092Console (file = output ,width = 80 ,color_system = None ).render_dashboard ( 1093sample ,width = 78 ,height = 22 ,history = history ,color = False )) 1094self .assertIn ("Group occupancy --" ,output .getvalue ()) 1095self .assertNotIn ("\x1b" ,output .getvalue ()) 1096self .assertNotIn ("\u202e" ,output .getvalue ()) 1097self .assertTrue (all (display_width (line )<= 80 for line in output .getvalue ().splitlines ())) 1098 1099sample ["work" ]["requests" ].append ({"id" :"reading-1" ,"state" :"reading" ,"slot" :2 , 1100"group" :1 ,"prompt_read" :250 ,"prompt_tokens" :1000 }) 1101output = io .StringIO () 1102Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 1103sample ,width = 108 ,height = 28 ,history = history ,glyphs = "unicode" ,color = False )) 1104self .assertIn ("Reading reading-1" ,output .getvalue ()) 1105self .assertIn ("250/1,000" ,output .getvalue ()) 1106self .assertTrue (all (display_width (line )<= 110 for line in output .getvalue ().splitlines ())) 1107 1108sample ["model" ]["loaded" ]= False 1109output = io .StringIO () 1110Console (file = output ,width = 110 ,color_system = None ).render_dashboard ( 1111sample ,width = 108 ,height = 28 ,history = history ,glyphs = "unicode" ,color = False )) 1112self .assertIn ("SLEEPING" ,output .getvalue ()) 1113self .assertNotIn ("42.5 tok/s" ,output .getvalue ()) 1114 1115def test_wide_visual_overview_uses_real_rates_slots_and_request_rows (self ): 1116from rich .console import Console 1117from strata_cli .dashboard import MonitorHistory ,render_dashboard 1118 1119sample = four_gpu_snapshot () 1120sample ["sampled_at" ]= time .time () 1121sample ["model" ]["context" ]= 32768 1122sample ["rates" ].update (answer_tok_s = 41.8 ,prefill_tok_s = 188.6 , 1123aggregate_output_tok_s = 119.4 ) 1124sample ["work" ].update (slots_effective = 8 ,queued = 2 ,effective_rows_window = 4.0 , 1125batch_active_rows_window = 3.0 ,batch_sample_age_s = 0.5 , 1126requests = [{"id" :"queue-a" ,"state" :"queued" ,"slot" :None , 1127"prompt_tokens" :500 ,"queued_at" :sample ["sampled_at" ]- 2 }, 1128 {"id" :"decode-b" ,"state" :"decoding" ,"slot" :0 , 1129"group" :0 ,"prompt_tokens" :200 ,"generated" :37 , 1130"first_engine_token_s" :0.71 }]) 1131sample ["work" ]["slots" ][0 ]["held_tokens" ]= 1200 1132history = MonitorHistory () 1133history .add (sample , ("id" ,"visual-fixture" )) 1134history .add (sample , ("id" ,"visual-fixture" )) 1135for width ,height in ((140 ,44 ), (128 ,36 )): 1136with self .subTest (width = width ,height = height ): 1137output = io .StringIO () 1138Console (file = output ,width = width ,color_system = None ).render_dashboard ( 1139sample ,width = width - 2 ,height = height - 2 ,history = history , 1140connection_state = "connected" ,glyphs = "ascii" ,color = False )) 1141shown = output .getvalue () 1142self .assertLessEqual (len (shown .splitlines ()),height - 1 ) 1143self .assertTrue (all (display_width (line )<= width for line in shown .splitlines ())) 1144for expected in ("THROUGHPUT" ,"PROMPT 188.6 tok/s" ,"119.4 tok/s" , 1145"GPUS" ,"GPU 0" ,"GPU 3" ,"CONTEXT / BATCHING" , 1146"MAX ACTIVE HELD 1,200" ,"PARALLEL SLOTS" ,"G0" , 1147"REQUESTS" ,"queue-a" ,"decode-b" ,"wait 2.0s" , 1148"1ST ENGINE" ): 1149self .assertIn (expected ,shown ) 1150self .assertNotIn ("cached 0" ,shown ) 1151history .gap () 1152self .assertIsNone (history .prefill_rate [- 1 ]) 1153self .assertIsNone (history .answer_rate [- 1 ]) 1154stale_output = io .StringIO () 1155Console (file = stale_output ,width = 140 ,color_system = None ).render_dashboard ( 1156sample ,width = 138 ,height = 42 ,history = history , 1157connection_state = "stale" ,glyphs = "ascii" ,color = False )) 1158self .assertIn ("MAX ACTIVE HELD --" ,stale_output .getvalue ()) 1159self .assertIn ("PROMPT -- tok/s" ,stale_output .getvalue ()) 1160self .assertNotIn ("119.4 tok/s" ,stale_output .getvalue ()) 1161idle = copy .deepcopy (sample ) 1162idle ["work" ].update (active = 0 ,queued = 0 ,waiting = 0 ,occupied_slots = 0 ,requests = []) 1163for slot in idle ["work" ]["slots" ]: 1164slot ["state" ]= "idle" 1165idle_output = io .StringIO () 1166Console (file = idle_output ,width = 140 ,color_system = None ).render_dashboard ( 1167idle ,width = 138 ,height = 42 ,history = history , 1168connection_state = "connected" ,glyphs = "ascii" ,color = False )) 1169self .assertIn ("MAX ACTIVE HELD 0" ,idle_output .getvalue ()) 1170self .assertIn ("No active requests" ,idle_output .getvalue ()) 1171 1172def test_initial_attach_keeps_status_when_telemetry_is_unavailable (self ): 1173status_only = sanitize_telemetry (normalize_status_only ( 1174 {"service" :"strata" ,"model" :"fixture" ,"loaded" :False , 1175"concurrency" : {"serving" :4 }})) 1176 1177class Source : 1178root = "http://127.0.0.1:8095" 1179 1180def snapshot (self ): 1181return status_only 1182 1183async def exercise (): 1184app = MonitorApp (Source (),None ,interval = 30 ) 1185async with app .run_test (size = (80 ,24 ))as pilot : 1186await pilot .pause (0.1 ) 1187self .assertEqual (app .connection_state ,"telemetry_unavailable" ) 1188self .assertTrue (app .has_snapshot ) 1189self .assertEqual (app .displayed ["model" ]["id" ],"fixture" ) 1190from rich .console import Console 1191output = io .StringIO () 1192console = Console (file = output ,width = 80 ,color_system = None ) 1193console .app .query_one ("#content" ).content ) 1194self .assertIn ("Telemetry unavailable; status only" ,output .getvalue ()) 1195self .assertIn ("NO MODEL LOADED" ,output .getvalue ()) 1196await pilot .press ("q" ) 1197asyncio .run (exercise ()) 1198 1199def test_stale_snapshot_hides_live_rates_without_changing_cached_values (self ): 1200sample = four_gpu_snapshot () 1201sample ["sampled_at" ]= time .time () 1202sample ["rates" ].update (answer_tok_s = 12 ,prefill_tok_s = 24 ,aggregate_output_tok_s = 36 ) 1203live = render_view (sample ,"overview" ,80 ,24 ,connection_state = "connected" ) 1204stale = render_view (sample ,"overview" ,80 ,24 ,connection_state = "stale" ) 1205serving = render_view (sample ,"serving" ,110 ,30 ,connection_state = "stale" ) 1206self .assertIn ("[LIVE]" ,live ) 1207self .assertIn ("Answer speed 12.0 tok/s" ,live ) 1208self .assertIn ("[STALE]" ,stale ) 1209self .assertIn ("Answer speed --" ,stale ) 1210self .assertIn ("Prompt reading --" ,stale ) 1211self .assertIn ("Total output --" ,serving ) 1212self .assertEqual (sample ["rates" ]["answer_tok_s" ],12 ) 1213self .assertIn ("[STALE]" ,render_view ({** sample ,"sampled_at" :time .time ()- 10 }, 1214"overview" ,80 ,24 ,connection_state = "connected" )) 1215 1216def test_failed_poll_marks_stale_immediately_then_recovers (self ): 1217initial = four_gpu_snapshot () 1218initial ["sampled_at" ]= time .time () 1219initial ["rates" ]["answer_tok_s" ]= 12 1220initial ["rates" ]["output_tokens_server_counter" ]= 100 1221initial ["instance" ]["id" ]= "same-instance" 1222sample_time = initial ["sampled_at" ] 1223 1224class Source : 1225root = "http://127.0.0.1:8095" 1226calls = 0 1227 1228def snapshot (self ): 1229self .calls += 1 1230if self .calls <= 3 : 1231raise ClientError ("temporarily unavailable" ,3 ) 1232result = four_gpu_snapshot () 1233result ["instance" ]["id" ]= "same-instance" 1234result ["sampled_at" ]= sample_time + self .calls - 4 1235result ["rates" ]["output_tokens_server_counter" ]= 160 + 30 * (self .calls - 4 ) 1236return result 1237 1238async def exercise (): 1239from rich .console import Console 1240 1241source = Source () 1242app = MonitorApp (source ,initial ,interval = 30 ) 1243async with app .run_test (size = (80 ,24 ))as pilot : 1244for expected in ("stale" ,"stale" ,"disconnected" ,"connected" ): 1245app ._schedule_poll (force = True ) 1246await pilot .pause (0.1 ) 1247self .assertEqual (app .connection_state ,expected ) 1248output = io .StringIO () 1249Console (file = output ,width = 80 ,color_system = None ).app .query_one ("#content" ).content ) 1250if expected == "disconnected" : 1251self .assertIn ("CONNECTION LOST" ,output .getvalue ()) 1252self .assertNotIn ("GPU 0" ,output .getvalue ()) 1253if expected in ("stale" ,"disconnected" ): 1254self .assertIsNone (app .history .batch_rows [- 1 ]) 1255self .assertIsNone (app .history .pre_admit [- 1 ]) 1256self .assertIsNone (app .history .device_util [0 ][- 1 ]) 1257if expected == "connected" : 1258self .assertIn ("GPU 0" ,output .getvalue ()) 1259self .assertNotIn ("CONNECTION LOST" ,output .getvalue ()) 1260self .assertEqual (source .calls ,4 ) 1261self .assertEqual (app .failures ,0 ) 1262self .assertIsNone (app .latest ["rates" ]["aggregate_output_tok_s" ]) 1263app ._schedule_poll (force = True ) 1264await pilot .pause (0.1 ) 1265self .assertEqual (app .latest ["rates" ]["aggregate_output_tok_s" ],30 ) 1266await pilot .press ("q" ) 1267asyncio .run (exercise ()) 1268 1269def test_unexpected_poll_error_marks_snapshot_stale_without_leaking_details (self ): 1270initial = four_gpu_snapshot () 1271initial ["sampled_at" ]= time .time () 1272 1273class Source : 1274root = "http://127.0.0.1:8095" 1275 1276def snapshot (self ): 1277raise RuntimeError ("private URL and credential" ) 1278 1279async def exercise (): 1280app = MonitorApp (Source (),initial ,interval = 30 ) 1281async with app .run_test (size = (80 ,24 ))as pilot : 1282app ._schedule_poll (force = True ) 1283await pilot .pause (0.1 ) 1284self .assertEqual (app .connection_state ,"stale" ) 1285self .assertEqual (app .error ,"Telemetry collection failed" ) 1286self .assertIsNone (app .rate_previous ) 1287self .assertNotIn ("private URL" ,str (app .query_one ("#message" ).render ())) 1288await pilot .press ("q" ) 1289asyncio .run (exercise ()) 1290 1291def test_initial_attach_shows_connecting_and_requires_manual_retry_after_auth (self ): 1292class Source : 1293root = "http://127.0.0.1:8095" 1294calls = 0 1295 1296def snapshot (self ): 1297self .calls += 1 1298if self .calls == 1 : 1299raise ClientError ("credential required" ,4 ) 1300if self .calls == 2 : 1301raise ClientError ("unsupported telemetry schema" ,5 ) 1302result = four_gpu_snapshot () 1303result ["sampled_at" ]= time .time () 1304return result 1305 1306async def exercise (): 1307source = Source () 1308app = MonitorApp (source ,None ,interval = 30 ) 1309self .assertEqual (app .connection_state ,"connecting" ) 1310async with app .run_test (size = (80 ,24 ))as pilot : 1311await pilot .pause (0.1 ) 1312self .assertEqual (app .connection_state ,"auth_required" ) 1313self .assertEqual (app .next_poll_at ,float ("inf" )) 1314self .assertFalse (app .has_snapshot ) 1315app ._schedule_poll () 1316await pilot .pause (0.1 ) 1317self .assertEqual (source .calls ,1 ) 1318app ._schedule_poll (force = True ) 1319await pilot .pause (0.1 ) 1320self .assertEqual (app .connection_state ,"incompatible" ) 1321self .assertEqual (app .next_poll_at ,float ("inf" )) 1322app ._schedule_poll (force = True ) 1323await pilot .pause (0.1 ) 1324self .assertEqual (app .connection_state ,"connected" ) 1325self .assertTrue (app .has_snapshot ) 1326self .assertIsNone (app .selection_notice ) 1327await pilot .press ("q" ) 1328asyncio .run (exercise ()) 1329 1330def test_restart_clears_matching_request_id_after_freeze (self ): 1331initial = four_gpu_snapshot () 1332initial ["instance" ]["id" ]= "server-old" 1333initial ["work" ]["requests" ]= [{"id" :"reused-id" ,"state" :"decoding" }] 1334initial ["recent" ]= [] 1335restarted = four_gpu_snapshot () 1336restarted ["instance" ]["id" ]= "server-new" 1337restarted ["work" ]["requests" ]= [{"id" :"reused-id" ,"state" :"queued" }] 1338restarted ["recent" ]= [] 1339 1340class Source : 1341root = "http://127.0.0.1:8095" 1342 1343def snapshot (self ): 1344return restarted 1345 1346async def exercise (): 1347app = MonitorApp (Source (),initial ,interval = 30 ) 1348async with app .run_test (size = (80 ,24 ))as pilot : 1349await pilot .press ("3" ,"enter" ,"space" ) 1350self .assertTrue (app .detail ) 1351app ._schedule_poll (force = True ) 1352await pilot .pause (0.1 ) 1353self .assertEqual (app .displayed ["instance" ]["id" ],"server-old" ) 1354self .assertTrue (app .detail ) 1355await pilot .press ("space" ) 1356self .assertEqual (app .displayed ["instance" ]["id" ],"server-new" ) 1357self .assertFalse (app .detail ) 1358self .assertIsNone (app .selected_identity ) 1359self .assertEqual (app .selection_notice ,"Server instance changed; selection cleared" ) 1360await pilot .press ("q" ) 1361asyncio .run (exercise ()) 1362 1363def test_table_keys_and_device_identity_survive_reorder (self ): 1364initial = four_gpu_snapshot () 1365initial ["work" ]["requests" ]= [{"id" :f"r { i :02d } " ,"state" :"queued" }for i in range (20 )] 1366initial ["recent" ]= [] 1367reordered = four_gpu_snapshot () 1368reordered ["devices" ].reverse () 1369disappeared = four_gpu_snapshot () 1370disappeared ["devices" ]= disappeared ["devices" ][:3 ] 1371 1372class Source : 1373root = "http://127.0.0.1:8095" 1374 1375def __init__ (self ): 1376self .values = [reordered ,disappeared ] 1377 1378def snapshot (self ): 1379return self .values .pop (0 ) 1380 1381async def exercise (): 1382app = MonitorApp (Source (),initial ,interval = 30 ,requests = 20 ) 1383async with app .run_test (size = (80 ,24 ))as pilot : 1384await pilot .press ("3" ,"end" ) 1385self .assertEqual (app .selected ,19 ) 1386await pilot .press ("pageup" ) 1387self .assertEqual (app .selected ,7 ) 1388await pilot .press ("home" ,"pagedown" ) 1389self .assertEqual (app .selected ,12 ) 1390await pilot .press ("right" ) 1391self .assertEqual (app .view ,3 ) 1392await pilot .press ("left" ,"5" ,"end" ,"enter" ) 1393self .assertEqual (app .selected_identity , ("device" ,"3" )) 1394self .assertTrue (app .detail ) 1395app ._schedule_poll (force = True ) 1396await pilot .pause (0.1 ) 1397self .assertEqual (app .selected ,0 ) 1398self .assertTrue (app .detail ) 1399self .assertIn ("GPU 3" ,str (app .query_one ("#content" ).render ())) 1400app ._schedule_poll (force = True ) 1401await pilot .pause (0.1 ) 1402self .assertFalse (app .detail ) 1403self .assertEqual (app .selection_notice ,"No longer retained; select another row" ) 1404await pilot .press ("q" ) 1405asyncio .run (exercise ()) 1406 1407def test_slot_detail_follows_slot_across_snapshot_reorder (self ): 1408initial = four_gpu_snapshot () 1409reordered = four_gpu_snapshot () 1410reordered ["work" ]["slots" ].reverse () 1411 1412class Source : 1413root = "http://127.0.0.1:8095" 1414 1415def snapshot (self ): 1416return reordered 1417 1418async def exercise (): 1419app = MonitorApp (Source (),initial ,interval = 30 ) 1420async with app .run_test (size = (80 ,24 ))as pilot : 1421await pilot .press ("2" ,"tab" ,"tab" ,"end" ,"enter" ) 1422self .assertEqual (app .selected_identity , ("slot" ,"7" )) 1423self .assertTrue (app .detail ) 1424app ._schedule_poll (force = True ) 1425await pilot .pause (0.1 ) 1426self .assertEqual (app .selected ,0 ) 1427self .assertTrue (app .detail ) 1428self .assertIn ("Slot 7" ,str (app .query_one ("#content" ).render ())) 1429await pilot .press ("q" ) 1430asyncio .run (exercise ()) 1431 1432def test_request_detail_follows_live_request_into_recent_history (self ): 1433value = four_gpu_snapshot () 1434value ["work" ]["requests" ]= [{"id" :"finishing-1" ,"state" :"decoding" }] 1435value ["recent" ]= [] 1436finished = four_gpu_snapshot () 1437finished ["work" ]["requests" ]= [] 1438finished ["recent" ]= [{"id" :"finishing-1" ,"finish" :"stop" ,"output_tokens" :9 }] 1439 1440class Source : 1441root = "http://127.0.0.1:8095" 1442 1443def snapshot (self ): 1444return finished 1445 1446async def exercise (): 1447app = MonitorApp (Source (),value ,interval = 30 ) 1448async with app .run_test (size = (80 ,24 ))as pilot : 1449await pilot .press ("3" ,"enter" ) 1450self .assertEqual (app .selected_identity , ("live" ,"finishing-1" )) 1451app ._schedule_poll (force = True ) 1452await pilot .pause (0.1 ) 1453self .assertEqual (app .selected_identity , ("recent" ,"finishing-1" )) 1454self .assertTrue (app .detail ) 1455self .assertIn ("RECENT REQUEST DETAIL" ,str (app .query_one ("#content" ).render ())) 1456await pilot .press ("q" ) 1457asyncio .run (exercise ()) 1458 1459def test_recent_detail_follows_identity_and_closes_when_it_disappears (self ): 1460def snapshot (recent_ids ): 1461value = four_gpu_snapshot () 1462value ["work" ]["requests" ]= [{"id" :"live-1" ,"state" :"decoding" }] 1463value ["recent" ]= [{"id" :item ,"finish" :"stop" ,"prompt_tokens" :100 , 1464"output_tokens" :2 ,"duration_s" :0.5 , 1465"first_engine_token_s" :0.2 }for item in recent_ids ] 1466value ["sampled_at" ]= time .time () 1467return value 1468 1469class Source : 1470root = "http://127.0.0.1:8095" 1471 1472def __init__ (self ): 1473self .values = [snapshot (["new-1" ,"done-1" ]),snapshot (["new-1" ])] 1474 1475def snapshot (self ): 1476return self .values .pop (0 ) 1477 1478async def exercise (): 1479app = MonitorApp (Source (),snapshot (["done-1" ]),interval = 30 ) 1480async with app .run_test (size = (80 ,24 ))as pilot : 1481await pilot .press ("3" ,"down" ,"enter" ) 1482await pilot .pause () 1483self .assertTrue (app .detail ) 1484self .assertEqual (app .selected_identity , ("recent" ,"done-1" )) 1485self .assertIn ("RECENT REQUEST DETAIL" ,str (app .query_one ("#content" ).render ())) 1486app ._schedule_poll (force = True ) 1487await pilot .pause (0.1 ) 1488self .assertEqual (app .selected ,2 ) 1489self .assertTrue (app .detail ) 1490self .assertIn ("done-1" ,str (app .query_one ("#content" ).render ())) 1491app ._schedule_poll (force = True ) 1492await pilot .pause (0.1 ) 1493self .assertFalse (app .detail ) 1494self .assertEqual (app .selection_notice ,"No longer retained; select another row" ) 1495await pilot .press ("q" ) 1496asyncio .run (exercise ()) 1497 1498def test_polling_has_one_in_flight_cycle_and_freeze_keeps_display (self ): 1499class Source : 1500root = "http://127.0.0.1:8095" 1501calls = 0 1502 1503def snapshot (self ): 1504self .calls += 1 1505time .sleep (0.1 ) 1506result = four_gpu_snapshot () 1507result ["sampled_at" ]= time .time () 1508return result 1509 1510async def exercise (): 1511source = Source () 1512initial = four_gpu_snapshot () 1513app = MonitorApp (source ,initial ,interval = 30 ) 1514async with app .run_test (size = (80 ,24 ))as pilot : 1515app .action_freeze () 1516app ._schedule_poll (force = True ) 1517app ._schedule_poll (force = True ) 1518await pilot .pause (0.2 ) 1519self .assertEqual (source .calls ,1 ) 1520self .assertIs (app .displayed ,initial ) 1521app .action_freeze () 1522self .assertIs (app .displayed ,app .latest ) 1523await pilot .press ("q" ) 1524asyncio .run (exercise ()) 1525 1526def test_aggregate_rate_uses_one_window_and_resets_on_restart (self ): 1527old = {"instance" : {"id" :"one" },"sampled_at" :10.0 , 1528"rates" : {"output_tokens_server_counter" :100 }} 1529fresh = {"instance" : {"id" :"one" },"sampled_at" :12.0 , 1530"rates" : {"output_tokens_server_counter" :160 }} 1531self .assertEqual (with_aggregate_rate (old ,fresh )["rates" ]["aggregate_output_tok_s" ],30 ) 1532restarted = {"instance" : {"id" :"two" },"sampled_at" :14.0 , 1533"rates" : {"output_tokens_server_counter" :3 }} 1534self .assertIsNone (with_aggregate_rate (fresh ,restarted )["rates" ]["aggregate_output_tok_s" ]) 1535invalid = {"instance" : {"id" :"one" },"sampled_at" :float ("inf" ), 1536"rates" : {"output_tokens_server_counter" :190 }} 1537self .assertIsNone (with_aggregate_rate (fresh ,invalid )["rates" ]["aggregate_output_tok_s" ]) 1538stale = {"instance" : {"id" :"one" },"sampled_at" :time .time ()- 10 , 1539"rates" : {"output_tokens_server_counter" :100 }} 1540self .assertIsNone (MonitorApp (Endpoint ("http://127.0.0.1:8080" ),stale ).rate_previous ) 1541 1542def test_navigation_freeze_and_quit_at_supported_sizes (self ): 1543async def exercise (size ): 1544endpoint = Endpoint ("http://127.0.0.1:18765" ) 1545app = MonitorApp (endpoint ,four_gpu_snapshot (),interval = 30 ) 1546async with app .run_test (size = size )as pilot : 1547await pilot .press ("2" ) 1548await pilot .pause () 1549self .assertEqual (app .view ,1 ) 1550await pilot .press ("tab" ) 1551await pilot .pause () 1552self .assertEqual (app .serving_pane ,"requests" ) 1553await pilot .press ("enter" ) 1554await pilot .pause () 1555self .assertFalse (app .detail )# fixture has no correlated request rows 1556await pilot .press ("space" ) 1557await pilot .pause () 1558self .assertTrue (app .frozen ) 1559await pilot .press ("space" ) 1560await pilot .pause () 1561self .assertFalse (app .frozen ) 1562await pilot .press ("q" ) 1563for size in ((110 ,30 ), (80 ,24 ), (60 ,16 ), (40 ,12 )): 1564asyncio .run (exercise (size )) 1565 1566def test_resize_keeps_selected_request_visible_in_tiny_serving_view (self ): 1567async def exercise (): 1568snapshot = four_gpu_snapshot () 1569snapshot ["work" ]["requests" ]= [ 1570 {"id" :"selected-1" ,"state" :"reading" ,"slot" :0 , 1571"group" :0 ,"prompt_read" :8 ,"prompt_tokens" :64 }] 1572app = MonitorApp (Endpoint ("http://127.0.0.1:18765" ),snapshot ,interval = 30 ) 1573async with app .run_test (size = (110 ,30 ))as pilot : 1574await pilot .press ("2" ,"tab" ,"enter" ) 1575await pilot .pause () 1576self .assertTrue (app .detail ) 1577identity = app .selected_identity 1578for width ,height in ((80 ,24 ), (60 ,16 ), (40 ,12 ), (110 ,30 )): 1579await pilot .resize_terminal (width ,height ) 1580content = str (app .query_one ("#content" ).render ()) 1581self .assertEqual ((app .screen .size .width ,app .screen .size .height ), 1582 (width ,height )) 1583self .assertIn ("selected-1" ,content ) 1584self .assertEqual (app .selected_identity ,identity ) 1585self .assertTrue (app .detail ) 1586if (width ,height )== (40 ,12 ): 1587self .assertIn ("More: strata status --json" ,content ) 1588self .assertIn ("q keeps server on" ,str (app .query_one ("#message" ).render ())) 1589elif (width ,height )== (110 ,30 ): 1590self .assertNotIn ("More: strata status --json" ,content ) 1591await pilot .press ("q" ) 1592asyncio .run (exercise ()) 1593 1594def test_request_detail_key_is_read_only (self ): 1595async def exercise (): 1596snapshot = four_gpu_snapshot () 1597snapshot ["work" ]["requests" ]= [{"id" :"r1" ,"state" :"reading" ,"slot" :0 , 1598"group" :0 ,"prompt_read" :8 ,"prompt_tokens" :64 }] 1599endpoint = Endpoint ("http://127.0.0.1:18765" ) 1600app = MonitorApp (endpoint ,snapshot ,interval = 30 ) 1601async with app .run_test (size = (80 ,24 ))as pilot : 1602await pilot .press ("2" ,"tab" ,"enter" ) 1603await pilot .pause () 1604self .assertTrue (app .detail ) 1605self .assertIn ("REQUEST DETAIL" ,str (app .query_one ("#content" ).render ())) 1606await pilot .press ("enter" ) 1607await pilot .pause () 1608self .assertFalse (app .detail ) 1609await pilot .press ("q" ) 1610asyncio .run (exercise ()) 1611 1612def test_filter_paste_is_bounded_clean_and_keeps_keyboard_focus (self ): 1613from textual .events import Paste 1614from textual .widgets import Input 1615 1616async def exercise (): 1617snapshot = four_gpu_snapshot () 1618snapshot ["work" ]["requests" ]= [{"id" :"r01" ,"state" :"reading" }, 1619 {"id" :"r02" ,"state" :"queued" }] 1620app = MonitorApp (Endpoint ("http://127.0.0.1:18765" ),snapshot ,interval = 30 ) 1621async with app .run_test (size = (80 ,24 ))as pilot : 1622await pilot .press ("3" ,"slash" ) 1623field = app .query_one ("#filter" ,Input ) 1624self .assertIs (app .focused ,field ) 1625field .post_message (Paste ("x" * 1024 + "\u202e" )) 1626await pilot .pause () 1627self .assertLessEqual (len (field .value ),80 ) 1628self .assertNotIn ("\u202e" ,field .value ) 1629await pilot .press ("q" ) 1630self .assertFalse (app .closing ) 1631field .value = "" 1632field .post_message (Paste ("\u202er01" )) 1633await pilot .pause () 1634self .assertEqual (field .value ,"r01" ) 1635await pilot .press ("enter" ) 1636self .assertEqual (app .filter_text ,"r01" ) 1637self .assertIsNone (app .focused ) 1638shown = str (app .query_one ("#content" ).render ()) 1639self .assertIn ("r01" ,shown ) 1640self .assertNotIn ("r02" ,shown ) 1641await pilot .press ("q" ) 1642self .assertTrue (app .closing ) 1643asyncio .run (exercise ()) 1644 1645 1646if __name__ == "__main__" : 1647unittest .main ()