okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
37.8 KiB591 linesraw
1"""Wide, read-only detail pages for the terminal monitor.
2
3Every value comes from the bounded telemetry snapshot. These pages are a
4presentation layer: they never inspect prompt bodies or query the engine.
5"""
6
7from __future__ import annotations
8
9from typing import Any
10
11from rich.console import Group
12from rich.panel import Panel
13from rich.text import Text
14
15from strata_cli import nav
16from strata_cli.client import complete_slots
17from strata_cli.dashboard import (set_ascii_boxes, _rounded, _age, _current_batch_value, _current_sample,
18                                  _device_role, _gib, _meter, _rate_spark, _spark,
19                                  _state, _visual_pair, _visual_panel, MonitorHistory)
20from strata_cli.render import (VIEWS, _device_stage, _queue_wait, _recent_detail,
21                               _request_detail, _slot_detail, activity_continuity_notice,
22                               activity_label, activity_rows, field, number,
23                               request_rows, safe)
24
25
26def _palette(color: bool, theme: str) -> dict[str, str]:
27    if not color:
28        return {key: "default" for key in ("cyan", "green", "amber", "violet", "red")}
29    if theme == "light":
30        return {"cyan": "#087b9a", "green": "#0c8a60", "amber": "#946000",
31                "violet": "#7842af", "red": "#b01a2e"}
32    return {"cyan": "#22d3ee", "green": "#34d399", "amber": "#fbbf24",
33            "violet": "#a78bfa", "red": "#ff8a98"}
34
35
36def _txt(value: str, style: str = "") -> Text:
37    return Text(value, style=style, no_wrap=True, overflow="crop")
38
39
40def _panel(lines: list[Text], title: str, accent: str, color: bool, height: int) -> Panel:
41    capacity = max(1, height - 2)
42    if len(lines) > capacity:
43        lines = lines[:capacity - 1] + [_txt("… more rows; use Up/Down or filter", "dim")]
44    return _visual_panel(lines, title, accent, color, height=height)
45
46
47def _window(rows: list[Any], selected: int, capacity: int) -> tuple[int, list[Any]]:
48    start = min(max(0, selected - capacity // 2), max(0, len(rows) - capacity))
49    return start, rows[start:start + capacity]
50
51
52def _route(row: dict) -> str:
53    replica = f"R{row['replica']}/" if type(row.get("replica")) is int else ""
54    slot = f"S{row['slot']}" if type(row.get("slot")) is int else "--"
55    return replica + slot
56
57
58def _request_line(row: dict, snapshot: dict, slots: list[dict] | None,
59                  *, selected: bool, live: bool, color: bool, palette: dict[str, str]) -> Text:
60    state = safe(row.get("state"), 10)
61    prompt = (f"{number(row.get('prompt_read'))}/{number(row.get('prompt_tokens'))}"
62              if state == "reading" else number(row.get("prompt_tokens")))
63    rate = next((slot.get("tok_s") for slot in slots or []
64                 if slot.get("slot") == row.get("slot") and slot.get("request_id") == row.get("id")), None)
65    wait = number(_queue_wait(row, snapshot.get("sampled_at")), "s", 1)
66    first = number(row.get("first_engine_token_s"), "s", 2)
67    line = (f"{'▸' if selected else ' '} {field(row.get('id'), 12)} {state:<10} "
68            f"{_route(row):<7} {prompt:<11} {number(row.get('generated')):>5} "
69            f"{number(rate if live else None, '', 1):>6}  {wait:>5}  {first:>6}")
70    tint = (palette["amber"] if state in ("queued", "reading") else
71            palette["green"] if state == "decoding" else palette["violet"])
72    return _txt(line, tint if color else "")
73
74
75def _request_heading() -> Text:
76    return _txt("  ID           STATE      ROUTE   PROMPT       OUT   SLOT/s   WAIT   1ST", "dim")
77
78
79def _device_lines(row: dict, *, selected: bool, topology: dict,
80                  history: MonitorHistory, glyphs: str, live: bool,
81                  palette: dict[str, str], color: bool) -> list[Text]:
82    index = row.get("index")
83    util = row.get("util") if live else None
84    used = row.get("mem_used") if live else None
85    total = row.get("mem_total") if live else None
86    power = row.get("power") if live else None
87    temp = row.get("temp") if live else None
88    marker = "▸" if selected else " "
89    name = field(row.get("name"), 20)
90    header = _txt(f"{marker} GPU {number(index):<2}  {name}  {_device_role(index, topology):<4} "
91                  f"{number(util, '%'):>4}   {number(temp, 'C'):>4}   {number(power, 'W'):>5}",
92                  palette["green"] if color else "")
93    bars = _txt(f"  LOAD {_meter(util, 100, 14, glyphs)}   "
94                f"VRAM {_meter(used, total, 12, glyphs)}  {_gib(used)}/{_gib(total)}G",
95                palette["green"] if color else "")
96    trend = _txt(f"  RECENT {_spark(history.device_util.get(index) if live else (), glyphs, 17)}  "
97                 f"VRAM {_spark(history.device_vram.get(index) if live else (), glyphs, 15)}",
98                 "dim")
99    return [header, bars, trend]
100
101
102def _detail_lines(kind: str, row: dict, snapshot: dict, width: int,
103                  live: bool) -> list[Text]:
104    if kind == "device":
105        topology = snapshot.get("topology") or {}
106        lines = [f"GPU {number(row.get('index'))}  {safe(row.get('name'), 40)}",
107                 f"Load {number(row.get('util') if live else None, '%')}  "
108                 f"VRAM {_gib(row.get('mem_used') if live else None)}/"
109                 f"{_gib(row.get('mem_total') if live else None)} GiB",
110                 f"Temp {number(row.get('temp') if live else None, 'C')}  "
111                 f"Power {number(row.get('power') if live else None, 'W')}",
112                 _device_stage(topology, row.get("index"), width)]
113    elif kind == "slot":
114        lines = _slot_detail(row if live else {**row, "tok_s": None}, width)[1:]
115    elif kind == "recent":
116        lines = _recent_detail(row, width)[1:]
117    else:
118        lines = _request_detail(row, snapshot.get("sampled_at"), width)[2:]
119    return [_txt(line) for line in lines]
120
121
122def _serving(snapshot: dict, history: MonitorHistory, *, heights: tuple[int, int, int],
123             selected: int, detail: bool, pane: str, filter_text: str,
124             live: bool, glyphs: str, color: bool, palette: dict[str, str],
125             width: int) -> Group:
126    work, rates = snapshot.get("work") or {}, snapshot.get("rates") or {}
127    topology, devices = snapshot.get("topology") or {}, snapshot.get("devices") or []
128    slots = complete_slots(work)
129    top_h, mid_h, low_h = heights
130    focus = f"PANE {pane.upper()}  ·  Tab: devices / requests / groups"
131    top_left = [_txt(f"{number(work.get('active'))} ACTIVE    "
132                     f"{number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))} SLOTS    "
133                     f"{number(work.get('waiting'))} ENGINE WAIT", palette["green"] if color else ""),
134                _txt(f"ALL OUTPUT {number(rates.get('aggregate_output_tok_s') if live else None, ' tok/s', 1)}  "
135                     f"PROMPT {number(rates.get('prefill_tok_s') if live else None, ' tok/s', 1)}",
136                     palette["cyan"] if color else ""),
137                _txt(f"{safe((snapshot.get('model') or {}).get('id'), 35)}  ·  "
138                     f"{safe(topology.get('mode'), 25)}", "dim"),
139                _txt(focus, palette["amber"] if color else "")]
140    top_right = [_txt(f"{number(_current_batch_value(work, 'effective_rows_window'), '', 1)} "
141                      f"ROWS/WINDOW processed     "
142                      f"{number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)} active",
143                      palette["violet"] if color else ""),
144                 _txt(f"{number(work.get('queued'))} PRE-ADMIT    "
145                      f"{number(work.get('admission_reserved'))}/{number(work.get('admission_limit'))} "
146                      f"RESERVED/LIMIT", palette["amber"] if color else ""),
147                 _txt(f"Recent rows {_rate_spark(history.batch_rows if live else (), glyphs)}    "
148                      f"pre-admit {_rate_spark(history.pre_admit if live else (), glyphs)}", "dim"),
149                 _txt("Rows/window is an engine sample; queue is before admission.", "dim")]
150    replica_batches = work.get("replica_batches") or []
151    if replica_batches:
152        top_right = [_txt(f"R{number(row.get('replica'))} ROWS/WIN  "
153                          f"{number(_current_batch_value(row, 'effective_rows_window'), '', 1)} processed / "
154                          f"{number(_current_batch_value(row, 'batch_active_rows_window'), '', 1)} active",
155                          palette["violet"] if color else "")
156                     for row in replica_batches[:2]]
157        top_right.append(_txt(f"{number(work.get('queued'))} PRE-ADMIT   "
158                              f"{number(work.get('admission_reserved'))}/"
159                              f"{number(work.get('admission_limit'))} RESERVED/LIMIT",
160                              palette["amber"] if color else ""))
161        top_right.append(_txt("Replica sample windows are independent.", "dim"))
162    requests, _ = request_rows(snapshot, filter_text)
163    request_start, request_shown = _window(requests, selected if pane == "requests" else 0,
164                                           max(1, mid_h - 5))
165    flow = [_request_heading()]
166    for i, row in enumerate(request_shown, request_start):
167        flow.append(_request_line(row, snapshot, slots, selected=pane == "requests" and i == selected,
168                                  live=live, color=color, palette=palette))
169    if not requests:
170        flow.append(_txt("Request identities unavailable" if work.get("requests") is None else
171                         "No requests match the filter" if filter_text else
172                         "No active requests", "dim"))
173    if len(requests) > len(request_shown):
174        flow.append(_txt(f"Showing {request_start + 1}-{request_start + len(request_shown)} "
175                         f"of {len(requests)}; use Requests for the full list", "dim"))
176    queue = [_txt(f"PRE-ADMIT   {_meter(work.get('queued'), work.get('max_queue'), 20, glyphs)} "
177                  f"{number(work.get('queued'))}/{number(work.get('max_queue'))}",
178                  palette["amber"] if color else ""),
179             _txt(f"Oldest wait {number(work.get('oldest_queue_s'), 's', 1)}   "
180                  f"timeout {number(work.get('queue_timeout_s'), 's', 1)}"),
181             _txt(f"Rejected {number(work.get('admission_rejected'))}   "
182                  f"timed out {number(work.get('queue_timeouts'))}   "
183                  f"disconnect cancels {number(work.get('client_disconnect_cancels'))}"),
184             _txt("", ""), _txt("ENGINE SLOT FLOW", "dim")]
185    for state, label, shade in (("reading", "PREFILL", palette["amber"]),
186                                ("decoding", "DECODE", palette["green"]),
187                                ("idle", "IDLE", "dim")):
188        count = sum(row.get("state") == state for row in slots or [])
189        queue.append(_txt(f"{label:<8} {number(count) if slots is not None else '--':>3}  "
190                          f"{_meter(count if slots is not None else None, len(slots or []), 20, glyphs)}",
191                          shade if color else ""))
192    queue.append(_txt("Groups are pipeline batch groups, not GPU assignments.", "dim"))
193    slot_rows = work.get("slots") or []
194    slot_start, slot_shown = _window(slot_rows, selected if pane == "groups" else 0,
195                                    max(1, low_h - 5))
196    slot_lines = [_txt("  SLOT  GROUP  STATE       REQUEST      HELD / CONTEXT     SLOT/s", "dim")]
197    context = (snapshot.get("model") or {}).get("context")
198    for i, row in enumerate(slot_shown, slot_start):
199        mark = "▸" if pane == "groups" and i == selected else " "
200        slot_lines.append(_txt(f"{mark} S{number(row.get('slot')):<4} "
201                               f"G{number(row.get('group')):<5} {safe(row.get('state'), 10):<11} "
202                               f"{field(row.get('request_id'), 12)} "
203                               f"{number(row.get('held_tokens')):>6}/{number(context):<7} "
204                               f"{number(row.get('tok_s') if live else None, '', 1):>6}",
205                               palette["green"] if row.get("state") == "decoding" and color else
206                               palette["amber"] if row.get("state") == "reading" and color else "dim"))
207    if not slot_rows:
208        slot_lines.append(_txt("Slot detail unavailable", "dim"))
209    if len(slot_rows) > len(slot_shown):
210        slot_lines.append(_txt(f"Slots {slot_start + 1}-{slot_start + len(slot_shown)} of {len(slot_rows)}", "dim"))
211    device_lines: list[Text] = []
212    device_start, device_shown = _window(devices, selected if pane == "devices" else 0, 4)
213    for i, row in enumerate(device_shown, device_start):
214        index = row.get("index")
215        device_lines.append(_txt(f"{'▸' if pane == 'devices' and i == selected else ' '} GPU "
216                                 f"{number(index)}  {field(row.get('name'), 18)}  "
217                                 f"{_device_role(index, topology):<4} "
218                                 f"{number(row.get('util') if live else None, '%'):>4}  "
219                                 f"{_gib(row.get('mem_used') if live else None)}/"
220                                 f"{_gib(row.get('mem_total') if live else None)}G",
221                                 palette["green"] if color else ""))
222        device_lines.append(_txt(f"    {_meter(row.get('util') if live else None, 100, 14, glyphs)}  "
223                                 f"VRAM {_meter(row.get('mem_used') if live else None, row.get('mem_total') if live else None, 13, glyphs)}",
224                                 palette["green"] if color else ""))
225    if not devices:
226        device_lines.append(_txt("Per-device readings unavailable", "dim"))
227    if len(devices) > 4:
228        device_lines.append(_txt(f"Cards {device_start + 1}-{device_start + len(device_shown)} "
229                                  f"of {len(devices)} · Hardware shows all", "dim"))
230    if detail:
231        rows = devices if pane == "devices" else requests if pane == "requests" else slot_rows
232        if rows and selected < len(rows):
233            kind = "device" if pane == "devices" else "live" if pane == "requests" else "slot"
234            device_lines.extend(_detail_lines(kind, rows[selected], snapshot, width - 70, live)[-3:])
235    return Group(_visual_pair(_panel(top_left, "SERVING / REQUEST PRESSURE", palette["cyan"], color, top_h),
236                              _panel(top_right, "BATCHING / ADMISSION", palette["violet"], color, top_h), 1, 1),
237                 _visual_pair(_panel(flow, f"REQUEST FLOW · {len(requests)} visible", palette["cyan"], color, mid_h),
238                              _panel(queue, "QUEUE / SLOT PHASES", palette["amber"], color, mid_h), 4, 3),
239                 _visual_pair(_panel(slot_lines, "ENGINE SLOTS / CONTEXT", palette["violet"], color, low_h),
240                              _panel(device_lines, "GPU FLEET / FOCUS", palette["green"], color, low_h), 4, 3))
241
242
243def _requests(snapshot: dict, *, heights: tuple[int, int, int], selected: int,
244              detail: bool, filter_text: str, live: bool, glyphs: str,
245              color: bool, palette: dict[str, str], width: int) -> Group:
246    work, rates = snapshot.get("work") or {}, snapshot.get("rates") or {}
247    slots = complete_slots(work)
248    active, recent = request_rows(snapshot, filter_text)
249    rows = [("live", row) for row in active] + [("recent", row) for row in recent]
250    top_h, mid_h, low_h = heights
251    top_left = [_txt(f"{len(active)} LIVE    {len(recent)} RECENT    "
252                     f"{number(work.get('queued'))} PRE-ADMIT    "
253                     f"{number(work.get('waiting'))} ENGINE WAIT",
254                     palette["green"] if color else ""),
255                _txt(f"{number(rates.get('aggregate_output_tok_s') if live else None, ' tok/s', 1)} "
256                     f"ALL OUTPUT   {number(rates.get('answer_tok_s') if live else None, ' tok/s', 1)} "
257                     f"ANSWER", palette["cyan"] if color else ""),
258                _txt("IDs and counts only · no prompt or tool text", "dim")]
259    top_right = [_txt(f"Occupied {number(work.get('occupied_slots'))}/"
260                      f"{number(work.get('slots_effective'))} slots    "
261                      f"Context {(number((snapshot.get('model') or {}).get('context')))} / slot",
262                      palette["violet"] if color else ""),
263                 _txt(f"Oldest queue {number(work.get('oldest_queue_s'), 's', 1)}   "
264                      f"Last first engine {number(recent[0].get('first_engine_token_s') if recent else None, 's', 2)}"),
265                 _txt("Up/Down selects · Enter opens detail · / filters", "dim")]
266    live_start, live_shown = _window(active, selected if selected < len(active) else 0,
267                                     max(1, mid_h - 5))
268    live_lines = [_request_heading()]
269    for i, row in enumerate(live_shown, live_start):
270        live_lines.append(_request_line(row, snapshot, slots, selected=i == selected,
271                                        live=live, color=color, palette=palette))
272    if not active:
273        live_lines.append(_txt("No live request summaries" if not filter_text else
274                               "No live requests match the filter", "dim"))
275    if len(active) > len(live_shown):
276        live_lines.append(_txt(f"Showing {live_start + 1}-{live_start + len(live_shown)} of {len(active)}", "dim"))
277    recent_lines = [_txt("  ID           FINISH      IN   CACHE   OUT   TIME   FIRST", "dim")]
278    recent_start, recent_shown = _window(recent, max(0, selected - len(active)), max(1, low_h - 4))
279    for i, row in enumerate(recent_shown, recent_start):
280        recent_lines.append(_txt(f"{'▸' if selected == len(active) + i else ' '} "
281                                 f"{field(row.get('id'), 12)} {safe(row.get('finish'), 10):<11} "
282                                 f"{number(row.get('prompt_tokens')):>6} "
283                                 f"{number(row.get('reused')):>5} "
284                                 f"{number(row.get('output_tokens')):>5} "
285                                 f"{number(row.get('duration_s'), 's', 1):>6} "
286                                 f"{number(row.get('first_engine_token_s'), 's', 2):>5}", "dim"))
287    if not recent:
288        recent_lines.append(_txt("No completed request summaries retained", "dim"))
289    if len(recent) > len(recent_shown):
290        recent_lines.append(_txt(f"Showing {recent_start + 1}-{recent_start + len(recent_shown)} of {len(recent)}", "dim"))
291    detail_lines: list[Text] = []
292    if rows:
293        kind, row = rows[min(max(0, selected), len(rows) - 1)]
294        detail_lines.append(_txt(f"{safe(row.get('id'), 28)}  ·  {kind.upper()}",
295                                 palette["green"] if color else ""))
296        if detail:
297            detail_lines.extend(_detail_lines(kind, row, snapshot, width // 2, live))
298        elif kind == "live":
299            detail_lines.extend([_txt(f"{safe(row.get('state'), 12)}  ·  {_route(row)}  ·  "
300                                      f"{number(row.get('prompt_tokens'))} prompt tokens"),
301                                 _txt(f"{number(row.get('generated'))} output  ·  "
302                                      f"wait {number(_queue_wait(row, snapshot.get('sampled_at')), 's', 1)}")])
303        else:
304            detail_lines.extend([_txt(f"{safe(row.get('finish'), 12)}  ·  "
305                                      f"{number(row.get('output_tokens'))} output tokens"),
306                                 _txt(f"Duration {number(row.get('duration_s'), 's', 2)}")])
307    else:
308        detail_lines.append(_txt("Select a request to inspect its redacted telemetry", "dim"))
309    detail_lines.append(_txt("Read only. Request text is never collected.", "dim"))
310    if not detail:
311        detail_lines.append(_txt("Enter expands the selected row", "dim"))
312    return Group(_visual_pair(_panel(top_left, "REQUESTS / CONCURRENCY", palette["cyan"], color, top_h),
313                              _panel(top_right, "LATENCY / CONTEXT", palette["amber"], color, top_h), 1, 1),
314                 _panel(live_lines, f"IN FLIGHT · {len(active)}", palette["green"], color, mid_h),
315                 _visual_pair(_panel(recent_lines, f"RECENTLY FINISHED · {len(recent)}", palette["violet"], color, low_h),
316                              _panel(detail_lines, "SELECTED REQUEST", palette["cyan"], color, low_h), 1, 1))
317
318
319def _engine(snapshot: dict, history: MonitorHistory, *, heights: tuple[int, int, int],
320            live: bool, glyphs: str, color: bool, palette: dict[str, str]) -> Group:
321    model, work = snapshot.get("model") or {}, snapshot.get("work") or {}
322    rates, topology = snapshot.get("rates") or {}, snapshot.get("topology") or {}
323    slots = complete_slots(work)
324    top_h, mid_h, low_h = heights
325    top_left = [_txt(f"{safe(topology.get('mode'), 30)}    "
326                     f"{number(len(topology.get('selected_devices') or []))} SELECTED GPUS",
327                     palette["cyan"] if color else ""),
328                _txt(f"{number(work.get('occupied_slots'))}/"
329                     f"{number(work.get('slots_effective'))} SLOTS   "
330                     f"{number(work.get('groups'))} BATCH GROUPS   "
331                     f"{number(model.get('context'))} CONTEXT", palette["violet"] if color else ""),
332                _txt("Layer mapping is from the engine start log when available.", "dim")]
333    top_right = [_txt(f"ANSWER {number(rates.get('answer_tok_s') if live else None, ' tok/s', 1)}   "
334                      f"PROMPT {number(rates.get('prefill_tok_s') if live else None, ' tok/s', 1)}",
335                      palette["cyan"] if color else ""),
336                 _txt(f"ROWS/WIN {number(_current_batch_value(work, 'effective_rows_window'), '', 1)} "
337                      f"processed / {number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)} active",
338                      palette["amber"] if color else ""),
339                 _txt("Host in-flight span is not GPU kernel utilization.", "dim")]
340    stages: list[Text] = []
341    replica_samples = {row.get("replica"): row for row in work.get("replica_stage_samples") or []}
342    if topology.get("replica_stages"):
343        for entry in topology["replica_stages"]:
344            replica = entry.get("replica")
345            sample = replica_samples.get(replica) or {}
346            fresh = _current_sample(sample, "stage_sample_age_s") and live
347            measured = {row.get("stage"): row for row in sample.get("stage_in_flight") or []} if fresh else {}
348            stages.append(_txt(f"R{number(replica)}  stage host span · "
349                               f"{number(sample.get('stage_sample_span_s') if fresh else None, 's', 1)} window",
350                               palette["violet"] if color else ""))
351            for stage in entry.get("stages") or []:
352                value = (measured.get(stage.get("stage")) or {}).get("percent")
353                stages.append(_txt(f"  S{number(stage.get('stage')):<2} GPU {number(stage.get('device_index')):<2} "
354                                   f"L{number(stage.get('layer_start'))}-{number(stage.get('layer_end')):<7} "
355                                   f"{_meter(value, 100, 16, glyphs)} {number(value, '%')}",
356                                   palette["violet"] if color else ""))
357    elif topology.get("stages"):
358        fresh = _current_sample(work, "stage_sample_age_s") and live
359        measured = {row.get("stage"): row for row in work.get("stage_in_flight") or []} if fresh else {}
360        for stage in topology["stages"]:
361            value = (measured.get(stage.get("stage")) or {}).get("percent")
362            stages.append(_txt(f"S{number(stage.get('stage')):<2} GPU {number(stage.get('device_index')):<2} "
363                               f"LAYERS {number(stage.get('layer_start')):>3}-"
364                               f"{number(stage.get('layer_end')):<4} "
365                               f"{_meter(value, 100, 18, glyphs)} {number(value, '%'):>4}",
366                               palette["violet"] if color else ""))
367    else:
368        stages.append(_txt("Stage/layer mapping unavailable", "dim"))
369    stages.append(_txt("Host poll delay is included; this is not kernel occupancy.", "dim"))
370    batch = [_txt(f"Engine rows/window  "
371                  f"{number(_current_batch_value(work, 'effective_rows_window'), '', 1)} processed  "
372                  f"{number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)} active",
373                  palette["amber"] if color else ""),
374             _txt(f"Trend {_rate_spark(history.batch_rows if live else (), glyphs)}", "dim"),
375             _txt(f"Sample {number(work.get('batch_sample_windows'))} windows / "
376                  f"{number(work.get('batch_sample_span_s'), 's', 1)}  "
377                  f"age {number(work.get('batch_sample_age_s'), 's', 1)}"),
378             _txt("")]
379    for row in (work.get("replica_batches") or [])[:6]:
380        current = _current_sample(row, "batch_sample_age_s") and live
381        batch.append(_txt(f"R{number(row.get('replica'))}  "
382                          f"{number(row.get('effective_rows_window') if current else None, '', 1)} "
383                          f"processed / {number(row.get('batch_active_rows_window') if current else None, '', 1)} "
384                          f"active    age {number(row.get('batch_sample_age_s'), 's', 1)}",
385                          palette["amber"] if color else ""))
386    batch.extend([_txt(""), _txt(f"{number(work.get('waiting'))} engine waiting  ·  "
387                                  f"{number(work.get('queued'))} before admission"),
388                  _txt("Rows/window counts engine batch work, not requests.", "dim")])
389    context = model.get("context")
390    contexts = [_txt("SLOT   STATE      HELD / CAPACITY                  REQUEST", "dim")]
391    if slots is None:
392        contexts.append(_txt("Complete slot map unavailable", "dim"))
393    else:
394        for row in slots[:max(1, low_h - 5)]:
395            held = row.get("held_tokens") if live and row.get("state") != "idle" else 0 if live and row.get("state") == "idle" else None
396            contexts.append(_txt(f"S{number(row.get('slot')):<4} "
397                                 f"{safe(row.get('state'), 10):<10} "
398                                 f"{_meter(held, context, 14, glyphs)} "
399                                 f"{number(held):>6}/{number(context):<7} "
400                                 f"{field(row.get('request_id'), 12)}",
401                                 palette["green"] if row.get("state") == "decoding" and color else
402                                 palette["amber"] if row.get("state") == "reading" and color else "dim"))
403    note = [_txt("MEASUREMENT SOURCES", palette["cyan"] if color else ""),
404            _txt("Layer ranges    engine start log"),
405            _txt("Stage in-flight host scheduling sample"),
406            _txt("GPU load        device sensor; see Hardware"),
407            _txt("Batch rows      engine window; may be unavailable"),
408            _txt("Context         held tokens in active slot"),
409            _txt(""),
410            _txt("Pipeline groups are concurrency partitions.", "dim"),
411            _txt("They do not identify GPU assignments.", "dim")]
412    return Group(_visual_pair(_panel(top_left, "ENGINE / TOPOLOGY", palette["cyan"], color, top_h),
413                              _panel(top_right, "ENGINE / PERFORMANCE", palette["amber"], color, top_h), 1, 1),
414                 _visual_pair(_panel(stages, "STAGES / HOST SPAN", palette["violet"], color, mid_h),
415                              _panel(batch, "BATCH WINDOW", palette["amber"], color, mid_h), 1, 1),
416                 _visual_pair(_panel(contexts, "SLOT CONTEXTS", palette["green"], color, low_h),
417                              _panel(note, "READING THE NUMBERS", palette["cyan"], color, low_h), 4, 3))
418
419
420def _hardware(snapshot: dict, history: MonitorHistory, *, heights: tuple[int, int, int],
421              selected: int, detail: bool, live: bool, glyphs: str,
422              color: bool, palette: dict[str, str], width: int) -> Group:
423    devices, topology = snapshot.get("devices") or [], snapshot.get("topology") or {}
424    ram = snapshot.get("ram") or {}
425    top_h, mid_h, low_h = heights
426    count = len(devices)
427    watts = [row.get("power") for row in devices]
428    total_watts = sum(watts) if watts and all(isinstance(w, (int, float)) and not isinstance(w, bool) for w in watts) else None
429    top_left = [_txt(f"{count} GPU DEVICES     "
430                     f"{number(total_watts if live else None, ' W', 0)} TOTAL BOARD POWER",
431                     palette["green"] if color else ""),
432                _txt(f"{safe(topology.get('mode'), 34)}   "
433                     f"selected {number(len(topology.get('selected_devices') or []))}", "dim"),
434                _txt("Per-card values come from device sensors.", "dim")]
435    used, total = ram.get("used") if live else None, ram.get("total") if live else None
436    top_right = [_txt(f"HOST RAM {_gib(used)}/{_gib(total)} GiB  "
437                      f"{_meter(used, total, 20, glyphs)}",
438                      palette["violet"] if color else ""),
439                 _txt(f"GPU load history  {_rate_spark(history.device_util.get(devices[0].get('index')) if devices and live else (), glyphs)}",
440                      "dim"),
441                 _txt("↑↓ select GPU  ·  Enter placement details", "dim")]
442    # Two cards per column; selection scrolls in four-card pages.
443    page = min(max(0, selected // 4 * 4), max(0, count - 4))
444    shown = devices[page:page + 4]
445    columns: list[list[Text]] = [[], []]
446    for offset, row in enumerate(shown):
447        column = columns[offset // 2]
448        column.extend(_device_lines(row, selected=page + offset == selected,
449                                    topology=topology, history=history,
450                                    glyphs=glyphs, live=live, palette=palette,
451                                    color=color))
452        column.append(_txt(""))
453    if not devices:
454        columns[0].append(_txt("Per-device sensor readings unavailable", "dim"))
455    for column in columns:
456        column.append(_txt(f"Showing GPU {page + 1}-{page + len(shown)} of {count}" if count else
457                           "No selected cards reported", "dim"))
458    trends: list[Text] = [_txt("GPU     UTILIZATION TREND           VRAM TREND", "dim")]
459    for row in devices[:max(1, low_h - 5)]:
460        index = row.get("index")
461        trends.append(_txt(f"GPU {number(index):<3} "
462                           f"{_spark(history.device_util.get(index) if live else (), glyphs, 22):<23} "
463                           f"{_spark(history.device_vram.get(index) if live else (), glyphs, 18)}",
464                           palette["green"] if color else ""))
465    if not devices:
466        trends.append(_txt("History unavailable", "dim"))
467    trends.append(_txt("Gaps in the sparkline mark missing samples.", "dim"))
468    focus: list[Text] = []
469    if devices:
470        row = devices[min(max(0, selected), len(devices) - 1)]
471        selected_lines = _detail_lines("device", row, snapshot, width // 2, live)
472        focus.extend(selected_lines if detail else selected_lines[:3])
473    else:
474        focus.append(_txt("Select a GPU when sensors become available", "dim"))
475    focus.append(_txt("", ""))
476    focus.append(_txt(f"HOST RAM   {_gib(used)}/{_gib(total)} GiB"))
477    focus.append(_txt(f"{_meter(used, total, 24, glyphs)}", palette["violet"] if color else ""))
478    focus.append(_txt("Placement follows the resolved engine log when reported.", "dim"))
479    if not detail:
480        focus.append(_txt("Enter expands selection; Tab changes Serving pane.", "dim"))
481    return Group(_visual_pair(_panel(top_left, "HARDWARE / GPU FLEET", palette["green"], color, top_h),
482                              _panel(top_right, "HOST MEMORY / NAVIGATION", palette["violet"], color, top_h), 1, 1),
483                 _visual_pair(_panel(columns[0], "GPU CARDS / A", palette["green"], color, mid_h),
484                              _panel(columns[1], "GPU CARDS / B", palette["green"], color, mid_h), 1, 1),
485                 _visual_pair(_panel(trends, "SENSOR HISTORY", palette["cyan"], color, low_h),
486                              _panel(focus, "SELECTED DEVICE", palette["violet"], color, low_h), 1, 1))
487
488
489def _logs(snapshot: dict, *, heights: tuple[int, int, int], filter_text: str,
490          color: bool, palette: dict[str, str]) -> Group:
491    activity = snapshot.get("activity") or {}
492    events = activity_rows(snapshot, filter_text)
493    top_h, mid_h, low_h = heights
494    top_left = [_txt(f"{len(events)} VISIBLE EVENTS    "
495                     f"LAST SEQ {number(activity.get('last_seq'))}",
496                     palette["cyan"] if color else ""),
497                _txt("Recent request activity · redacted IDs and lifecycle", "dim"),
498                _txt("This is a recent telemetry ring, not durable server logs.", "dim")]
499    notice = activity_continuity_notice(snapshot)
500    top_right = [_txt("CONTINUITY  " + (notice or "No gap reported"),
501                      palette["amber"] if notice and color else ""),
502                 _txt(f"Server source {safe(snapshot.get('source'), 34)}"),
503                 _txt("/ filters by request ID, event, or outcome", "dim")]
504    timeline = [_txt("SEQ     TIME      REQUEST ID        EVENT / OUTCOME", "dim")]
505    if not activity.get("available"):
506        timeline.append(_txt("Request activity unavailable on this server", "dim"))
507    elif not events:
508        timeline.append(_txt("No transitions retained" if not filter_text else
509                             "No events match the filter", "dim"))
510    else:
511        for row in events[-max(1, mid_h - 4):]:
512            event = safe(row.get("event"), 16)
513            tint = (palette["red"] if event in ("cancelled", "error", "rejected") else
514                    palette["green"] if event in ("finished", "first_token") else
515                    palette["amber"] if event in ("queued", "reading") else palette["cyan"])
516            timeline.append(_txt(activity_label(row, 95), tint if color else ""))
517        if len(events) > mid_h - 4:
518            timeline.append(_txt(f"Newest {mid_h - 4} of {len(events)} events shown", "dim"))
519    by_request: dict[str, list[str]] = {}
520    for row in events:
521        ident = safe(row.get("request_id"), 12)
522        by_request.setdefault(ident, []).append(safe(row.get("event"), 12))
523    flow = [_txt("REQUEST ID      OBSERVED LIFECYCLE", "dim")]
524    for ident, states in list(by_request.items())[-max(1, low_h - 5):]:
525        flow.append(_txt(f"{ident:<14} {' → '.join(states[-5:])}", palette["cyan"] if color else ""))
526    if not by_request:
527        flow.append(_txt("No request lifecycle available", "dim"))
528    flow.append(_txt("Only events retained in the current ring appear here.", "dim"))
529    limits = [_txt("PRIVACY / RETENTION", palette["violet"] if color else ""),
530              _txt("Request IDs are bounded telemetry identifiers."),
531              _txt("Prompt bodies, output text and tool content are absent."),
532              _txt("The ring may roll over between polls."),
533              _txt("A sequence gap means events were missed."),
534              _txt(""),
535              _txt(f"Newest sequence {number(activity.get('last_seq'))}"),
536              _txt(f"Visible after filter {len(events)}"),
537              _txt("Use strata logs for a one-shot redacted snapshot.", "dim")]
538    return Group(_visual_pair(_panel(top_left, "LOGS / REQUEST ACTIVITY", palette["cyan"], color, top_h),
539                              _panel(top_right, "CONTINUITY / SOURCE", palette["amber"], color, top_h), 1, 1),
540                 _panel(timeline, "RECENT EVENT TIMELINE", palette["green"], color, mid_h),
541                 _visual_pair(_panel(flow, "REQUEST LIFECYCLES", palette["cyan"], color, low_h),
542                              _panel(limits, "WHAT THIS VIEW CONTAINS", palette["violet"], color, low_h), 1, 1))
543
544
545def render_detail_dashboard(snapshot: dict, view: str, *, width: int, height: int,
546                            history: MonitorHistory, connection: str = "",
547                            connection_state: str = "connected", frozen: bool = False,
548                            filter_text: str = "", glyphs: str = "ascii",
549                            color: bool = True, theme: str = "dark", selected: int = 0,
550                            detail: bool = False, serving_pane: str = "devices", connect: bool = False) -> Group:
551    """Render the five wide pages with the visual Overview's panel language."""
552    set_ascii_boxes(glyphs == "ascii")
553    palette = _palette(color, theme)
554    state, live = _state(snapshot, connection_state, frozen)
555    active = palette["green"] if state == "LIVE" else palette["amber"] if "STALE" in state else palette["red"]
556    heading = Text()
557    heading.append(f"STRATA  /  {view.upper()}", style=f"bold {palette['cyan']}")
558    heading.append("   ")
559    heading.append(state, style=f"bold {active}" if color else "bold")
560    heading.append(f"   {safe(connection, max(0, width - 48))}")
561    header = Panel(heading, box=_rounded(), border_style=active if color else "",
562                   padding=(0, 1))
563    age = _age(snapshot)
564    hints = f"Tab pane  ↑↓ select  Enter detail  / filter  age {number(age, 's', 1)}"
565    footer = nav.styled(VIEWS.index(view), max(24, width - len(hints) - 5), connect, accent=palette["cyan"] if color else "", color=color)
566    footer.append("   ")
567    footer.append(hints, style="dim")
568    top_h = 6 if height >= 40 else 5
569    room = max(0, height - 4 - top_h)
570    mid_h = room // 2 + (3 if view in ("serving", "requests", "logs") else 1)
571    low_h = room - mid_h
572    shared = dict(heights=(top_h, mid_h, low_h), live=live, glyphs=glyphs,
573                  color=color, palette=palette)
574    if view == "serving":
575        body = _serving(snapshot, history, selected=selected, detail=detail,
576                        pane=serving_pane, filter_text=filter_text, width=width, **shared)
577    elif view == "requests":
578        body = _requests(snapshot, selected=selected, detail=detail,
579                         filter_text=filter_text, width=width, **{k: v for k, v in shared.items() if k != "heights"},
580                         heights=shared["heights"])
581    elif view == "engine":
582        body = _engine(snapshot, history, **shared)
583    elif view == "hardware":
584        body = _hardware(snapshot, history, selected=selected, detail=detail,
585                         width=width, **shared)
586    elif view == "logs":
587        body = _logs(snapshot, heights=shared["heights"], filter_text=filter_text,
588                     color=color, palette=palette)
589    else:
590        raise ValueError("visual detail view must be serving, requests, engine, hardware or logs")
591    return Group(header, body, footer)