okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-022-apikey: the API key is optional; serving without one warns, never refusescc500be1c

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