Skip to main content

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