Skip to main content

nmbrs_tui/
state.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shared state between the executor and the TUI display.
5//!
6//! `RunState` is mutated only by the [`crate::run_state_actor`]
7//! single-owner thread. Observers (executor side) and the TUI
8//! both send typed [`crate::run_state_actor::RunStateCmd`]
9//! messages into the actor inbox; the actor publishes
10//! immutable `Arc<RunState>` snapshots through an
11//! `arc_swap::ArcSwap` after every applied command. The TUI
12//! reads at its render cadence (4 Hz) via
13//! `RunStateHandle::load()` — a single atomic op that cannot
14//! wait on the writer. There is intentionally no shared
15//! `RwLock<RunState>` between the planes; see SRD-02 §"Display
16//! and Diagnostic Decoupling" for the rationale.
17//!
18//! The methods on `RunState` (`set_phase_running`, `push_log`,
19//! `install_tree`, …) are inherent helpers used by the actor's
20//! command-application path; tests can also call them directly
21//! against an unwrapped `RunState` to exercise the data-model
22//! semantics in isolation.
23
24use std::collections::HashMap;
25use std::sync::Arc;
26use std::time::Instant;
27
28use nmbrs_metrics::summaries::binomial_summary::BinomialSummary;
29use nmbrs_metrics::summaries::ewma::Ewma;
30use nmbrs_metrics::summaries::peak_tracker::PeakTracker;
31
32/// Composite key for the active-phase map (SRD-100 §4):
33/// `(exec_id, name, labels)`. `exec_id` (SRD-88) partitions
34/// concurrent in-process executions so two executions running the
35/// same phase don't collide on one slot; `name`+`labels` address a
36/// specific phase iteration within an execution.
37#[derive(Debug, Clone, PartialEq, Eq, Hash)]
38pub struct ActivePhaseId {
39    pub exec_id: u64,
40    pub name: String,
41    pub labels: String,
42}
43
44impl ActivePhaseId {
45    pub fn new(exec_id: u64, name: impl Into<String>, labels: impl Into<String>) -> Self {
46        Self {
47            exec_id,
48            name: name.into(),
49            labels: labels.into(),
50        }
51    }
52}
53
54/// Transitional alias — existing `PhaseKey` type positions resolve
55/// to [`ActivePhaseId`]; construction sites use the struct directly.
56pub type PhaseKey = ActivePhaseId;
57
58/// Log severity level for display coloring.
59///
60/// Variants are ordered from least to most severe, so the
61/// derived `Ord`/`PartialOrd` reads as a "min level" comparison
62/// in the TUI's level filter (`severity >= filter` = "show this
63/// entry").
64#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
65pub enum LogSeverity {
66    Debug,
67    Info,
68    Warn,
69    Error,
70}
71
72/// A log message with severity for display coloring.
73///
74/// Carries the wall-clock instant the entry was produced
75/// so the failure-dump path can surface time-of-arrival
76/// alongside the message — without it, "recent log
77/// messages" reads as an opaque list with no clue which
78/// lines came seconds vs. minutes apart, or which line
79/// was the one closest to the failure.
80#[derive(Clone, Debug)]
81pub struct LogEntry {
82    pub severity: LogSeverity,
83    pub message: String,
84    /// Provenance tag — two orthogonal axes (see
85    /// [`nmbrs_runtime::observer::EventTag`]): the execution-
86    /// lifecycle boundary the entry attaches to (`None` =
87    /// in-flight) and its semantic category. Sinks derive their
88    /// presentation rules from the axes — e.g. the terminal sink
89    /// keeps `PhaseStart`-attached renders out of its scrollback
90    /// (the managed phase-history region shows them instead).
91    pub tag: EventTag,
92    /// Wall-clock at log-entry creation. The dump uses
93    /// this directly; the live TUI ignores it (it has its
94    /// own scroll-based ordering).
95    pub at: std::time::SystemTime,
96}
97
98// `EntryKind` and `PhaseStatus` now live on the canonical
99// [`nmbrs_runtime::scene_tree`] types — re-exported here so existing
100// `crate::state::EntryKind::Phase` references keep working without
101// touching every call site.
102pub use nmbrs_runtime::scene_tree::NodeKind as EntryKind;
103pub use nmbrs_runtime::scene_tree::PhaseStatus;
104pub use nmbrs_runtime::scene_tree::{SceneNode, SceneNodeId, SceneTree};
105
106// Provenance tag for log entries, owned by the observer layer.
107// Re-exported so `crate::state::EventTag` / `EventCategory` read
108// naturally at the sink call sites (mirrors the `EntryKind` /
109// `PhaseStatus` re-export pattern above).
110pub use nmbrs_runtime::observer::{EventCategory, EventTag};
111
112/// End-of-phase metrics snapshot attached to a completed phase.
113/// Mirrors the live progress bar so an expanded tree entry shows the
114/// same fields a non-TUI run would print on stderr.
115#[derive(Clone, Debug, Default)]
116pub struct PhaseSummary {
117    /// Total ops finished during the phase.
118    pub ops_finished: u64,
119    /// Ops that succeeded (no error after retry).
120    pub ops_ok: u64,
121    /// SKIPPED ops (`skips_total`) — excluded from the ok% denominator.
122    pub skips: u64,
123    /// Ops started — used with `ops_finished` to compute active/pending.
124    pub ops_started: u64,
125    /// Errors observed (includes retries).
126    pub errors: u64,
127    /// Retries attempted.
128    pub retries: u64,
129    /// Fibers the phase was run with (concurrency).
130    pub fibers: usize,
131    /// Average ops/s over the phase duration.
132    pub ops_per_sec: f64,
133    /// Service-time percentiles in nanoseconds (latest sample).
134    pub min_nanos: u64,
135    pub p50_nanos: u64,
136    pub p99_nanos: u64,
137    pub max_nanos: u64,
138    /// Primary cursor: name and total extent at phase end.
139    pub cursor_name: String,
140    pub cursor_extent: u64,
141    /// Adapter-specific status counters: (name, total, rate) at phase end.
142    pub adapter_counters: Vec<(String, u64, f64)>,
143    /// Average rows per batch (if batching — else 0).
144    pub rows_per_batch: f64,
145    /// Count of cycles consumed from each input cursor, in the order
146    /// the source dispatch produced them.
147    pub cursors: Vec<(String, u64)>,
148    /// Final relevancy aggregates per metric. Same shape as
149    /// `ActivePhase::relevancy` but captured at phase_completed time.
150    pub relevancy: Vec<(String, f64, f64, u64, usize)>,
151    /// Frozen snapshot of the phase's throughput sparkline at
152    /// completion — a clone of the `BinomialSummary`'s sample
153    /// buffer. The detail block renders this instead of the
154    /// (now-discarded) live `Arc<BinomialSummary>` so a scrolled-
155    /// back completed phase still shows the shape of its
156    /// throughput curve. Empty when the phase produced no
157    /// samples (no `phase_progress` updates).
158    pub throughput_samples: Vec<f64>,
159}
160
161/// Live metrics for the currently running phase.
162#[derive(Clone, Debug)]
163pub struct ActivePhase {
164    pub name: String,
165    pub labels: String,
166    pub cursor_name: String,
167    pub cursor_extent: u64,
168    /// SRD-82 Part 6 — this phase runs as a DAEMON (off the foreground
169    /// budget, open-extent cursor). Excluded from AGGREGATE progress:
170    /// the footer gutter bar averages the NON-daemon phases, since a
171    /// daemon's percent-of-budget is not meaningful run progress.
172    pub daemon: bool,
173    /// Cursor ordinals consumed / cursor extent for a data-driven
174    /// phase (polydat `global_consumed()` / `global_extent()`). Both
175    /// `0` for non-cursor phases (plain `cycles:`). `rows_total > 0`
176    /// drives the row-denominated `rows:{consumed}/{total}` status
177    /// chip in place of the op-denominated `cycles:` chip.
178    pub rows_consumed: u64,
179    pub rows_total: u64,
180    pub fibers: usize,
181    pub started_at: Instant,
182    /// Session-clock reading (see [`RunState::elapsed_secs`]) when this
183    /// phase entered Running — the SINGLE time basis every displayed
184    /// phase timer derives from, so `session_started + leaf-time` always
185    /// equals the session column shown beside it.
186    pub session_started: f64,
187
188    // Snapshot counters (updated by progress thread)
189    pub ops_started: u64,
190    pub ops_finished: u64,
191    pub ops_ok: u64,
192    /// SKIPPED ops (`skips_total`) — excluded from the ok% denominator.
193    pub skips: u64,
194    pub errors: u64,
195    pub retries: u64,
196    pub ops_per_sec: f64,
197
198    // Adapter-specific
199    pub adapter_counters: Vec<(String, u64, f64)>, // (name, total, rate)
200    pub rows_per_batch: f64,
201
202    /// Live relevancy aggregates — one entry per metric (e.g. `recall@10`).
203    /// `(name, window_mean, total_mean, total_count, window_len)`
204    pub relevancy: Vec<(String, f64, f64, u64, usize)>,
205
206    /// Phase-scoped throughput sparkline storage. One sample per
207    /// `phase_progress` tick; capacity caps at the sparkline's
208    /// horizontal cell count so the ring never outgrows the
209    /// render width. Wrapped in `Arc` so cloning `ActivePhase`
210    /// (for the pause snapshot) shares the summary instead of
211    /// duplicating its buffer. See SRD 62 §"Design notes →
212    /// Per-phase sparkline".
213    pub throughput_summary: Arc<BinomialSummary>,
214    /// Smoothed cursor-advance rate. The raw `ops_per_sec` from
215    /// the progress thread bounces frame-to-frame; the EWMA
216    /// gives the detail-block readout a stable number that
217    /// matches what a human would call "the current rate".
218    pub rate_ewma: Arc<Ewma>,
219    /// Rolling max latency over the last 5 seconds — drives the
220    /// `╪` 5s-peak cross-bar marker on the latency range row.
221    pub latency_peak_5s: Arc<PeakTracker>,
222    /// Rolling max latency over the last 10 seconds — drives the
223    /// `╫` 10s-peak cross-bar marker.
224    pub latency_peak_10s: Arc<PeakTracker>,
225
226    /// SRD-100 P2 — the per-phase live render handle. `Some` once the
227    /// executor has attached it (after the activity's metrics/binder
228    /// exist); `None` for the brief window between `phase_starting` and
229    /// the attach, and for phases with no live display fold. The
230    /// consumer-side status renderers fold `active_phases` and call
231    /// [`crate::status_fold::render_phase_status`] on this handle to
232    /// re-derive *this phase's* status line — replacing the retired
233    /// inline-status producer threads + the single `status_render` scalar.
234    pub render: Option<nmbrs_runtime::observer::PhaseRenderHandle>,
235}
236
237/// A single entry rendered in the TUI's phase list — a flat
238/// projection over the scene tree's DFS order. Carries the scene-
239/// node id so callers can cross-reference parent / children, plus
240/// the heavy `PhaseSummary` (only meaningful for completed
241/// phases). Held as a `Cow`-equivalent: produced by walking the
242/// tree at iter time, not stored.
243#[derive(Clone, Debug)]
244pub struct PhaseEntry {
245    pub node_id: SceneNodeId,
246    pub name: String,
247    pub labels: String,
248    pub status: PhaseStatus,
249    pub kind: EntryKind,
250    pub op_count: usize,
251    pub duration_secs: Option<f64>,
252    /// Session cumulative time (seconds) captured at this leaf's
253    /// terminal boundary — the session clock reading when the phase
254    /// completed/failed. Persisted so a finished row keeps showing the
255    /// session time at which it finished. `None` while still running or
256    /// pending (the renderer substitutes the live session clock).
257    pub session_elapsed: Option<f64>,
258    /// Session-clock reading when the phase entered Running; the time
259    /// basis for the leaf timer (`session_elapsed - session_started` =
260    /// displayed duration, exactly).
261    pub session_started: Option<f64>,
262    pub depth: usize,
263    pub summary: Option<PhaseSummary>,
264    /// Stanza op-template names. Populated for `Phase` entries
265    /// from the scene tree at install time. Used by the TUI's
266    /// drilled stanza view (Right arrow on an expanded phase).
267    pub op_names: Vec<String>,
268    /// 1-based pre-map sequence number. Populated only on
269    /// `Phase` entries; `None` for `Scope` rows. Source of truth
270    /// for the `[N/total]` prefix shown next to phase names and
271    /// the `phase X/Y` counter in the TUI header (see
272    /// [`nmbrs_runtime::scene_tree::SceneNode::seq`]).
273    pub seq: Option<usize>,
274}
275
276/// An op-level execution leaf (SRD-63), shown as a timed status line
277/// nested under its parent phase when the op declares `readout: visible`.
278/// Mirrors the phase's status-margin fields so the same renderer/slots
279/// apply, specialized: the count slot is `[seq/total]` within the phase,
280/// the leaf time is this op's execution time, the session time is the
281/// session clock at the op.
282#[derive(Clone)]
283pub struct OpEntry {
284    pub name: String,
285    pub status: PhaseStatus,
286    /// Start of the current execution (for the live timer while running).
287    pub started_at: Instant,
288    /// Session-clock reading at op start — the display time basis (see
289    /// [`ActivePhase::session_started`]).
290    pub session_started: f64,
291    /// Persisted op execution time, set at completion/failure.
292    /// Computed as a session-clock delta (`session_elapsed -
293    /// session_started`) so it reconciles with the session column.
294    pub duration_secs: Option<f64>,
295    /// The op's key measurable, rendered from its `measure:` template at
296    /// completion ("12 sstables", "1.4 GiB"). Shown in the leaf's gutter cell
297    /// ahead of the duration: a reader usually wants what the step PRODUCED,
298    /// and the duration alone cannot say.
299    pub measure: Option<String>,
300    /// Session clock captured at the op's terminal boundary.
301    pub session_elapsed: Option<f64>,
302    /// Arrival order within the parent phase (0-based).
303    pub seq: usize,
304}
305
306/// Top-level run state shared between executor and TUI.
307#[derive(Clone)]
308pub struct RunState {
309    pub workload_file: String,
310    pub scenario_name: String,
311    pub adapter: String,
312    pub started_at: Instant,
313    /// Wall-clock at session start. Captured alongside the
314    /// monotonic `started_at` so the failure-dump path can
315    /// (a) print a UTC header naming the absolute moment
316    /// `0.00000` corresponds to, and (b) compute per-entry
317    /// deltas against it. The monotonic `started_at` stays
318    /// authoritative for elapsed-time comparisons; this one
319    /// is for human-readable display only.
320    pub started_at_utc: std::time::SystemTime,
321    pub profiler: String,
322    pub limit: String,
323
324    /// Canonical scene tree: every concrete phase + scope header
325    /// wired by parent / children pointers. The pre-mapped
326    /// scenario shape lands here once via `scenario_pre_mapped`;
327    /// lifecycle callbacks (`set_phase_running` / `_completed` /
328    /// `_failed`) mutate node statuses in place.
329    pub tree: SceneTree,
330    /// Heavy per-phase metrics produced at completion. Keyed by
331    /// `SceneNodeId` so scope-level renderers can also look up
332    /// child summaries cheaply. Side-map (rather than baked into
333    /// `SceneNode`) so the tree itself stays small / serializable.
334    pub summaries: HashMap<SceneNodeId, PhaseSummary>,
335    /// Latest sysmon sample window (host utilization), when the session-level
336    /// sampler is enabled. Refreshed every sample interval; `None` when the
337    /// sampler is off, so display surfaces add nothing.
338    pub sysmon: Option<nmbrs_runtime::sysmon::SysmonSample>,
339    /// Side-map of the session clock reading captured when each leaf
340    /// reached a terminal state (completed/failed), keyed by
341    /// `SceneNodeId`. Mirrors `summaries`; feeds `PhaseEntry::session_elapsed`
342    /// so a finished row persists the session time at which it finished.
343    pub phase_session_elapsed: HashMap<SceneNodeId, f64>,
344    /// Session clock at each phase's Running transition — see
345    /// [`PhaseEntry::session_started`]. Keyed like
346    /// `phase_session_elapsed`.
347    pub phase_session_started: HashMap<SceneNodeId, f64>,
348    /// Op-level status leaves keyed by their parent phase's `SceneNodeId`,
349    /// in arrival order. Populated only for ops declaring `readout: visible`
350    /// (via the `readout` wrapper's op-lifecycle events); empty otherwise, so
351    /// there is no cost for the common case.
352    pub phase_ops: HashMap<SceneNodeId, Vec<OpEntry>>,
353    /// Denormalized DFS view of `tree` in display order, kept in
354    /// sync by `rebuild_phases()` after every tree mutation. Read
355    /// by the renderer hot paths via `state.phases` indexing —
356    /// rebuilding once per mutation beats walking the tree per
357    /// frame, and the cost is negligible (mutations are a handful
358    /// per phase lifecycle, not per-op).
359    pub phases: Vec<PhaseEntry>,
360
361    /// Phase-count denominator from the pre-map walk —
362    /// pinned at `install_tree` time and never mutated by
363    /// runtime phase materialization. The renderer's `X/N`
364    /// margin display reads this as the stable Y, so an
365    /// operator watching the progress sees a fixed total
366    /// rather than one that drifts upward as `for_each`
367    /// expansion lands new phases at runtime.
368    ///
369    /// When the runtime materializes more phases than the
370    /// pre-map enumerated (param-driven `for_each` whose iter
371    /// source the structural walker couldn't resolve), the
372    /// numerator can exceed `expected_total_phases` — that's
373    /// the honest signal that the planning walk under-counted,
374    /// surfaced as `N/Y` with `N > Y` rather than papered
375    /// over by a moving denominator.
376    pub expected_total_phases: usize,
377
378    /// Every phase currently in flight, keyed by (name, labels).
379    /// Empty between phases. Multi-phase scenarios (stanza-level
380    /// parallelism, multi-activity sessions) populate more than
381    /// one entry. Most read sites today still assume at most one
382    /// running phase — those use [`Self::first_active`] as a
383    /// compatibility shim over the map.
384    pub active_phases: HashMap<PhaseKey, ActivePhase>,
385
386    /// Latency percentiles from last capture (nanoseconds).
387    pub min_nanos: u64,
388    pub p50_nanos: u64,
389    pub p90_nanos: u64,
390    pub p99_nanos: u64,
391    pub p999_nanos: u64,
392    pub max_nanos: u64,
393
394    /// Log ring buffer (last 200 entries). Displayed in TUI log panel.
395    pub log_messages: Vec<LogEntry>,
396    /// Monotonic sequence of every push to `log_messages`, *never*
397    /// decremented. The ring keeps only the last 200 entries; this
398    /// counter keeps growing forever so [`crate::display_sink`]
399    /// implementations can detect "new entries since I last
400    /// drained" without wrestling the ring. A renderer remembers
401    /// the last value it printed; on each tick it looks at
402    /// `log_seq_total - last_printed` and reads that many entries
403    /// off the tail of `log_messages`. Overflow (renderer slower
404    /// than 200 events / poll) is detectable as `delta >
405    /// log_messages.len()` and the renderer can emit a "dropped N
406    /// log lines" notice.
407    pub log_seq_total: u64,
408
409    /// Rolling ops/s history for sparkline (last 120 samples).
410    pub ops_history: Vec<f64>,
411    /// Rolling secondary-counter history for sparkline. The counter
412    /// sampled is whichever adapter counter is first in
413    /// `active.adapter_counters` — only populated when an adapter
414    /// actually reports one, so it's never a hardcoded "rows".
415    pub rows_history: Vec<f64>,
416    /// Display label for the secondary sparkline (e.g. "rows/s" or
417    /// "inserted/s"). `None` when no adapter counter is being tracked.
418    pub rows_sparkline_label: Option<String>,
419    /// Rolling max-latency history (nanoseconds). Sampled every drain
420    /// tick (~250ms). Used by the latency panel to mark windowed peaks
421    /// (e.g., "last 5s", "last 10s") with cross-bar glyphs.
422    pub max_history: Vec<u64>,
423    /// Rolling per-percentile histories, one push per frame delivered
424    /// by the metrics scheduler (≈1 Hz). Fed to the time-series latency
425    /// view and the short-window (5s / 15s max) variants on the
426    /// barchart. Bounded at HISTORY_CAP so memory doesn't grow with
427    /// the run — for true lifetime statistics use the `*_lifetime`
428    /// aggregates below.
429    pub min_history: Vec<u64>,
430    pub p50_history: Vec<u64>,
431    pub p90_history: Vec<u64>,
432    pub p99_history: Vec<u64>,
433    pub p999_history: Vec<u64>,
434
435    /// Set to true when the run is complete.
436    pub finished: bool,
437}
438
439impl RunState {
440    pub fn new(workload_file: &str, scenario_name: &str, adapter: &str) -> Self {
441        Self {
442            workload_file: workload_file.to_string(),
443            scenario_name: scenario_name.to_string(),
444            adapter: adapter.to_string(),
445            started_at: Instant::now(),
446            started_at_utc: std::time::SystemTime::now(),
447            profiler: "off".to_string(),
448            limit: "none".to_string(),
449            tree: SceneTree::new(),
450            summaries: HashMap::new(),
451            sysmon: None,
452            phase_session_elapsed: HashMap::new(),
453            phase_session_started: HashMap::new(),
454            phase_ops: HashMap::new(),
455            phases: Vec::new(),
456            expected_total_phases: 0,
457            active_phases: HashMap::new(),
458            log_messages: Vec::new(),
459            log_seq_total: 0,
460            min_nanos: 0,
461            p50_nanos: 0,
462            p90_nanos: 0,
463            p99_nanos: 0,
464            p999_nanos: 0,
465            max_nanos: 0,
466            ops_history: Vec::new(),
467            rows_history: Vec::new(),
468            rows_sparkline_label: None,
469            max_history: Vec::new(),
470            min_history: Vec::new(),
471            p50_history: Vec::new(),
472            p90_history: Vec::new(),
473            p99_history: Vec::new(),
474            p999_history: Vec::new(),
475            finished: false,
476        }
477    }
478
479    /// Borrow any one currently-running phase, if any exist.
480    /// Compatibility shim for call sites that still assume a single
481    /// running phase (ETA display, header labels, …). Multi-phase
482    /// call sites should iterate [`Self::active_phases`] directly.
483    pub fn first_active(&self) -> Option<&ActivePhase> {
484        self.active_phases.values().next()
485    }
486
487    /// Borrow the active-phase entry matching a specific (name,
488    /// labels) pair — used when the caller already knows which
489    /// phase row it's rendering detail for.
490    pub fn active_phase(&self, name: &str, labels: &str) -> Option<&ActivePhase> {
491        // Compat lookup by (name, labels) — display detail paths only have
492        // a scene-tree row, not yet an exec_id (SRD-100 P1c threads exec_id
493        // through the scene tree). First match: correct for a single
494        // execution; ambiguous under concurrent executions of the same
495        // phase (same as the pre-SRD-100 (name,labels) key), resolved in P1c.
496        self.active_phases
497            .values()
498            .find(|a| a.name == name && a.labels == labels)
499    }
500
501    /// Mutable borrow of the active-phase entry for a specific
502    /// (exec_id, name, labels) key. Used by the observer's progress
503    /// callback to update in place.
504    pub fn active_phase_mut(
505        &mut self,
506        exec_id: u64,
507        name: &str,
508        labels: &str,
509    ) -> Option<&mut ActivePhase> {
510        self.active_phases
511            .get_mut(&ActivePhaseId::new(exec_id, name, labels))
512    }
513
514    /// Push a log entry to the ring buffer (capped at 200).
515    /// `log_seq_total` increments unconditionally so display sinks
516    /// can detect new-since-last-drain without inspecting the ring.
517    pub fn push_log(&mut self, severity: LogSeverity, message: String) {
518        self.push_log_tagged(severity, EventTag::default(), message);
519    }
520
521    /// [`Self::push_log`] with an explicit [`EventTag`]. The tag
522    /// travels with the entry into the ring so the terminal sink
523    /// can derive its filtering (boundary-attached renders out of
524    /// scrollback) from the axes at drain time.
525    pub fn push_log_tagged(&mut self, severity: LogSeverity, tag: EventTag, message: String) {
526        self.push_log_entry(LogEntry {
527            severity,
528            message,
529            tag,
530            at: std::time::SystemTime::now(),
531        });
532    }
533
534    /// Push a pre-built [`LogEntry`] into the ring and return the
535    /// new [`Self::log_seq_total`] it was assigned. The ring stays
536    /// bounded (last 200) — it backs the inspector `log` view, the
537    /// TUI log panel, and the post-run failure dump, none of which
538    /// need unbounded history. The **durable, no-drop scrollback
539    /// stream** is a separate channel the actor feeds in lock-step
540    /// with this push (see
541    /// [`crate::run_state_actor::spawn_run_state_actor`]); the
542    /// returned seq tags the matching stream item so a
543    /// terminal-mode sink can skip lines already emitted elsewhere
544    /// (pre-handoff stderr, or a prior sink's scrollback).
545    pub fn push_log_entry(&mut self, entry: LogEntry) -> u64 {
546        self.log_messages.push(entry);
547        if self.log_messages.len() > 200 {
548            self.log_messages.remove(0);
549        }
550        self.log_seq_total = self.log_seq_total.saturating_add(1);
551        self.log_seq_total
552    }
553
554    /// Push an ops/s sample to the sparkline history (capped at 120).
555    pub fn push_ops_sample(&mut self, ops_per_sec: f64) {
556        self.ops_history.push(ops_per_sec);
557        if self.ops_history.len() > 120 {
558            self.ops_history.remove(0);
559        }
560    }
561
562    /// Push a rows/s sample to the sparkline history.
563    pub fn push_rows_sample(&mut self, rows_per_sec: f64) {
564        self.rows_history.push(rows_per_sec);
565        if self.rows_history.len() > 120 {
566            self.rows_history.remove(0);
567        }
568    }
569
570    /// Replace the scene tree wholesale — called once from the
571    /// observer's `scenario_pre_mapped` hook with the fully
572    /// resolved pre-map. Existing summaries are dropped (they
573    /// never apply across pre-maps).
574    pub fn install_tree(&mut self, tree: SceneTree) {
575        self.tree = tree;
576        self.summaries.clear();
577        self.phase_session_elapsed.clear();
578        self.phase_session_started.clear();
579        self.phase_ops.clear();
580        self.rebuild_phases();
581        // Pin the pre-map's phase count. Read by the margin
582        // renderer as the stable denominator so a refine /
583        // for_each / runtime-materialized phase doesn't drift
584        // the displayed total. The pre-map walker's
585        // `pre_map_only` flag (executor.rs) suppresses sentinel
586        // status mutations during the pre-map pass, so this
587        // count reflects pending phases only.
588        self.expected_total_phases = self.tree.total_phases();
589    }
590
591    /// Add a pending phase to the tree at the synthetic root —
592    /// fallback path for sources that don't pre-map.
593    pub fn add_phase(&mut self, name: &str, labels: &str, _depth: usize) {
594        let root = self.tree.root();
595        self.tree.push(root, EntryKind::Phase, name, labels);
596        self.rebuild_phases();
597    }
598
599    /// Add a visual grouping header at the synthetic root.
600    pub fn add_scope(&mut self, label: &str, _depth: usize) {
601        let root = self.tree.root();
602        self.tree.push(root, EntryKind::Scope, label, "");
603        self.rebuild_phases();
604    }
605
606    /// Resolve the scene-tree node id to mutate for a lifecycle
607    /// transition (SRD-100 P1c). Prefers the dispatch-time
608    /// `scene_node_id` threaded from the executor — race-safe under
609    /// concurrent same-name dispatch — when it addresses a matching
610    /// `Phase` node **in the wanted state**. Falling back to the
611    /// by-name [`SceneTree::find_phase`] (filtered by `want`)
612    /// otherwise covers two cases the threaded id can't:
613    ///
614    /// 1. **Runtime-materialized phases** absent from this tree
615    ///    (pushed by the executor after `scenario_pre_mapped`
616    ///    snapshotted it).
617    /// 2. **Sequential loop re-runs** (`do_while` / `do_until` /
618    ///    phase-level `for_each`) where the executor reuses ONE
619    ///    global node id across iterations (`SceneTree::push` is
620    ///    idempotent by name). After iteration 1 completes, that id
621    ///    is no longer `Pending` — so the next `set_phase_running`
622    ///    falls through to `find_phase(Pending)`, misses, and
623    ///    appends a fresh per-iteration node, preserving the
624    ///    one-row-per-iteration rollup the post-run summary shows.
625    ///
626    /// The `want` filter is what distinguishes (2) — a re-used id
627    /// whose node is already terminal — from a genuine concurrent
628    /// sibling, whose own node is still in the wanted state when its
629    /// transition fires.
630    fn resolve_phase_node(
631        &self,
632        scene_node_id: SceneNodeId,
633        name: &str,
634        labels: &str,
635        want: Option<&PhaseStatus>,
636    ) -> Option<SceneNodeId> {
637        let id_addresses_live_phase = self.tree.nodes.get(scene_node_id).is_some_and(|n| {
638            n.kind == EntryKind::Phase
639                && n.name == name
640                && match want {
641                    // Running/completed transitions: the threaded id wins
642                    // only when its node is in the exact wanted state.
643                    Some(w) => &n.status == w,
644                    // Failure (want=None): the id wins for an *active*
645                    // (Pending/Running) node — the phase that just failed.
646                    // A terminal node at this id is a re-used loop id, so
647                    // fall through to the by-name lookup instead.
648                    None => !matches!(n.status, PhaseStatus::Completed | PhaseStatus::Failed(_)),
649                }
650        });
651        if id_addresses_live_phase {
652            return Some(scene_node_id);
653        }
654        // Fallback: runtime-materialized phase, or a re-used loop id whose node
655        // is no longer in the wanted state.
656        match want {
657            // Failure: target the LIVE iteration — Running, else Pending — so a
658            // failing loop iteration N marks ITS row, not iteration 1's already
659            // -completed one (`find_phase(.., None)` returns the first-by-DFS
660            // node, which is the stale terminal row). Last-resort any-status
661            // match keeps a degenerate single-row tree working.
662            None => self
663                .tree
664                .find_phase(name, labels, Some(&PhaseStatus::Running))
665                .or_else(|| {
666                    self.tree
667                        .find_phase(name, labels, Some(&PhaseStatus::Pending))
668                })
669                .or_else(|| self.tree.find_phase(name, labels, None)),
670            some => self.tree.find_phase(name, labels, some),
671        }
672    }
673
674    /// Mark a phase as running, keyed by the dispatch-time
675    /// `scene_node_id` (SRD-100 P1c). Pre-mapped phases flip their
676    /// own node directly; a phase the pre-map never enumerated is
677    /// pushed dynamically so it still gets a tree slot.
678    pub fn set_phase_running(
679        &mut self,
680        scene_node_id: SceneNodeId,
681        name: &str,
682        labels: &str,
683        op_count: usize,
684    ) {
685        let session_now = self.elapsed_secs();
686        if let Some(id) =
687            self.resolve_phase_node(scene_node_id, name, labels, Some(&PhaseStatus::Pending))
688        {
689            self.tree.set_phase_running_at(id, op_count);
690            self.phase_session_started.insert(id, session_now);
691        } else {
692            // Not found — add dynamically and mark running. Phases
693            // that weren't pre-mapped (e.g. unresolvable for_each
694            // at pre-map time) still need a tree slot.
695            let root = self.tree.root();
696            let id = self.tree.push(root, EntryKind::Phase, name, labels);
697            self.tree.set_phase_running_at(id, op_count);
698            self.phase_session_started.insert(id, session_now);
699        }
700        self.rebuild_phases();
701    }
702
703    /// Mark a phase as completed and attach a metrics summary,
704    /// keyed by the dispatch-time `scene_node_id` (SRD-100 P1c).
705    /// Final per-op timing leaves for a phase at its completion —
706    /// the durable form of the footer's SRD-63 op rows, preserved
707    /// into scrollback under the ✓ outcome block. Terminal ops carry
708    /// their execution time and session finish-stamp; an op still
709    /// mid-flight at phase end (a cancelled daemon probe) shows `—`.
710    /// Empty when the phase declared no `readout: visible` ops.
711    /// Returns `(line, duration_cell)` pairs: the leaf body carries
712    /// icon · name · `[i/N]` · `@ session-stamp`; the node's own
713    /// execution DURATION is the second element, rendered as the
714    /// leaf row's default gutter cell (SRD-92: a visible node with
715    /// no declared gutter gets its execution time as the cell —
716    /// the scannable per-step time ledger). Single placement: the
717    /// duration appears only in the cell, the session stamp only
718    /// in the body.
719    pub fn final_op_leaves(&self, name: &str, labels: &str) -> Vec<(String, String)> {
720        let node_id = match self.phases.iter().find(|e| {
721            e.name == name && e.labels == labels && matches!(e.status, PhaseStatus::Running)
722        }) {
723            Some(e) => e.node_id,
724            None => return Vec::new(),
725        };
726        let ops = match self.phase_ops.get(&node_id) {
727            Some(ops) if !ops.is_empty() => ops,
728            _ => return Vec::new(),
729        };
730        let total = ops.len();
731        ops.iter()
732            .map(|op| {
733                let icon = match &op.status {
734                    PhaseStatus::Completed => "✓",
735                    PhaseStatus::Failed(_) => "✗",
736                    _ => "—",
737                };
738                // Same form as the live leaf: what the step produced, then how
739                // long it took. The settled scrollback row is where this matters
740                // most — it is the copy a reader comes back to.
741                let duration_cell = op
742                    .duration_secs
743                    .map(|d| match op.measure.as_deref() {
744                        Some(m) => format!("[{m}] {}", crate::widgets::format_dur_compact(d)),
745                        None => crate::widgets::format_dur_compact(d),
746                    })
747                    .unwrap_or_else(|| "—".to_string());
748                let stamp = match op.session_elapsed {
749                    Some(v) => format!("  @ {}", crate::widgets::format_dur_compact(v)),
750                    None => String::new(),
751                };
752                let mut line = format!(
753                    "    {icon} {name}  [{seq}/{total}]{stamp}",
754                    name = op.name,
755                    seq = op.seq + 1,
756                );
757                if let PhaseStatus::Failed(err) = &op.status {
758                    line.push_str("  ");
759                    line.push_str(err);
760                }
761                (line, duration_cell)
762            })
763            .collect()
764    }
765
766    pub fn set_phase_completed(
767        &mut self,
768        scene_node_id: SceneNodeId,
769        name: &str,
770        labels: &str,
771        duration_secs: f64,
772        summary: PhaseSummary,
773    ) {
774        // Capture the session clock BEFORE the mutable-borrow block so a
775        // finished leaf persists the session time at which it finished.
776        let session_now = self.elapsed_secs();
777        // `skipped_phases=elide|prune`: a FULLY-SKIPPED phase (every op
778        // `if:`-gated off, nothing measured) leaves no completed-tree
779        // entry — remove its node instead of folding it in. `mark` (the
780        // default) keeps it, rendered with the runtime's ⊘ outcome.
781        let fully_skipped = summary.skips > 0
782            && summary.ops_finished > 0
783            && summary.skips >= summary.ops_finished
784            && summary.ops_ok == 0
785            && summary.errors == 0;
786        if fully_skipped
787            && matches!(
788                nmbrs_runtime::observer::skipped_phase_display(),
789                nmbrs_runtime::observer::SkippedPhaseDisplay::Elide
790                    | nmbrs_runtime::observer::SkippedPhaseDisplay::Prune
791            )
792        {
793            if let Some(id) =
794                self.resolve_phase_node(scene_node_id, name, labels, Some(&PhaseStatus::Running))
795            {
796                self.tree.remove_node(id);
797                self.summaries.remove(&id);
798                self.phase_session_started.remove(&id);
799                self.rebuild_phases();
800            }
801            return;
802        }
803        if let Some(id) =
804            self.resolve_phase_node(scene_node_id, name, labels, Some(&PhaseStatus::Running))
805        {
806            // Displayed duration is a session-clock delta so
807            // `session_started + duration == session_elapsed` holds
808            // exactly on every rendered row. The executor-measured
809            // `duration_secs` is the fallback when the start was never
810            // observed (runtime-materialized phase).
811            let display_duration = self
812                .phase_session_started
813                .get(&id)
814                .map(|s| (session_now - s).max(0.0))
815                .unwrap_or(duration_secs);
816            self.tree.set_phase_completed_at(id, display_duration);
817            self.summaries.insert(id, summary);
818            self.phase_session_elapsed.insert(id, session_now);
819            self.rebuild_phases();
820        }
821    }
822
823    /// Mark a phase as failed, keyed by the dispatch-time
824    /// `scene_node_id` (SRD-100 P1c).
825    pub fn set_phase_failed(
826        &mut self,
827        scene_node_id: SceneNodeId,
828        name: &str,
829        labels: &str,
830        error: &str,
831    ) {
832        let session_now = self.elapsed_secs();
833        if let Some(id) = self.resolve_phase_node(scene_node_id, name, labels, None) {
834            self.tree.set_phase_failed_at(id, error);
835            self.phase_session_elapsed.insert(id, session_now);
836            self.rebuild_phases();
837        }
838    }
839
840    /// An op-level status leaf started (SRD-63). Creates or re-arms the entry
841    /// (keyed by name within the parent phase) as Running with a fresh timer.
842    pub fn op_starting(&mut self, parent: SceneNodeId, name: &str) {
843        let session_now = self.elapsed_secs();
844        let ops = self.phase_ops.entry(parent).or_default();
845        if let Some(e) = ops.iter_mut().find(|e| e.name == name) {
846            e.status = PhaseStatus::Running;
847            e.started_at = Instant::now();
848            e.session_started = session_now;
849            e.duration_secs = None;
850            e.session_elapsed = None;
851        } else {
852            let seq = ops.len();
853            ops.push(OpEntry {
854                measure: None,
855                name: name.to_string(),
856                status: PhaseStatus::Running,
857                started_at: Instant::now(),
858                session_started: session_now,
859                duration_secs: None,
860                session_elapsed: None,
861                seq,
862            });
863        }
864    }
865
866    /// An op-level status leaf completed; persists its execution time and the
867    /// session clock at completion.
868    /// Record an op's key measurable. Arrives just before completion, so the
869    /// leaf row has it the moment it settles.
870    pub fn op_measure(&mut self, parent: SceneNodeId, op_name: &str, text: &str) {
871        if let Some(ops) = self.phase_ops.get_mut(&parent)
872            && let Some(op) = ops.iter_mut().find(|o| o.name == op_name)
873        {
874            op.measure = Some(text.to_string());
875        }
876    }
877
878    pub fn op_completed(&mut self, parent: SceneNodeId, name: &str, duration_secs: f64) {
879        let session_now = self.elapsed_secs();
880        if let Some(ops) = self.phase_ops.get_mut(&parent)
881            && let Some(e) = ops.iter_mut().find(|e| e.name == name)
882        {
883            e.status = PhaseStatus::Completed;
884            // Session-clock delta, not the executor's own measure —
885            // see PhaseEntry::session_started. Executor value is the
886            // fallback for a start that was never observed.
887            let _ = duration_secs;
888            e.duration_secs = Some((session_now - e.session_started).max(0.0));
889            e.session_elapsed = Some(session_now);
890        }
891    }
892
893    /// An op-level status leaf failed; freezes its elapsed time and session clock.
894    pub fn op_failed(&mut self, parent: SceneNodeId, name: &str, error: &str) {
895        let session_now = self.elapsed_secs();
896        if let Some(ops) = self.phase_ops.get_mut(&parent)
897            && let Some(e) = ops.iter_mut().find(|e| e.name == name)
898        {
899            e.duration_secs = Some((session_now - e.session_started).max(0.0));
900            e.status = PhaseStatus::Failed(error.to_string());
901            e.session_elapsed = Some(session_now);
902        }
903    }
904
905    /// Elapsed time since run started.
906    pub fn elapsed_secs(&self) -> f64 {
907        self.started_at.elapsed().as_secs_f64()
908    }
909
910    /// The uncolored status-margin body (`session · [n/N] · leaf`)
911    /// for the CURRENT state. The run-state actor stamps this onto
912    /// every scrollback line at Log-command processing time, so a
913    /// line's gutter is computed from exactly the state that
914    /// preceded it in the command stream — it can never disagree
915    /// with the event the line describes (the old render-time
916    /// margin was one snapshot for a whole drained batch, and raced
917    /// the very transitions the lines reported).
918    pub fn margin_body_stamp(&self) -> String {
919        let secs = self.elapsed_secs();
920        let phase_only: Vec<_> = self
921            .phases
922            .iter()
923            .filter(|p| matches!(p.kind, EntryKind::Phase))
924            .collect();
925        let total = self.expected_total_phases;
926        let running = phase_only
927            .iter()
928            .find(|p| matches!(p.status, PhaseStatus::Running));
929        let running_seq = running.and_then(|p| p.seq);
930        let latest_done_seq = phase_only
931            .iter()
932            .filter(|p| !matches!(p.status, PhaseStatus::Pending))
933            .filter_map(|p| p.seq)
934            .max();
935        let fallback_done = phase_only
936            .iter()
937            .filter(|p| !matches!(p.status, PhaseStatus::Pending))
938            .count();
939        let count = match (running_seq, latest_done_seq, total) {
940            (Some(s), _, n) if n > 0 => format!("[{s}/{n}]"),
941            (None, Some(s), n) if n > 0 => format!("[{s}/{n}]"),
942            (None, None, n) if n > 0 && fallback_done > 0 => format!("[{fallback_done}/{n}]"),
943            (_, _, n) if n > 0 => format!("[0/{n}]"),
944            _ => "[-/-]".to_string(),
945        };
946        let leaf = running
947            .and_then(|p| self.active_phase(&p.name, &p.labels))
948            .map(|a| (secs - a.session_started).max(0.0));
949        crate::widgets::margin_body(total, &count, leaf, Some(secs))
950    }
951
952    /// Rebuild the denormalized `phases` view from the current
953    /// tree. Called after every mutation that affects the DFS
954    /// order or any node's display fields.
955    fn rebuild_phases(&mut self) {
956        self.phases = self
957            .tree
958            .dfs()
959            .filter(|n| n.kind != EntryKind::Root)
960            .map(|n| PhaseEntry {
961                node_id: n.id,
962                name: n.name.clone(),
963                labels: n.labels.clone(),
964                status: n.status.clone(),
965                kind: n.kind,
966                op_count: n.op_count,
967                duration_secs: n.duration_secs,
968                // SceneNode depths count the synthetic root as 1 —
969                // subtract so top-level scenario entries land at
970                // depth 0 (matching pre-tree behavior).
971                depth: n.depth.saturating_sub(1),
972                summary: self.summaries.get(&n.id).cloned(),
973                session_elapsed: self.phase_session_elapsed.get(&n.id).copied(),
974                session_started: self.phase_session_started.get(&n.id).copied(),
975                op_names: n.op_names.clone(),
976                seq: n.seq,
977            })
978            .collect();
979    }
980
981    /// Total `Phase` entries in the pre-mapped scene tree —
982    /// denominator for the `[N/total]` and `phase X/Y` displays.
983    pub fn total_phases(&self) -> usize {
984        self.tree.total_phases()
985    }
986}
987
988#[cfg(test)]
989mod resolve_tests {
990    //! SRD-100 P1c — `resolve_phase_node` is the reconciliation between
991    //! id-keyed routing (race-safe under concurrent distinct-node dispatch)
992    //! and the by-name fallback (runtime-materialized phases + sequential
993    //! loop id-reuse). These drive it through the public `set_phase_*` API.
994    use super::*;
995
996    /// A two-cell distinct-node tree: two same-name `p` phases under DISTINCT
997    /// parent scopes (the topology scenario-level `for_each` /
998    /// `for_combinations` / nesting produce, where each cell gets its own id).
999    fn two_cell_tree() -> (SceneTree, SceneNodeId, SceneNodeId) {
1000        let mut t = SceneTree::new();
1001        let s1 = t.push(t.root(), EntryKind::Scope, "x=1", "");
1002        let p1 = t.push(s1, EntryKind::Phase, "p", "x=1");
1003        let s2 = t.push(t.root(), EntryKind::Scope, "x=2", "");
1004        let p2 = t.push(s2, EntryKind::Phase, "p", "x=2");
1005        (t, p1, p2)
1006    }
1007
1008    fn row(s: &RunState, id: SceneNodeId) -> &PhaseEntry {
1009        s.phases
1010            .iter()
1011            .find(|e| e.node_id == id)
1012            .expect("row for id")
1013    }
1014
1015    fn running_count(s: &RunState) -> usize {
1016        s.phases
1017            .iter()
1018            .filter(|e| matches!(e.status, PhaseStatus::Running))
1019            .count()
1020    }
1021
1022    /// The id-keyed-wins branch: two distinct same-name nodes, completed in
1023    /// REVERSED order, each keep their own op_count / duration / status. With
1024    /// the pre-P1c by-name routing the first completion would land on the
1025    /// first-DFS node and mis-attribute.
1026    #[test]
1027    fn id_keyed_wins_under_reordered_completion() {
1028        let (tree, p1, p2) = two_cell_tree();
1029        let mut s = RunState::new("", "", "");
1030        s.install_tree(tree);
1031        s.set_phase_running(p1, "p", "x=1", 3);
1032        s.set_phase_running(p2, "p", "x=2", 7);
1033        s.set_phase_completed(p2, "p", "x=2", 10.0, PhaseSummary::default());
1034        s.set_phase_completed(p1, "p", "x=1", 5.0, PhaseSummary::default());
1035        // Displayed durations are session-clock deltas (NOT the
1036        // executor-passed 10.0/5.0): each row must reconcile exactly
1037        // against its own session columns, the single-time-basis
1038        // invariant the gutter readout depends on.
1039        for p in [p1, p2] {
1040            let r = row(&s, p);
1041            let d = r.duration_secs.expect("completed row has duration");
1042            let reconciled = r.session_elapsed.expect("session_elapsed set")
1043                - r.session_started.expect("session_started set");
1044            assert!(
1045                (d - reconciled).abs() < 1e-9,
1046                "duration {d} must equal session_elapsed - session_started {reconciled}"
1047            );
1048        }
1049        assert_eq!(row(&s, p1).op_count, 3);
1050        assert_eq!(row(&s, p2).op_count, 7);
1051        assert!(matches!(row(&s, p1).status, PhaseStatus::Completed));
1052        assert!(matches!(row(&s, p2).status, PhaseStatus::Completed));
1053    }
1054
1055    /// Sequential loop id-reuse: the executor reuses ONE node id across
1056    /// iterations (push is idempotent by name). Iteration 2's `running`
1057    /// falls through to append a fresh live row; a FAILURE on iteration 2
1058    /// (reported with the reused, now-Completed id) must mark the LIVE row,
1059    /// leaving iteration 1's completed row intact and nothing stranded
1060    /// Running. Fails against the naive `find_phase(.., None)` failure
1061    /// fallback (which grabs the first-DFS terminal row).
1062    #[test]
1063    fn reused_loop_id_appends_and_failure_targets_live_row() {
1064        // The looped phase sits under a scope (a `do_while` / `for_each`
1065        // header), as it does in a real run — so the append-on-miss fallback
1066        // (which pushes under root) yields a node distinct from the reused
1067        // scoped one, rather than colliding with it via push idempotency.
1068        let mut t = SceneTree::new();
1069        let scope = t.push(t.root(), EntryKind::Scope, "do_while", "");
1070        let p = t.push(scope, EntryKind::Phase, "p", "");
1071        let mut s = RunState::new("", "", "");
1072        s.install_tree(t);
1073        // iteration 1 reuses the pre-mapped node `p`
1074        s.set_phase_running(p, "p", "i=1", 1);
1075        s.set_phase_completed(p, "p", "i=1", 1.0, PhaseSummary::default());
1076        // iteration 2 reuses the same id (now Completed) -> append a live row
1077        s.set_phase_running(p, "p", "i=2", 1);
1078        assert_eq!(
1079            running_count(&s),
1080            1,
1081            "iteration 2 appended a distinct live row"
1082        );
1083        // iteration 2 fails, reported with the reused id `p`
1084        s.set_phase_failed(p, "p", "i=2", "boom");
1085        assert!(
1086            matches!(row(&s, p).status, PhaseStatus::Completed),
1087            "iteration 1's row stays Completed, got {:?}",
1088            row(&s, p).status
1089        );
1090        let failed = s
1091            .phases
1092            .iter()
1093            .filter(|e| matches!(e.status, PhaseStatus::Failed(_)))
1094            .count();
1095        assert_eq!(failed, 1, "exactly the live iteration-2 row failed");
1096        assert_eq!(running_count(&s), 0, "no row left stranded Running");
1097    }
1098}
1099
1100#[cfg(test)]
1101mod measure_tests {
1102    use super::*;
1103
1104    /// A settled leaf row carries WHAT the step produced ahead of how long it
1105    /// took. Duration alone answers "did it hang" — the less interesting
1106    /// question once a step is done.
1107    #[test]
1108    fn settled_leaf_shows_measure_before_duration() {
1109        let mut st = RunState::new("w.yaml", "s", "stdout");
1110        let node: SceneNodeId = 1;
1111        st.phases.push(PhaseEntry {
1112            node_id: node,
1113            name: "finalize".into(),
1114            labels: String::new(),
1115            status: PhaseStatus::Running,
1116            kind: EntryKind::Phase,
1117            op_count: 1,
1118            duration_secs: None,
1119            session_elapsed: None,
1120            session_started: None,
1121            depth: 0,
1122            summary: None,
1123            op_names: Vec::new(),
1124            seq: None,
1125        });
1126        st.op_starting(node, "read_sstables");
1127        st.op_measure(node, "read_sstables", "12 sst");
1128        st.op_completed(node, "read_sstables", 0.3);
1129
1130        let leaves = st.final_op_leaves("finalize", "");
1131        assert_eq!(leaves.len(), 1);
1132        let (_, cell) = &leaves[0];
1133        assert!(
1134            cell.starts_with("[12 sst] "),
1135            "measure precedes the duration in the gutter cell: {cell:?}"
1136        );
1137    }
1138
1139    /// An op with no `measure:` renders exactly as before — the feature is
1140    /// additive, and every existing workload keeps its current output.
1141    #[test]
1142    fn leaf_without_measure_is_unchanged() {
1143        let mut st = RunState::new("w.yaml", "s", "stdout");
1144        let node: SceneNodeId = 1;
1145        st.phases.push(PhaseEntry {
1146            node_id: node,
1147            name: "finalize".into(),
1148            labels: String::new(),
1149            status: PhaseStatus::Running,
1150            kind: EntryKind::Phase,
1151            op_count: 1,
1152            duration_secs: None,
1153            session_elapsed: None,
1154            session_started: None,
1155            depth: 0,
1156            summary: None,
1157            op_names: Vec::new(),
1158            seq: None,
1159        });
1160        st.op_starting(node, "plain");
1161        st.op_completed(node, "plain", 0.3);
1162
1163        let (_, cell) = &st.final_op_leaves("finalize", "")[0];
1164        assert!(
1165            !cell.contains('['),
1166            "no brackets without a measure: {cell:?}"
1167        );
1168    }
1169}