nmbrs_tui/status_fold.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! SRD-100 P2 — consumer-side per-phase status renderer.
5//!
6//! The live multi-phase status is produced by **folding the snapshot at
7//! the consumer**, not by N per-phase producer threads submitting strings
8//! to one slot (SRD-100 §6). Each display surface walks `active_phases`
9//! and calls [`render_phase_status`] on every entry to re-derive *that
10//! phase's* status line from its
11//! [`PhaseRenderHandle`](nmbrs_runtime::observer::PhaseRenderHandle)
12//! (`nmbrs_runtime::observer`). This replaces the retired inline-status
13//! refresh thread + the single `RunState::status_render` scalar that the
14//! threads stomped under concurrency.
15//!
16//! **Byte-identity (SRD-100 §12 A1):** the render reuses the producer's
17//! own `build_inline_refresh_context` and fires the same `BakedBody`
18//! template, so a single-phase run renders identical bytes to the
19//! pre-SRD-100 producer path. `BakedBody` is `Send + Sync`, so the format
20//! template rides the ArcSwap snapshot as pure data; only the `!Sync`
21//! *binder* is kept out (bodies fire with `&self`).
22
23use nmbrs_runtime::build_inline_refresh_context;
24use nmbrs_runtime::readouts::{ContentMode, StringSink};
25
26use crate::state::{ActivePhase, PhaseStatus, RunState};
27use crate::widgets::format_dur_compact;
28
29/// Collect the active phases in **stable dispatch order** — pre-map `seq`
30/// first (so sibling order matches the plan), then `(name, labels)` for a
31/// total order independent of `HashMap` iteration. Shared by every status
32/// fold so all surfaces agree on ordering (SRD-100 §7a/§12).
33pub fn active_phases_ordered(snap: &RunState) -> Vec<&ActivePhase> {
34 let mut phases: Vec<&ActivePhase> = snap.active_phases.values().collect();
35 phases.sort_by(|a, b| {
36 let ka = (a.render.as_ref().and_then(|h| h.seq), &a.name, &a.labels);
37 let kb = (b.render.as_ref().and_then(|h| h.seq), &b.name, &b.labels);
38 ka.cmp(&kb)
39 });
40 phases
41}
42
43/// Fold every active phase into one status block — one phase's status
44/// render per stable-ordered entry, joined by newlines. This is the P2
45/// consumer-side replacement for the single `status_render` scalar; P3
46/// layers the height cap, multi-running counter, and overflow roll-up on
47/// top. Returns `None` when no active phase has a renderable status (so a
48/// surface clears its footer exactly as the old `status(None)` did).
49pub fn render_active_status(snap: &RunState) -> Option<String> {
50 render_active_status_with_gutters(snap).map(|(text, _)| text)
51}
52
53/// Per-line CONTEXTUAL GUTTER content for the footer's left margin
54/// (SRD-92). Each block renders header-first: the header row carries
55/// the node's own timing triad, and every detail row under it owns
56/// one gutter cell (possibly blank) — cells stack vertically under
57/// the header, single-placement intact.
58#[derive(Clone, Debug, PartialEq)]
59pub enum RowGutter {
60 /// Plain blank-aligned divider.
61 Blank,
62 /// Node HEADER row (SRD-92 R1): the pre-rendered, uncolored
63 /// margin body (`session · [n/N] · node-time` triad) for this
64 /// node — the sink wraps it in the color + divider dressing.
65 Header(String),
66 /// Key-metric detail row (SRD-92 R4): the metric macro's live
67 /// view — a bright TREND sparkline of the phase's primary key
68 /// metric, labeled by metric name. The current numeric lives
69 /// only in the row body's chips (single placement); the cell
70 /// carries what the body can't — the history. `key` persists
71 /// the sink-side sample ring across ticks like `Spark`.
72 Metric {
73 key: String,
74 name: String,
75 value: f64,
76 },
77 /// Metered phase: completion-bar fill fraction.
78 Bar(f64),
79 /// Open-ended phase (daemon poller): latency trend. `key`
80 /// identifies the phase so the sink's sample ring persists
81 /// across ticks; p50/p99 are the current service-time
82 /// percentiles in nanos.
83 Latency {
84 key: String,
85 p50: u64,
86 p99: u64,
87 count: u64,
88 },
89 /// Workload-declared layout text (`gutter: "<template>"`),
90 /// placed in the cell verbatim (truncated to fit).
91 Text(String),
92 /// Key metric: label at the cell's left edge, value against the divider.
93 Labeled { name: String, value: String },
94 /// Workload-declared layout text COMPOSED with the phase's own
95 /// completion fraction (SRD-92 R3): the cell shows the auto
96 /// bar and the workload text side by side, so a custom cell
97 /// (e.g. a measured units/s readout) doesn't cost the operator
98 /// the progress indicator. Built by the fold whenever a Text
99 /// spec lands on a phase that has a completion fraction.
100 BarText { frac: f64, text: String },
101 /// Workload-declared trend sample (`gutter: {spark: ...}`):
102 /// sparkline ring + current value. `key` persists the ring
103 /// across ticks, like `Latency`.
104 Spark { key: String, value: f64 },
105 /// Open-ended phase, LIFETIME-histogram form: the sink's
106 /// decimating trend buffer keeps the phase's whole latency
107 /// history renderable at cell resolution (one sample per cell
108 /// until the width fills, then re-averaged at half resolution,
109 /// etc.), labeled with the discrete lifetime min∕max. Distinct
110 /// renderable from the rolling `Latency` form.
111 /// `count` is the timer's LIFETIME sample count — the sink
112 /// re-renders (and pushes a trend sample) only when it advanced
113 /// since the last draw, so a slow poller (1 op/s) keeps a stable
114 /// cell between ops instead of restating the same value every
115 /// redraw tick.
116 LatencyHist { key: String, p50: u64, count: u64 },
117 /// Session-level host-utilization strip (sysmon): one `(glyph, frac)`
118 /// per item, rendered as a single-cell symbol + a two-cell braille
119 /// meter, colored by utilization. Items arrive in display order.
120 /// SRD-92 R6: rendered ONCE per frame as the SESSION BAND leading
121 /// the fold — never embedded into phase blocks.
122 Sysmon { items: Vec<(char, f64)> },
123}
124
125/// Row roles within one rendered block (SRD-92): the header leads,
126/// details follow. Classification is positional per the contract —
127/// renderers compose header-first — with memo rows recognized by
128/// their `[[` banner form at any position.
129#[derive(Clone, Copy, Debug, PartialEq)]
130pub enum RowRole {
131 Header,
132 Memo,
133 /// The standard counters detail line (rate/ok/att/e/r/c/…).
134 Standard,
135 /// Key-metric detail rows (status-metric / adapter chips).
136 KeyMetrics,
137}
138
139/// Strip SGR escape sequences (`ESC [ … <alpha>`) so role matching
140/// sees the text an operator sees. The old classifier tested the
141/// RAW bytes and a color-styled memo banner defeated it, landing
142/// the standard-detail gutter cell on the header row.
143pub fn strip_ansi(s: &str) -> String {
144 let mut plain = String::with_capacity(s.len());
145 let mut esc = false;
146 for c in s.chars() {
147 if esc {
148 if c.is_ascii_alphabetic() {
149 esc = false;
150 }
151 continue;
152 }
153 if c == '\u{1b}' {
154 esc = true;
155 continue;
156 }
157 plain.push(c);
158 }
159 plain
160}
161
162/// Classify each row of a rendered block per SRD-92: memo rows are
163/// `[[ … ]]` banners (ANSI-stripped match), the first non-memo row
164/// is the header, the next non-memo row the standard detail line,
165/// and remaining non-memo rows are key-metric details.
166pub fn classify_block(rows: &[&str]) -> Vec<RowRole> {
167 let mut roles = Vec::with_capacity(rows.len());
168 let mut seen_header = false;
169 let mut seen_standard = false;
170 for r in rows {
171 let plain = strip_ansi(r);
172 if plain.trim_start().starts_with("[[") {
173 roles.push(RowRole::Memo);
174 } else if !seen_header {
175 seen_header = true;
176 roles.push(RowRole::Header);
177 } else if !seen_standard {
178 seen_standard = true;
179 roles.push(RowRole::Standard);
180 } else {
181 roles.push(RowRole::KeyMetrics);
182 }
183 }
184 roles
185}
186
187/// As [`render_active_status`], additionally returning one
188/// [`RowGutter`] per rendered line (indices align with the '\n'
189/// split of the returned text).
190pub fn render_active_status_with_gutters(snap: &RunState) -> Option<(String, Vec<RowGutter>)> {
191 let mut lines: Vec<String> = Vec::new();
192 let mut gutters: Vec<RowGutter> = Vec::new();
193 let session_now = snap.elapsed_secs();
194 // SRD-92 R6 — the SESSION BAND leads the fold: session-tier
195 // signals render once per frame here, above every phase block,
196 // and phase blocks carry only what they own. (Sysmon used to be
197 // embedded per phase — N active phases rendered N copies of one
198 // session-tier sample, and the copies leaked into the persisted
199 // status record.)
200 if let Some(sm) = &snap.sysmon {
201 lines.push(sysmon_detail_line(sm));
202 gutters.push(RowGutter::Sysmon {
203 items: sysmon_items(sm),
204 });
205 }
206 for p in active_phases_ordered(snap) {
207 if let Some((status, chips)) = render_phase_status_parts(p, session_now) {
208 let block: Vec<&str> = status.split('\n').collect();
209 let roles = classify_block(&block);
210 let ctx_gutter = phase_context_gutter(p);
211 let header_gutter = phase_header_gutter(p, session_now);
212 let metric_cell = phase_metric_gutter(p, &chips);
213 for (i, line) in block.iter().enumerate() {
214 lines.push((*line).to_string());
215 gutters.push(match roles[i] {
216 RowRole::Header => header_gutter.clone(),
217 RowRole::Memo => RowGutter::Blank,
218 RowRole::Standard => ctx_gutter.clone(),
219 RowRole::KeyMetrics => metric_cell.clone(),
220 });
221 }
222 for (leaf, cell) in render_op_leaves(snap, p) {
223 lines.push(leaf);
224 gutters.push(cell);
225 }
226 }
227 }
228 if lines.is_empty() {
229 None
230 } else {
231 Some((lines.join("\n"), gutters))
232 }
233}
234
235/// The sysmon glyphs, defined ONCE.
236///
237/// The gutter strip and the detail-line body both render them, and the whole
238/// point of repeating a glyph beside its named measurement is that the reader
239/// can tie the two together — so a strip glyph that disagreed with its body
240/// glyph would actively mislead. One constant per category makes that
241/// impossible by construction; `strip_and_body_agree_on_every_glyph` pins it.
242///
243/// Single-cell, text-presentation characters per the
244/// `crate::widgets::TIMING_MARK` rule: an emoji-presentation glyph would
245/// occupy two terminal cells and shift every divider on the row.
246pub const GLYPH_CPU: char = '⚙';
247pub const GLYPH_IO: char = '⛃';
248pub const GLYPH_RAM: char = '▤';
249pub const GLYPH_RAMBW: char = '⇅';
250pub const GLYPH_STORAGE: char = '⛁';
251
252/// Display order + glyphs for the sysmon strip, in the category order the
253/// setting names them: cpu, io, ram, rambw, storage. Only enabled
254/// categories appear — a `Some` field is an enabled category with a
255/// measurement; absent is absent, not zero.
256///
257/// Glyphs follow the `crate::widgets::TIMING_MARK` rule: single-cell,
258/// text-presentation symbols — an emoji-presentation glyph would occupy two
259/// terminal cells and shift every divider on the row. ⚙ cpu, ⛃ io (busy
260/// platters), ▤ ram (bank rows), ⇅ rambw (transfer), ⛁ storage (space on
261/// the same platters, hollow).
262pub fn sysmon_items(s: &nmbrs_runtime::sysmon::SysmonSample) -> Vec<(char, f64)> {
263 let mut items = Vec::new();
264 if let Some(c) = &s.cpu {
265 items.push((GLYPH_CPU, c.mean));
266 }
267 if let Some((_, u)) = &s.io {
268 items.push((GLYPH_IO, *u));
269 }
270 if let Some((committed, _)) = &s.ram {
271 items.push((GLYPH_RAM, *committed));
272 }
273 if let Some(bw) = s.rambw {
274 items.push((GLYPH_RAMBW, bw));
275 }
276 if let Some((_, u)) = &s.storage {
277 items.push((GLYPH_STORAGE, *u));
278 }
279 items
280}
281
282/// The right-side body for the sysmon detail row: the latest numbers with
283/// their subjects named — which device was busiest, which core was most
284/// saturated, which filesystem is fullest. The strip answers "how much";
285/// this line answers "of what".
286pub fn sysmon_detail_line(s: &nmbrs_runtime::sysmon::SysmonSample) -> String {
287 let pct = |f: f64| format!("{:.0}%", f * 100.0);
288 let mut parts: Vec<String> = Vec::new();
289 // Each measurement is PREFIXED with the same glyph its meter carries in
290 // the gutter, so the strip stops being a private code: a reader seeing
291 // an orange ⛁ two columns to the left can find `⛁ storage / 91%` on the
292 // right without being told the mapping.
293 if let Some(c) = &s.cpu {
294 parts.push(format!(
295 "{GLYPH_CPU} cpu {} (max c{} {})",
296 pct(c.mean),
297 c.top_core,
298 pct(c.max_core)
299 ));
300 }
301 if let Some((dev, u)) = &s.io {
302 parts.push(if dev.is_empty() {
303 format!("{GLYPH_IO} io {}", pct(*u))
304 } else {
305 format!("{GLYPH_IO} io {dev} {}", pct(*u))
306 });
307 }
308 if let Some((committed, cached)) = &s.ram {
309 parts.push(format!(
310 "{GLYPH_RAM} ram {} (+cache {})",
311 pct(*committed),
312 pct(*cached)
313 ));
314 }
315 if let Some(bw) = s.rambw {
316 parts.push(format!("{GLYPH_RAMBW} rambw {}", pct(bw)));
317 }
318 if let Some((mount, u)) = &s.storage {
319 parts.push(format!("{GLYPH_STORAGE} storage {mount} {}", pct(*u)));
320 }
321 format!(" sys: {}", parts.join(" · "))
322}
323
324/// SRD-92 R1 — the header row's margin: this node's OWN timing triad
325/// (`session · [n/N] · phase-time`), same body format the actor
326/// stamps on scrollback headers, so every concurrently-visible
327/// phase's header carries its own [n/N] and clock rather than only
328/// footer row 0 wearing the workload-level stamp.
329fn phase_header_gutter(p: &ActivePhase, session_now: f64) -> RowGutter {
330 let Some((s, n)) = p.render.as_ref().and_then(|h| h.seq) else {
331 return RowGutter::Blank;
332 };
333 let elapsed = (session_now - p.session_started).max(0.0);
334 RowGutter::Header(crate::widgets::margin_body(
335 n,
336 &format!("[{s}/{n}]"),
337 Some(elapsed),
338 Some(session_now),
339 ))
340}
341
342/// SRD-92 R4 — the key-metric detail row's default gutter cell: the
343/// metric macro, a bright trend of the phase's PRIMARY key metric
344/// (first `status_metrics:` match, numeric form). Blank when the
345/// phase publishes no chips or no primary numeric is measurable —
346/// the row body still shows the chips text either way.
347fn phase_metric_gutter(p: &ActivePhase, chips: &str) -> RowGutter {
348 if strip_ansi(chips).trim().is_empty() {
349 return RowGutter::Blank;
350 }
351 let Some(handle) = p.render.as_ref() else {
352 return RowGutter::Blank;
353 };
354 match handle
355 .metrics
356 .collect_status_primary(&handle.status_metrics)
357 {
358 Some((name, value)) => RowGutter::Metric {
359 key: format!("metric:{}@{}", p.name, p.labels),
360 name,
361 value,
362 },
363 None => RowGutter::Blank,
364 }
365}
366
367/// The contextual gutter payload for one phase: latency trend for
368/// open-ended daemons, completion bar for metered phases (fraction
369/// basis mirrors `ReadoutContext::progress_fraction`: override →
370/// rows → cycles), Blank when nothing meaningful exists.
371fn phase_context_gutter(p: &ActivePhase) -> RowGutter {
372 let Some(handle) = p.render.as_ref() else {
373 return RowGutter::Blank;
374 };
375 // A workload-declared `gutter:` wrapper spec overrides the
376 // automatic derivation — the phase owns its cell. A TEXT spec on
377 // a metered phase COMPOSES with the completion fraction instead
378 // of replacing it (SRD-92 R3): custom readout and progress bar
379 // share the cell.
380 if let Some(spec) = handle.gutter.load_full() {
381 use nmbrs_runtime::wrappers::gutter::GutterSpec;
382 return match spec.as_ref() {
383 GutterSpec::Labeled { name, value } => RowGutter::Labeled {
384 name: name.clone(),
385 value: value.clone(),
386 },
387 GutterSpec::Text(s) => match (!p.daemon).then(|| metered_fraction(p, handle)).flatten()
388 {
389 Some(f) => RowGutter::BarText {
390 frac: f,
391 text: s.clone(),
392 },
393 None => RowGutter::Text(s.clone()),
394 },
395 GutterSpec::Bar(f) => RowGutter::Bar(*f),
396 GutterSpec::Spark(v) => RowGutter::Spark {
397 key: format!("spark:{}@{}", p.name, p.labels),
398 value: *v,
399 },
400 };
401 }
402 if p.daemon {
403 // Sliding-window view, NOT the delta reservoir: the metrics
404 // reporter drains the reservoir on its cadence, so a peek
405 // right after a drain sees an empty histogram and the cell
406 // would blink out. The 10 s rolling window keeps the
407 // percentiles time-averaged and persistent between
408 // refreshes; only a genuinely silent daemon blanks the cell.
409 let ring = handle.metrics.service_time.enable_live_window(
410 nmbrs_metrics::summaries::live_window::LiveWindowConfig {
411 window: std::time::Duration::from_secs(10),
412 ..Default::default()
413 },
414 );
415 let h = ring.peek();
416 if h.is_empty() {
417 return RowGutter::Blank;
418 }
419 // Lifetime-histogram form: the whole phase's latency history
420 // stays visible (decimated to cell width) rather than a
421 // rolling last-N-ticks window. The rolling `Latency` form
422 // remains available as the alternative renderable.
423 return RowGutter::LatencyHist {
424 key: format!("{}@{}", p.name, p.labels),
425 p50: h.value_at_quantile(0.50),
426 count: handle.metrics.service_time.count(),
427 };
428 }
429 match metered_fraction(p, handle) {
430 Some(f) => RowGutter::Bar(f),
431 None => RowGutter::Blank,
432 }
433}
434
435/// The phase's completion fraction on the single agreed basis
436/// (override → rows → cycles), `None` when nothing meters it.
437fn metered_fraction(
438 p: &ActivePhase,
439 handle: &nmbrs_runtime::observer::PhaseRenderHandle,
440) -> Option<f64> {
441 handle
442 .metrics
443 .progress_override()
444 .or_else(|| {
445 (p.rows_total > 0)
446 .then(|| (p.rows_consumed as f64 / p.rows_total as f64).clamp(0.0, 1.0))
447 })
448 .or_else(|| {
449 (p.cursor_extent > 0).then(|| {
450 (handle.metrics.cycles_completed() as f64 / p.cursor_extent as f64).clamp(0.0, 1.0)
451 })
452 })
453}
454
455/// SRD-63 / SRD-92 — render an active phase's op-level status leaves (ops
456/// that declared `readout: visible`) as footer lines nested under the
457/// phase: status icon · name · `[i/N]` (+ `@ <session>` stamp on terminal
458/// rows). Each leaf row's GUTTER CELL carries the node's own execution
459/// time — cumulative while running, final once terminal — the default
460/// cell for a visible node with no declared gutter. Single placement:
461/// duration in the cell, session stamp in the body.
462///
463/// The leaves live in `phase_ops` keyed by the phase's scene-node id, which the
464/// `ActivePhase` doesn't carry; we resolve it from the running tree row with a
465/// matching `(name, labels)`. Returns empty (no allocation of leaf lines) when
466/// the phase has no row yet or no opted-in ops.
467fn render_op_leaves(snap: &RunState, phase: &ActivePhase) -> Vec<(String, RowGutter)> {
468 let node_id = match snap.phases.iter().find(|e| {
469 e.name == phase.name && e.labels == phase.labels && matches!(e.status, PhaseStatus::Running)
470 }) {
471 Some(e) => e.node_id,
472 None => return Vec::new(),
473 };
474 let ops = match snap.phase_ops.get(&node_id) {
475 Some(ops) if !ops.is_empty() => ops,
476 _ => return Vec::new(),
477 };
478 let total = ops.len();
479 ops.iter()
480 .map(|op| {
481 let (icon, leaf, sess): (&str, Option<f64>, Option<f64>) = match &op.status {
482 PhaseStatus::Running => (
483 op_spinner((snap.elapsed_secs() - op.session_started).max(0.0)),
484 Some((snap.elapsed_secs() - op.session_started).max(0.0)),
485 // Live session clock belongs to the margin, not here.
486 None,
487 ),
488 PhaseStatus::Completed => ("✓", op.duration_secs, op.session_elapsed),
489 PhaseStatus::Failed(_) => ("✗", op.duration_secs, op.session_elapsed),
490 PhaseStatus::Pending => ("○", None, None),
491 };
492 // Duration is the leaf's GUTTER CELL (cumulative while
493 // running, final once terminal); terminal rows keep their
494 // session finish-stamp in the body — its only home.
495 // The gutter cell carries WHAT the step produced ahead of how long
496 // it took: `[12 sstables] 0.3s`. Duration alone answers "did it
497 // hang", which is the less interesting question once a step has
498 // settled. Ops with no `measure:` render exactly as before.
499 let cell = match (op.measure.as_deref(), leaf) {
500 (Some(m), Some(v)) => RowGutter::Text(format!("[{m}] {}", format_dur_compact(v))),
501 (Some(m), None) => RowGutter::Text(format!("[{m}]")),
502 (None, Some(v)) => RowGutter::Text(format_dur_compact(v)),
503 (None, None) => RowGutter::Blank,
504 };
505 let stamp = match sess {
506 Some(v) => format!(" @ {}", format_dur_compact(v)),
507 None => String::new(),
508 };
509 let mut line = format!(
510 " {icon} {name} [{seq}/{total}]{stamp}",
511 name = op.name,
512 seq = op.seq + 1,
513 );
514 if let PhaseStatus::Failed(err) = &op.status {
515 line.push_str(" ");
516 line.push_str(err);
517 }
518 (line, cell)
519 })
520 .collect()
521}
522
523/// Per-op running spinner, derived from the op's own elapsed time (250 ms
524/// cadence) so it animates without threading a sink-side tick counter through —
525/// the same elapsed-derived approach `render_phase_status` uses for its frame.
526fn op_spinner(elapsed: f64) -> &'static str {
527 use throbber_widgets_tui::symbols::throbber::BRAILLE_SIX;
528 let idx = ((elapsed * 4.0) as usize) % BRAILLE_SIX.symbols.len();
529 BRAILLE_SIX.symbols[idx]
530}
531
532/// Render one active phase's status line by folding its live render
533/// handle. Returns `None` when the phase has no handle yet (the brief
534/// window between `phase_starting` and the executor's on-task attach), no
535/// bound `on_update` bodies, or an empty render.
536///
537/// The readout's spinner frame is derived from the phase's own elapsed
538/// time at the retired producer thread's 500 ms cadence (`elapsed * 2`),
539/// so the animation rate stays identical and per-phase — no sink-side
540/// tick counter is threaded through.
541pub fn render_phase_status(phase: &ActivePhase, session_now: f64) -> Option<String> {
542 render_phase_status_parts(phase, session_now).map(|(s, _)| s)
543}
544
545/// As [`render_phase_status`], additionally returning the phase's
546/// key-metric chips text (adapter + batch + status-metric chips, as
547/// the context composes them) so the fold can derive the key-metric
548/// row's default gutter cell (SRD-92 R4) from the same context build.
549pub fn render_phase_status_parts(
550 phase: &ActivePhase,
551 session_now: f64,
552) -> Option<(String, String)> {
553 let handle = phase.render.as_ref()?;
554 if handle.bodies.is_empty() {
555 return None;
556 }
557 // `cursor_extent` is the live source extent: the executor's progress
558 // thread re-reads `global_extent()` each tick and feeds it through
559 // `PhaseProgressUpdate`, so a growing (`until_elapsed`) source's total
560 // tracks here rather than pinning at the initial base. `elapsed` is
561 // derived at the consumer.
562 // Session-clock delta — same basis as the margin's session column,
563 // so `session_started + elapsed == session_now` reconciles exactly.
564 let elapsed = (session_now - phase.session_started).max(0.0);
565 // Spinner cadence: the inline thread ticked once per 500 ms sleep, so
566 // `tick ≈ elapsed * 2`. Matching it keeps the spinner frame stable
567 // across the producer→consumer move (SRD-100 §12 A1).
568 let tick = (elapsed * 2.0) as u64;
569 let ctx = build_inline_refresh_context(
570 &handle.metrics,
571 &handle.activity_name,
572 handle.concurrency,
573 phase.cursor_extent,
574 phase.rows_consumed,
575 phase.rows_total,
576 elapsed,
577 tick,
578 &handle.status_metrics,
579 &handle.memo,
580 handle.seq,
581 handle.depth_indent.clone(),
582 // Daemons are open-ended background pollers: no progress meter,
583 // latency chip in its place.
584 phase.daemon,
585 );
586 // Fire the resolved `on_update` bodies in declaration order with
587 // `ContentMode::Value` — exactly what `DefaultBinder::fire` did for
588 // the producer thread, minus the (now consumer-owned) binder state.
589 let mut sink = StringSink::with_capacity(192);
590 for body in handle.bodies.iter() {
591 body.fire(&ctx, ContentMode::Value, &mut sink);
592 }
593 let rendered = sink.take();
594 if rendered.trim().is_empty() {
595 return None;
596 }
597 use nmbrs_runtime::readouts::context::ReadoutContext as _;
598 let chips = format!(
599 "{}{}{}",
600 ctx.adapter_counters_text(),
601 ctx.batch_info_text(),
602 ctx.status_metric_chips(),
603 );
604 Some((rendered, chips))
605}
606
607#[cfg(test)]
608mod tests {
609 use super::*;
610 use std::sync::Arc;
611 use std::time::{Duration, Instant};
612
613 use nmbrs_metrics::labels::Labels;
614 use nmbrs_metrics::summaries::binomial_summary::BinomialSummary;
615 use nmbrs_metrics::summaries::ewma::Ewma;
616 use nmbrs_metrics::summaries::peak_tracker::PeakTracker;
617 use nmbrs_runtime::activity::ActivityMetrics;
618 use nmbrs_runtime::observer::PhaseRenderHandle;
619 use nmbrs_runtime::readouts::{BakedBody, RenderStep};
620
621 use crate::state::{ActivePhaseId, RunState};
622
623 /// A live phase whose `on_update` template is a single literal — the
624 /// fold fires it and yields exactly `text`, so a test can assert the
625 /// fold's *composition* (ordering, joining, clearing) without coupling
626 /// to the `phase_status` readout's format.
627 fn literal_phase(name: &str, seq: Option<usize>, text: Option<&str>) -> ActivePhase {
628 let render = text.map(|t| PhaseRenderHandle {
629 exec_id: 1,
630 name: name.to_string(),
631 labels: String::new(),
632 activity_name: name.to_string(),
633 metrics: Arc::new(ActivityMetrics::new(&Labels::empty())),
634 bodies: Arc::new(vec![BakedBody::from_steps(vec![RenderStep::Literal(
635 t.to_string(),
636 )])]),
637 memo: Arc::new(arc_swap::ArcSwap::from_pointee(String::new())),
638 gutter: Arc::new(arc_swap::ArcSwapOption::empty()),
639 status_metrics: Arc::from(Vec::<String>::new()),
640 concurrency: 1,
641 seq: seq.map(|s| (s, 2)),
642 depth_indent: String::new(),
643 });
644 ActivePhase {
645 name: name.to_string(),
646 labels: String::new(),
647 cursor_name: "c".into(),
648 daemon: false,
649 cursor_extent: 100,
650 rows_consumed: 0,
651 rows_total: 0,
652 fibers: 1,
653 started_at: Instant::now(),
654 session_started: 0.0,
655 ops_started: 0,
656 ops_finished: 0,
657 ops_ok: 0,
658 skips: 0,
659 errors: 0,
660 retries: 0,
661 ops_per_sec: 0.0,
662 adapter_counters: Vec::new(),
663 rows_per_batch: 0.0,
664 relevancy: Vec::new(),
665 throughput_summary: Arc::new(BinomialSummary::new(60)),
666 rate_ewma: Arc::new(Ewma::new(Duration::from_secs(1))),
667 latency_peak_5s: Arc::new(PeakTracker::max(Duration::from_secs(5))),
668 latency_peak_10s: Arc::new(PeakTracker::max(Duration::from_secs(10))),
669 render,
670 }
671 }
672
673 fn state_with(phases: Vec<ActivePhase>) -> RunState {
674 let mut s = RunState::new("w.yaml", "default", "stdout");
675 for p in phases {
676 s.active_phases
677 .insert(ActivePhaseId::new(1, p.name.clone(), p.labels.clone()), p);
678 }
679 s
680 }
681
682 #[test]
683 fn single_phase_renders_its_body() {
684 let s = state_with(vec![literal_phase("run", Some(1), Some("ops=5 ok=5"))]);
685 assert_eq!(render_active_status(&s).as_deref(), Some("ops=5 ok=5"));
686 }
687
688 #[test]
689 fn two_phases_fold_in_seq_order_not_map_order() {
690 // Insert B (seq 2) and A (seq 1); the fold must emit A before B
691 // regardless of `HashMap` iteration order (SRD-100 §7a/§12).
692 let s = state_with(vec![
693 literal_phase("b", Some(2), Some("B-status")),
694 literal_phase("a", Some(1), Some("A-status")),
695 ]);
696 assert_eq!(
697 render_active_status(&s).as_deref(),
698 Some("A-status\nB-status"),
699 );
700 }
701
702 /// SRD-92 R6 — with a sysmon sample present, the utilization strip
703 /// renders EXACTLY ONCE, as the session band LEADING the fold,
704 /// regardless of how many phases are active — a session-tier signal
705 /// is never embedded per phase block. Rows/gutters stay index-
706 /// aligned, the invariant the sink's zip depends on.
707 #[test]
708 fn sysmon_renders_once_as_the_leading_session_band() {
709 let mut with = state_with(vec![
710 literal_phase("a", Some(1), Some("A")),
711 literal_phase("b", Some(2), Some("B")),
712 ]);
713 let (base_lines, base_gutters) =
714 render_active_status_with_gutters(&with).expect("baseline renders");
715 assert_eq!(base_lines.split('\n').count(), base_gutters.len());
716
717 with.sysmon = Some(nmbrs_runtime::sysmon::SysmonSample {
718 cpu: Some(nmbrs_host::cpu::CpuReading {
719 mean: 0.34,
720 max_core: 0.89,
721 top_core: 7,
722 ..Default::default()
723 }),
724 io: Some(("nvme1n1".into(), 0.97)),
725 ram: Some((0.41, 0.93)),
726 rambw: None,
727 storage: Some(("/mnt/nvme".into(), 0.71)),
728 ..Default::default()
729 });
730 let (lines, gutters) = render_active_status_with_gutters(&with).expect("renders");
731 let lines: Vec<&str> = lines.split('\n').collect();
732 assert_eq!(
733 lines.len(),
734 gutters.len(),
735 "rows and gutters must stay zipped"
736 );
737 let strips: Vec<usize> = gutters
738 .iter()
739 .enumerate()
740 .filter(|(_, g)| matches!(g, RowGutter::Sysmon { .. }))
741 .map(|(i, _)| i)
742 .collect();
743 assert_eq!(
744 strips,
745 vec![0],
746 "one session band, leading the fold — never per phase"
747 );
748 let body = lines[0];
749 assert!(
750 body.contains("nvme1n1") && body.contains("max c7 89%"),
751 "the band body names the subjects: {body:?}"
752 );
753 // The band is additive: exactly one row over the baseline.
754 assert_eq!(
755 lines.len(),
756 base_lines.split('\n').count() + 1,
757 "two active phases add exactly ONE band row, not two"
758 );
759 }
760
761 /// The edification contract: every glyph in the gutter strip appears in
762 /// the body beside its named measurement, in the same order. If these
763 /// ever diverge the strip becomes a private code that the body
764 /// mis-explains — worse than no legend at all.
765 #[test]
766 fn strip_and_body_agree_on_every_glyph() {
767 let sample = nmbrs_runtime::sysmon::SysmonSample {
768 cpu: Some(nmbrs_host::cpu::CpuReading {
769 mean: 0.02,
770 max_core: 0.70,
771 top_core: 5,
772 ..Default::default()
773 }),
774 io: Some(("loop0".into(), 0.0)),
775 ram: Some((0.22, 0.61)),
776 rambw: Some(0.33),
777 storage: Some(("/".into(), 0.40)),
778 ..Default::default()
779 };
780 let body = sysmon_detail_line(&sample);
781 let strip: Vec<char> = sysmon_items(&sample).iter().map(|(g, _)| *g).collect();
782
783 // Same glyphs, same order, on both sides.
784 let in_body: Vec<char> = body.chars().filter(|c| strip.contains(c)).collect();
785 assert_eq!(
786 in_body, strip,
787 "body must echo every strip glyph once, in strip order:\n{body}"
788 );
789
790 // And each one actually labels its own measurement.
791 for (glyph, name) in [
792 (GLYPH_CPU, "cpu"),
793 (GLYPH_IO, "io"),
794 (GLYPH_RAM, "ram"),
795 (GLYPH_RAMBW, "rambw"),
796 (GLYPH_STORAGE, "storage"),
797 ] {
798 assert!(
799 body.contains(&format!("{glyph} {name}")),
800 "{glyph} must sit immediately before `{name}`:\n{body}"
801 );
802 }
803 }
804
805 /// A category that was not measured contributes NO glyph to either side —
806 /// the legend never advertises something the strip does not show.
807 #[test]
808 fn disabled_categories_appear_in_neither_strip_nor_body() {
809 let sample = nmbrs_runtime::sysmon::SysmonSample {
810 cpu: Some(nmbrs_host::cpu::CpuReading {
811 mean: 0.5,
812 max_core: 0.5,
813 top_core: 0,
814 ..Default::default()
815 }),
816 io: None,
817 ram: None,
818 rambw: None,
819 storage: None,
820 ..Default::default()
821 };
822 let body = sysmon_detail_line(&sample);
823 assert!(body.contains(&format!("{GLYPH_CPU} cpu")));
824 for absent in [GLYPH_IO, GLYPH_RAM, GLYPH_RAMBW, GLYPH_STORAGE] {
825 assert!(!body.contains(absent), "{absent} must not appear:\n{body}");
826 }
827 assert_eq!(sysmon_items(&sample).len(), 1);
828 }
829
830 /// The bandwidth item exists only when it was measured. Three items
831 /// without resctrl, four with.
832 #[test]
833 fn sysmon_strip_omits_unavailable_bandwidth() {
834 let mut sample = nmbrs_runtime::sysmon::SysmonSample {
835 cpu: Some(nmbrs_host::cpu::CpuReading {
836 mean: 0.2,
837 max_core: 0.3,
838 top_core: 0,
839 ..Default::default()
840 }),
841 io: Some(("sda".into(), 0.5)),
842 ram: Some((0.4, 0.8)),
843 rambw: None,
844 storage: None,
845 ..Default::default()
846 };
847 assert_eq!(
848 sysmon_items(&sample).len(),
849 3,
850 "disabled categories are absent, not zero"
851 );
852 sample.rambw = Some(0.12);
853 sample.storage = Some(("/".into(), 0.7));
854 let items = sysmon_items(&sample);
855 assert_eq!(items.len(), 5);
856 // Category order is the order the setting names them.
857 assert_eq!(
858 items.iter().map(|(g, _)| *g).collect::<Vec<_>>(),
859 vec!['⚙', '⛃', '▤', '⇅', '⛁']
860 );
861 }
862
863 #[test]
864 fn fold_is_deterministic_for_a_fixed_snapshot() {
865 // Same snapshot → same bytes (the §12 multi-phase determinism
866 // property — the literal body removes elapsed/tick variance).
867 let s = state_with(vec![
868 literal_phase("a", Some(1), Some("A")),
869 literal_phase("b", Some(2), Some("B")),
870 ]);
871 assert_eq!(render_active_status(&s), render_active_status(&s));
872 }
873
874 #[test]
875 fn phase_without_handle_contributes_nothing() {
876 // A phase still in the attach window (render = None) is skipped; a
877 // concurrent phase with a handle still renders (no peer-wipe).
878 let s = state_with(vec![
879 literal_phase("pending", Some(1), None),
880 literal_phase("live", Some(2), Some("LIVE")),
881 ]);
882 assert_eq!(render_active_status(&s).as_deref(), Some("LIVE"));
883 }
884
885 #[test]
886 fn no_renderable_phase_yields_none() {
887 // Empties the footer exactly as the retired `status(None)` did.
888 assert!(render_active_status(&state_with(vec![])).is_none());
889 let s = state_with(vec![literal_phase("pending", Some(1), None)]);
890 assert!(render_active_status(&s).is_none());
891 }
892
893 #[test]
894 fn op_leaves_nest_under_their_active_phase() {
895 // SRD-63: a phase's `readout: visible` op leaves render as indented
896 // lines directly under its status line, in arrival order, with the
897 // status icon, `[i/N]` count and compact times.
898 use crate::state::{EntryKind, OpEntry, PhaseEntry, PhaseStatus};
899
900 let mut s = state_with(vec![literal_phase("flush", Some(1), Some("flush-status"))]);
901 let node_id = 1usize; // SceneNodeId is a usize; value only has to be consistent below
902 s.phases.push(PhaseEntry {
903 node_id,
904 name: "flush".into(),
905 labels: String::new(),
906 status: PhaseStatus::Running,
907 kind: EntryKind::Phase,
908 op_count: 0,
909 duration_secs: None,
910 session_elapsed: None,
911 session_started: Some(0.0),
912 depth: 0,
913 summary: None,
914 op_names: Vec::new(),
915 seq: Some(1),
916 });
917 s.phase_ops.insert(
918 node_id,
919 vec![
920 OpEntry {
921 measure: None,
922 name: "encode".into(),
923 status: PhaseStatus::Completed,
924 started_at: Instant::now(),
925 session_started: 0.0,
926 duration_secs: Some(1.5),
927 session_elapsed: Some(10.0),
928 seq: 0,
929 },
930 OpEntry {
931 measure: None,
932 name: "write".into(),
933 status: PhaseStatus::Running,
934 started_at: Instant::now(),
935 session_started: 0.0,
936 duration_secs: None,
937 session_elapsed: None,
938 seq: 1,
939 },
940 ],
941 );
942
943 let out = render_active_status(&s).expect("some status");
944 let mut lines = out.lines();
945 assert_eq!(lines.next(), Some("flush-status")); // phase line leads
946 let l1 = lines.next().expect("op leaf 1");
947 assert!(l1.contains("✓ encode") && l1.contains("[1/2]"), "got: {l1}");
948 let l2 = lines.next().expect("op leaf 2");
949 assert!(l2.contains("write") && l2.contains("[2/2]"), "got: {l2}");
950 assert_eq!(lines.next(), None); // nothing extra
951 }
952
953 #[test]
954 fn phase_without_op_leaves_is_unchanged() {
955 // The interleave must not alter output for phases with no opted-in ops.
956 let s = state_with(vec![literal_phase("run", Some(1), Some("ops=5 ok=5"))]);
957 assert_eq!(render_active_status(&s).as_deref(), Some("ops=5 ok=5"));
958 }
959
960 #[test]
961 fn classify_block_is_ansi_immune() {
962 // SRD-92: role classification strips SGR before matching. A
963 // color-styled memo banner (`\x1b[1;33m[[ … ]]`) used to defeat
964 // the raw `starts_with("[[")` test, sliding the standard-detail
965 // gutter cell onto the header row (bar-beside-header bug).
966 let rows = [
967 " \u{1b}[1m\u{1b}[34mfinalize_index\u{1b}[0m 64%",
968 " \u{1b}[1;33m[[ finalize step 3/4 ]]\u{1b}[0m",
969 " 0/s ok:100% e:0 r:0 c:1",
970 " rows/s=12.5K recall:97.84%",
971 ];
972 assert_eq!(
973 classify_block(&rows),
974 vec![
975 RowRole::Header,
976 RowRole::Memo,
977 RowRole::Standard,
978 RowRole::KeyMetrics,
979 ],
980 );
981 }
982
983 #[test]
984 fn classify_block_memo_anywhere_never_shifts_roles() {
985 // Memo rows are recognized positionally-independently; the
986 // header is always the first NON-memo row and the standard
987 // detail the next, wherever the memo lands.
988 let rows = ["[[ memo ]]", "head", "stats"];
989 assert_eq!(
990 classify_block(&rows),
991 vec![RowRole::Memo, RowRole::Header, RowRole::Standard],
992 );
993 }
994
995 #[test]
996 fn text_gutter_on_metered_phase_composes_with_bar() {
997 // SRD-92 R3: a workload Text cell on a phase that has a
998 // completion fraction keeps the progress indicator — the fold
999 // emits the composed BarText, not a bare Text that would cost
1000 // the operator the bar.
1001 let p = literal_phase("run", Some(1), Some("body"));
1002 let handle = p.render.as_ref().unwrap();
1003 handle.gutter.store(Some(std::sync::Arc::new(
1004 nmbrs_runtime::wrappers::gutter::GutterSpec::Text("≈42 units/s".into()),
1005 )));
1006 match phase_context_gutter(&p) {
1007 RowGutter::BarText { frac, text } => {
1008 assert_eq!(text, "≈42 units/s");
1009 assert!((0.0..=1.0).contains(&frac));
1010 }
1011 other => panic!("metered phase + text spec must compose: {other:?}"),
1012 }
1013
1014 // A daemon (no fraction) keeps the bare text cell.
1015 let mut d = literal_phase("watch", Some(2), Some("body"));
1016 d.daemon = true;
1017 d.render
1018 .as_ref()
1019 .unwrap()
1020 .gutter
1021 .store(Some(std::sync::Arc::new(
1022 nmbrs_runtime::wrappers::gutter::GutterSpec::Text("t".into()),
1023 )));
1024 assert!(
1025 matches!(phase_context_gutter(&d), RowGutter::Text(_)),
1026 "open-ended phase has no fraction to compose"
1027 );
1028 }
1029
1030 #[test]
1031 fn header_rows_carry_their_own_triad_gutter() {
1032 // SRD-92 R1: every phase's header row gets a Header gutter
1033 // carrying that node's OWN margin body ([n/N] from its seq) —
1034 // not just footer row 0.
1035 let s = state_with(vec![
1036 literal_phase("a", Some(1), Some("A-status")),
1037 literal_phase("b", Some(2), Some("B-status")),
1038 ]);
1039 let (_, gutters) = render_active_status_with_gutters(&s).expect("some");
1040 match (&gutters[0], &gutters[1]) {
1041 (RowGutter::Header(a), RowGutter::Header(b)) => {
1042 assert!(a.contains("[1/2]"), "phase a triad: {a:?}");
1043 assert!(b.contains("[2/2]"), "phase b triad: {b:?}");
1044 }
1045 other => panic!("both header rows must carry Header gutters: {other:?}"),
1046 }
1047 }
1048}