Skip to main content

nmbrs_runtime/
readout_context.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! [`ActivityReadoutContext`] — concrete `ReadoutContext`
5//! impl built from the activity-side data the
6//! ✓ DONE block already gathers.
7//!
8//! Push 1 surface only. Built up by `nmbrs-runtime::activity`
9//! at end-of-activity right before invoking the `phase_outcome`
10//! readout. Each later push grows this struct as new
11//! built-ins (and new `ReadoutContext` methods) arrive.
12//!
13//! Owned, not borrowed: every field is computed at the call
14//! site (counter snapshots, the rendered chip string, the
15//! depth-indent string) and parked here for the readout's
16//! duration. This keeps the readout call free of borrow
17//! plumbing through the activity's locks.
18
19use std::sync::Arc;
20use std::sync::atomic::Ordering;
21
22use crate::lifecycle::EventType;
23use crate::readouts::{LifecycleState, ReadoutContext};
24
25/// Snapshot of everything `phase_outcome` needs to render at
26/// `Lod::Labeled / ContentMode::Value`. Constructed at
27/// end-of-activity in `nmbrs-runtime::activity`; thrown
28/// away after the render returns.
29pub struct ActivityReadoutContext {
30    pub phase_name: String,
31    pub phase_seq: Option<(usize, usize)>,
32    pub phase_labels: String,
33    pub cycles_completed: u64,
34    pub cycles_total: u64,
35    pub ops_ok: u64,
36    /// SKIPPED ops (`skips_total`) — excluded from the ok% denominator
37    /// (a skip is neither a success nor a failure).
38    pub skips: u64,
39    pub errors: u64,
40    pub retries: u64,
41    pub concurrency: usize,
42    pub elapsed_secs: f64,
43    pub consumed: u64,
44    /// Cursor ordinals consumed and the cursor's extent, for a phase
45    /// with a declared cursor; both `0` otherwise. A batched phase
46    /// strides several rows per op, so its completion fraction is
47    /// `rows_consumed / rows_total`, never ops over the row extent
48    /// ([`ReadoutContext::progress_fraction`]).
49    pub rows_consumed: u64,
50    pub rows_total: u64,
51    pub status_metric_chips: String,
52    pub depth_indent: String,
53    pub use_color: bool,
54    /// Snapshot of the activity's memo at context-build time.
55    /// Empty when no `memo:` wrapper is active on any op.
56    pub memo: String,
57    /// SRD-76 / SRD-82 Part 1 — the terminal two-axis outcome. The
58    /// executor sets this when it installs the
59    /// [`crate::phase_outcome::PhaseOutcome`] on the scene tree,
60    /// before firing the on_phase_end binder.
61    pub outcome: crate::phase_outcome::Outcome,
62    /// SRD-76 — chronologically ordered error list. Empty
63    /// for `Completed`/`Skipped`; non-empty for `Failed`.
64    /// Drives the failure-flavoured rendering of the
65    /// [`crate::readouts::builtins::phase_outcome`] readout.
66    pub outcome_errors: Vec<crate::phase_outcome::PhaseErrorDetail>,
67    /// SRD-76 — cursor-resume payload, when the phase
68    /// supports it. `None` for the common case.
69    pub outcome_resume_cursor: Option<crate::phase_outcome::ResumeCursor>,
70    /// True for a daemon (open-ended) phase: there is no "done" to
71    /// meter, so completion renders no percentage (SRD-92 — the
72    /// same rule the live meter slot follows). Without this the
73    /// trait-default `false` let `progress_fraction()` fall through
74    /// to the cycles basis and a stopped daemon printed a
75    /// meaningless `N%` (cycles over its wall-clock ceiling).
76    pub open_ended: bool,
77}
78
79impl ReadoutContext for ActivityReadoutContext {
80    fn subject_name(&self) -> &str {
81        &self.phase_name
82    }
83    fn subject_seq(&self) -> Option<(usize, usize)> {
84        self.phase_seq
85    }
86    fn subject_labels(&self) -> &str {
87        &self.phase_labels
88    }
89    fn open_ended(&self) -> bool {
90        self.open_ended
91    }
92    fn cycles_completed(&self) -> u64 {
93        self.cycles_completed
94    }
95    fn cycles_total(&self) -> u64 {
96        self.cycles_total
97    }
98    fn ops_ok(&self) -> u64 {
99        self.ops_ok
100    }
101    fn skips(&self) -> u64 {
102        self.skips
103    }
104    fn errors(&self) -> u64 {
105        self.errors
106    }
107    fn retries(&self) -> u64 {
108        self.retries
109    }
110    fn concurrency(&self) -> usize {
111        self.concurrency
112    }
113    fn elapsed_secs(&self) -> f64 {
114        self.elapsed_secs
115    }
116    fn consumed(&self) -> u64 {
117        self.consumed
118    }
119    fn rows_consumed(&self) -> u64 {
120        self.rows_consumed
121    }
122    fn rows_total(&self) -> u64 {
123        self.rows_total
124    }
125    fn status_metric_chips(&self) -> String {
126        self.status_metric_chips.clone()
127    }
128    fn depth_indent(&self) -> &str {
129        &self.depth_indent
130    }
131    fn use_color(&self) -> bool {
132        self.use_color
133    }
134    fn event(&self) -> EventType {
135        EventType::PhaseEnd
136    }
137    fn subject_state(&self) -> LifecycleState {
138        // Mirror the outcome status onto the lifecycle axis
139        // so existing consumers that branch on `subject_state`
140        // see Failed when the phase failed (today they'd see
141        // Completed because the binder fired before the
142        // executor recorded the failure). SRD-76 unifies
143        // the two surfaces.
144        match self.outcome.validity {
145            crate::phase_outcome::Validity::Succeeded => LifecycleState::Completed,
146            crate::phase_outcome::Validity::Failed => LifecycleState::Failed(
147                self.outcome_errors
148                    .first()
149                    .map(|e| e.message.clone())
150                    .unwrap_or_else(|| "phase failed".into()),
151            ),
152        }
153    }
154    fn phase_memo(&self) -> &str {
155        &self.memo
156    }
157    fn outcome(&self) -> crate::phase_outcome::Outcome {
158        self.outcome.clone()
159    }
160    fn outcome_errors(&self) -> &[crate::phase_outcome::PhaseErrorDetail] {
161        &self.outcome_errors
162    }
163    fn outcome_resume_cursor(&self) -> Option<&crate::phase_outcome::ResumeCursor> {
164        self.outcome_resume_cursor.as_ref()
165    }
166}
167
168/// Per-event context for lifecycle fires (Push 9a):
169/// `on_session_start` / `on_session_end`,
170/// `on_phase_start`, `on_each_start` / `on_each_end`,
171/// `on_scope_start` / `on_scope_end`.
172///
173/// Carries just the fields a structural readout
174/// (`scope_header`, `session_banner`, `each_close`, …)
175/// needs — subject name, root-first labels, depth indent,
176/// colour flag, plus the firing event so a wildcard-bound
177/// readout can branch.
178///
179/// Counter-shaped methods all return zero / empty since
180/// lifecycle readouts don't depend on per-cycle progress;
181/// the `Default` impl on the trait handles those.
182pub struct LifecycleContext {
183    pub event: crate::lifecycle::EventType,
184    pub subject_name: String,
185    pub subject_labels: String,
186    pub depth_indent: String,
187    pub use_color: bool,
188    /// SRD-106 — the session id the `stick_session` rung
189    /// re-attached to; empty everywhere except the SessionStart
190    /// fire of a stick-engaged run. Read by `session_notice`.
191    pub stick_reattached: String,
192}
193
194impl ReadoutContext for LifecycleContext {
195    fn subject_name(&self) -> &str {
196        &self.subject_name
197    }
198    fn subject_seq(&self) -> Option<(usize, usize)> {
199        None
200    }
201    fn subject_labels(&self) -> &str {
202        &self.subject_labels
203    }
204    fn cycles_completed(&self) -> u64 {
205        0
206    }
207    fn cycles_total(&self) -> u64 {
208        0
209    }
210    fn ops_ok(&self) -> u64 {
211        0
212    }
213    fn errors(&self) -> u64 {
214        0
215    }
216    fn retries(&self) -> u64 {
217        0
218    }
219    fn concurrency(&self) -> usize {
220        0
221    }
222    fn elapsed_secs(&self) -> f64 {
223        0.0
224    }
225    fn consumed(&self) -> u64 {
226        0
227    }
228    fn status_metric_chips(&self) -> String {
229        String::new()
230    }
231    fn depth_indent(&self) -> &str {
232        &self.depth_indent
233    }
234    fn use_color(&self) -> bool {
235        self.use_color
236    }
237    fn event(&self) -> crate::lifecycle::EventType {
238        self.event
239    }
240    fn stick_reattached_session(&self) -> &str {
241        &self.stick_reattached
242    }
243    fn subject_state(&self) -> LifecycleState {
244        // Lifecycle events fire at the boundary; the
245        // subject is in transition. `Running` is the safe
246        // default for `on_*_start` (the subject is now
247        // in flight); `_end` events technically transition
248        // to `Completed` but the readouts that fire here
249        // (scope_header, session_banner, etc.) don't
250        // branch on subject_state anyway, so a single
251        // default keeps things simple.
252        LifecycleState::Running
253    }
254}
255
256/// Per-tick context for the inline-status refresh thread
257/// (Push 2). Identifies as [`EventType::Update`]; carries a
258/// monotonic refresh tick for spinner cycling, the full
259/// activity name with leaf coord, and pre-formatted
260/// adapter / batch tails (the iteration over registered
261/// dispensers stays in the surface for now — Push 4
262/// migrates the trait to expose the typed iterator).
263pub struct InlineRefreshContext {
264    pub phase_name: String,
265    pub activity_name: String,
266    pub phase_seq: Option<(usize, usize)>,
267    pub phase_labels: String,
268    pub cycles_completed: u64,
269    pub cycles_total: u64,
270    pub ops_started: u64,
271    pub ops_finished: u64,
272    pub ops_ok: u64,
273    /// SKIPPED ops (`skips_total`) — `if:`-gated ops that ran no
274    /// adapter call. Excluded from the `ok%` denominator: a skip is
275    /// neither a success nor a failure.
276    pub skips: u64,
277    pub errors: u64,
278    pub retries: u64,
279    /// SRD-91 attempt-level tallies — successful and failed
280    /// RESOLVED attempts (both observed at attempt end).
281    /// `attempt_ok / (attempt_ok + attempt_failed)` is the
282    /// attempt success rate the status line surfaces beside the
283    /// result-level `ok%`; in-flight attempts are excluded so it
284    /// doesn't skew low the way the dispatch-time counter would.
285    pub attempt_ok: u64,
286    pub attempt_failed: u64,
287    pub concurrency: usize,
288    pub elapsed_secs: f64,
289    pub consumed: u64,
290    /// Cursor ordinals consumed / cursor extent for a data-driven
291    /// phase (polydat `global_consumed()` / `global_extent()`).
292    /// Both `0` for non-cursor phases (plain `cycles:`), where the
293    /// display keeps the op-denominated `cycles:` chip. `rows_total
294    /// > 0` selects the row-denominated `rows:{consumed}/{total}`
295    /// > chip + rows/s rate.
296    pub rows_consumed: u64,
297    pub rows_total: u64,
298    pub status_metric_chips: String,
299    pub adapter_counters_text: String,
300    pub batch_info_text: String,
301    pub depth_indent: String,
302    pub refresh_tick: u64,
303    pub use_color: bool,
304    /// Snapshot of the activity's memo at tick build time.
305    /// Empty when no `memo:` wrapper has published anything.
306    pub memo: String,
307    /// Derived-progress override snapshot (see
308    /// [`crate::activity::ActivityMetrics::progress_override`]).
309    pub progress_override: Option<f64>,
310    /// Producer-elapsed seconds recorded with the override — the
311    /// measured-basis ETA's time denominator.
312    pub progress_override_elapsed: Option<f64>,
313    /// Open-ended subject (daemon / background poll): no progress
314    /// meter; latency summary renders in its place.
315    pub open_ended: bool,
316    /// Live service-time percentiles (nanos) from the activity's
317    /// timer, for the open-ended latency chip. 0 = no data yet.
318    pub lat_p50_nanos: u64,
319    pub lat_p99_nanos: u64,
320}
321
322impl ReadoutContext for InlineRefreshContext {
323    fn subject_name(&self) -> &str {
324        &self.phase_name
325    }
326    fn activity_name(&self) -> &str {
327        &self.activity_name
328    }
329    fn subject_seq(&self) -> Option<(usize, usize)> {
330        self.phase_seq
331    }
332    fn subject_labels(&self) -> &str {
333        &self.phase_labels
334    }
335    fn cycles_completed(&self) -> u64 {
336        self.cycles_completed
337    }
338    fn cycles_total(&self) -> u64 {
339        self.cycles_total
340    }
341    fn ops_started(&self) -> u64 {
342        self.ops_started
343    }
344    fn ops_finished(&self) -> u64 {
345        self.ops_finished
346    }
347    fn ops_ok(&self) -> u64 {
348        self.ops_ok
349    }
350    fn skips(&self) -> u64 {
351        self.skips
352    }
353    fn errors(&self) -> u64 {
354        self.errors
355    }
356    fn retries(&self) -> u64 {
357        self.retries
358    }
359    fn attempt_ok(&self) -> u64 {
360        self.attempt_ok
361    }
362    fn attempt_failed(&self) -> u64 {
363        self.attempt_failed
364    }
365    fn concurrency(&self) -> usize {
366        self.concurrency
367    }
368    fn elapsed_secs(&self) -> f64 {
369        self.elapsed_secs
370    }
371    fn consumed(&self) -> u64 {
372        self.consumed
373    }
374    fn rows_consumed(&self) -> u64 {
375        self.rows_consumed
376    }
377    fn rows_total(&self) -> u64 {
378        self.rows_total
379    }
380    fn status_metric_chips(&self) -> String {
381        self.status_metric_chips.clone()
382    }
383    fn adapter_counters_text(&self) -> String {
384        self.adapter_counters_text.clone()
385    }
386    fn batch_info_text(&self) -> String {
387        self.batch_info_text.clone()
388    }
389    fn depth_indent(&self) -> &str {
390        &self.depth_indent
391    }
392    fn use_color(&self) -> bool {
393        self.use_color
394    }
395    fn event(&self) -> EventType {
396        EventType::Update
397    }
398    fn refresh_tick(&self) -> u64 {
399        self.refresh_tick
400    }
401    fn phase_memo(&self) -> &str {
402        &self.memo
403    }
404    fn progress_override(&self) -> Option<f64> {
405        self.progress_override
406    }
407    fn open_ended(&self) -> bool {
408        self.open_ended
409    }
410    fn latency_p50_nanos(&self) -> u64 {
411        self.lat_p50_nanos
412    }
413    fn latency_p99_nanos(&self) -> u64 {
414        self.lat_p99_nanos
415    }
416    /// SRD-63 Push 9f: derive ETA from `cycles_total -
417    /// ops_finished` divided by the observed throughput
418    /// rate (`ops_finished / elapsed`). `None` when the
419    /// extent isn't known (sourceless phase running by
420    /// time / open-ended) or no progress has been made
421    /// yet (rate would divide-by-zero).
422    ///
423    /// A derived-progress override with a recorded producer
424    /// elapsed wins: ETA = `elapsed × (1−f)/f` — the measured
425    /// basis for a single long op (a poll-driven drain) whose
426    /// cycle accounting stands still. Guarded to `f` in
427    /// `(0, 1)`: at 0 nothing is measurable yet, at 1 the
428    /// after-state takes over momentarily.
429    fn eta_secs(&self) -> Option<f64> {
430        // Open-ended subjects have no completion, hence no ETA.
431        if self.open_ended {
432            return None;
433        }
434        if let (Some(f), Some(e)) = (self.progress_override, self.progress_override_elapsed)
435            && f > 0.0
436            && f < 1.0
437            && e > 0.0
438        {
439            return Some(e * (1.0 - f) / f);
440        }
441        // Cursor-driven phase: rows are the authoritative ordinal
442        // basis. Ops stride N rows each, so an op-denominated rate
443        // against the row-denominated extent would overstate the
444        // ETA by the stride factor (e.g. ~64/s ops vs 7.8K/s rows
445        // → 35h instead of 18m).
446        if self.rows_total > 0 && self.elapsed_secs > 0.0 {
447            if self.rows_consumed == 0 {
448                return None;
449            }
450            let rate = self.rows_consumed as f64 / self.elapsed_secs;
451            let remaining = self.rows_total.saturating_sub(self.rows_consumed) as f64;
452            return Some(remaining / rate);
453        }
454        if self.cycles_total == 0 || self.elapsed_secs <= 0.0 {
455            return None;
456        }
457        let rate = self.ops_finished as f64 / self.elapsed_secs;
458        if rate <= 0.0 {
459            return None;
460        }
461        let remaining = self.cycles_total.saturating_sub(self.ops_finished) as f64;
462        Some(remaining / rate)
463    }
464}
465
466/// One-shot lifecycle fire helper. Builds a binder for
467/// `event` against `bindings`, runs every bound body
468/// against `ctx`, writes the rendered text via
469/// `crate::diag!` (so it lands in stderr / log file
470/// uniformly), and captures to the snapshot store via
471/// `subject_kind` / `subject_id`.
472///
473/// Best-effort: errors building the binder log a warning
474/// and the fire is skipped — a malformed `readouts:`
475/// binding never blocks the run. Bindings that resolve
476/// to zero bodies (the usual case for structural slots
477/// with no built-in default and no workload binding)
478/// produce no output.
479pub fn fire_lifecycle(
480    event: crate::lifecycle::EventType,
481    bindings: &nmbrs_workload::model::ReadoutsBindings,
482    default: Option<crate::readouts::BakedBody>,
483    ctx: &dyn crate::readouts::ReadoutContext,
484    snapshot_writer: Option<&crate::readouts::snapshot::SnapshotWriter>,
485) {
486    use crate::readouts::ReadoutBinder;
487
488    // Use the built-in default when supplied (currently
489    // only PhaseEnd/Update have defaults); otherwise the
490    // slot starts empty and falls through to whatever the
491    // workload bound. `build_event_binder` always seeds
492    // the default — pass an empty body when none exists
493    // so unbound slots stay quiet.
494    let seed = default.unwrap_or_default();
495    let mut binder = match crate::readouts::build_event_binder(bindings, event, seed) {
496        Ok(b) => b,
497        Err(e) => {
498            crate::diag!(
499                crate::observer::LogLevel::Warn,
500                "readouts: failed to bind {slot} — {e}",
501                slot = event.slot_name()
502            );
503            return;
504        }
505    };
506    let mut sink = crate::readouts::StringSink::with_capacity(128);
507    binder.fire(event, ctx, &mut sink);
508    let rendered = sink.take();
509    if rendered.trim().is_empty() {
510        return; // no bound body for this slot — quiet exit
511    }
512    // The firing lifecycle slot IS the tag's attachment axis —
513    // this readout render is definitionally attached to the
514    // boundary that fired it. Sinks derive their rules from the
515    // axes (the terminal sink keeps `PhaseStart`-attached renders
516    // out of scrollback — its managed phase-history region mirrors
517    // them; scope / iteration / session boundaries have no region
518    // counterpart and flow through like in-flight lines).
519    let tag = crate::observer::EventTag::at(event, crate::observer::EventCategory::General);
520    crate::observer::log_tagged(crate::observer::LogLevel::Info, tag, &rendered);
521
522    // Snapshot capture per Push 6. Subject identity comes
523    // straight from the context: `subject_kind` from the
524    // firing event (the sole source of truth for which
525    // table dimension this row belongs to), `subject_id`
526    // from `ctx.subject_id()`'s default `name@labels`
527    // shape (overridden for session-scope contexts that
528    // collapse to a literal `"session"`). Replay reads
529    // stable tuples (slot, subject_kind, subject_id, ...).
530    crate::readouts::snapshot::capture(
531        snapshot_writer,
532        event,
533        ctx,
534        "binder",
535        crate::readouts::Lod::Labeled,
536        &rendered,
537    );
538}
539
540/// Build an [`InlineRefreshContext`] from the per-tick
541/// counter snapshots the inline-status thread takes. This
542/// preserves the byte-equivalence target by constructing
543/// the same intermediate values the prior `format!()`
544/// inlined (adapter counter chips, batch info, the
545/// scene-tree-walk for `seq` + depth indent) — they're
546/// each derived once per tick, then handed to the
547/// [`crate::readouts::builtins::phase_status::PhaseStatus`]
548/// readout for actual rendering.
549// reason: cohesive per-tick context builder — each argument is a distinct
550// counter snapshot/handle taken once per refresh tick; grouping them into a
551// struct would only relocate the same fields.
552/// Resolve a phase's `(seq, total)` pre-map coordinate + depth indent
553/// from the GLOBAL scene tree by NAME, matching the first Running node.
554///
555/// Retained for the legacy inline-status / phase-end callers that only
556/// have the activity name. The executor's on-task render-handle attach
557/// (SRD-100 P2) resolves these from the dispatch-time `SceneNodeId`
558/// instead — race-safe under concurrent same-name dispatch, where this
559/// first-Running-match could pick the wrong sibling.
560pub fn resolve_phase_coord_by_name(activity_name: &str) -> (Option<(usize, usize)>, String) {
561    let bare_name = activity_name
562        .split_once(" (")
563        .map(|(n, _)| n)
564        .unwrap_or(activity_name);
565    crate::scene_tree::current()
566        .and_then(|t| {
567            let node = t
568                .dfs_phases()
569                .find(|n| {
570                    n.name == bare_name
571                        && matches!(n.status, crate::scene_tree::PhaseStatus::Running)
572                })?
573                .clone();
574            let seq = node.seq?;
575            let depth = node.depth.saturating_sub(1);
576            Some((Some((seq, t.total_phases())), " ".repeat(depth)))
577        })
578        .unwrap_or((None, String::new()))
579}
580
581/// Resolve a phase's `(seq, total)` pre-map coordinate + depth indent
582/// from the GLOBAL scene tree by its dispatch-time [`SceneNodeId`](crate::scene_tree::SceneNodeId).
583///
584/// SRD-100 P2 — the race-safe replacement for [`resolve_phase_coord_by_name`]:
585/// keying on the node id (allocated at dispatch, P1c) addresses the exact
586/// node, so concurrent same-name siblings (sweep cells, comprehension
587/// iterations, daemon+foreground) each resolve their OWN coordinate. The
588/// executor calls this once at render-handle attach time.
589pub fn resolve_phase_coord_by_id(
590    scene_node_id: crate::scene_tree::SceneNodeId,
591) -> (Option<(usize, usize)>, String) {
592    crate::scene_tree::current()
593        .and_then(|t| {
594            let node = t.nodes.get(scene_node_id)?;
595            let seq = node.seq?;
596            let depth = node.depth.saturating_sub(1);
597            Some((Some((seq, t.total_phases())), " ".repeat(depth)))
598        })
599        .unwrap_or((None, String::new()))
600}
601
602/// Average batch size for the ` rows/batch:` chip — rows written per
603/// successful batch op.
604///
605/// Prefers `rows_inserted / batch_writes`, where `batch_writes` is the
606/// number of ops that actually wrote ≥1 row (published by the CQL
607/// batch dispensers alongside `rows_inserted`). This is the true
608/// per-op stride: retried, failed, and non-inserting ops never touch
609/// `batch_writes`, so the denominator can't drift the way
610/// `stanzas_total` (one inc per op *attempt*, regardless of
611/// success/failure/type) does.
612///
613/// Falls back to `rows_inserted / stanzas_total` when no `batch_writes`
614/// counter is present — non-CQL or older adapter paths that never
615/// learned to publish it. Returns `None` when no batched write was
616/// observed (average would be ≤1 row/op, i.e. not a batch).
617///
618/// Kept as a free function (not inline at the call site) so the three
619/// display paths that render this chip — the inline refresh here and
620/// the two TUI progress-thread snapshots in `executor.rs` — share one
621/// formula, and so the formula is unit-testable in isolation.
622/// Whether a dispenser status counter is INTERNAL — published only to feed a
623/// derived display metric, never rendered as its own `<name>/s` throughput
624/// chip. The convention is a **leading underscore**: `_batch_writes` backs the
625/// `rows/batch` average (see `rows_per_batch`) but must not clutter the
626/// operator-facing chip row as `_batch_writes/s`. Every surface that turns a
627/// dispenser counter into a chip filters on this one predicate, so the
628/// convention has a single point of truth. `find_counter`-style lookups pass
629/// the underscore name explicitly, so the counter stays available to the
630/// derived metric it exists for.
631pub fn is_internal_counter(name: &str) -> bool {
632    name.starts_with('_')
633}
634
635pub(crate) fn rows_per_batch(
636    rows_inserted: Option<u64>,
637    batch_writes: Option<u64>,
638    stanzas: u64,
639) -> Option<f64> {
640    let rows = rows_inserted?;
641    match batch_writes {
642        // A batch write count is present: divide by it directly. Show
643        // only when a real batch (>1 row/op) was observed.
644        Some(batches) if batches > 0 => (rows > batches).then(|| rows as f64 / batches as f64),
645        // Legacy / non-CQL fallback: attempt-count denominator.
646        _ => (stanzas > 0 && rows > stanzas).then(|| rows as f64 / stanzas as f64),
647    }
648}
649
650#[allow(clippy::too_many_arguments)]
651pub fn build_inline_refresh_context(
652    progress_metrics: &Arc<crate::activity::ActivityMetrics>,
653    activity_name: &str,
654    concurrency: usize,
655    total_extent: u64,
656    // Row-level cursor progress for a data-driven phase
657    // (`global_consumed()` / `global_extent()`); both `0` for
658    // non-cursor phases so the readout keeps the `cycles:` chip.
659    rows_consumed: u64,
660    rows_total: u64,
661    elapsed_secs: f64,
662    refresh_tick: u64,
663    status_metrics: &[String],
664    memo: &arc_swap::ArcSwap<String>,
665    // SRD-100 P2 — pre-map `(seq, total)` coordinate + depth indent,
666    // resolved by the caller. The producer no longer walks the global
667    // scene tree by name (a first-Running-match that raced under
668    // concurrent same-name dispatch); the executor's on-task attach
669    // resolves these from the dispatch-time `SceneNodeId` instead.
670    phase_seq: Option<(usize, usize)>,
671    depth_indent: String,
672    // Open-ended (daemon) subject: suppress progress metering, carry
673    // the latency chip instead.
674    open_ended: bool,
675) -> InlineRefreshContext {
676    // Counter snapshots — must match the prior inline-status
677    // formulas so byte equivalence holds.
678    let started = progress_metrics.ops_started.load(Ordering::Relaxed);
679    let finished = progress_metrics.ops_finished.load(Ordering::Relaxed);
680    let ops_completed = progress_metrics.cycles_completed();
681    // SRD-91: terminal-success count = `result_success.count()`;
682    // `errors_total` is RESULT-level (one inc per terminal failure),
683    // so it drives the `e:` count directly.
684    let successes = progress_metrics.result_success.count();
685    let errors = progress_metrics.errors_total.get();
686    let failed_ops = ops_completed
687        .saturating_sub(successes)
688        .saturating_sub(progress_metrics.skips_total.get());
689    let consumed = finished;
690    // SRD-91 attempt-level tallies, owned by the innermost
691    // `TriesDispenser` (or the error-handler wrapper for
692    // single-attempt ops). ALL attempt instruments count when an
693    // attempt RETURNS (2026-07-10 — attempt_total moved from
694    // dispatch to resolution, same discipline as the result
695    // instruments), so `attempt_total == attempt_success +
696    // attempt_failure` holds at every read and
697    // `attempt_ok / (attempt_ok + attempt_failed)` is the exact
698    // attempt success rate — dropping below the result-level
699    // `ok%` exactly when retries burn attempts to keep results
700    // green.
701    let attempt_ok = progress_metrics.attempt_success.count();
702    let attempt_failed = progress_metrics.attempt_failure.count();
703    // Retries = failed attempts that were NOT the terminal outcome.
704    // `errors_total` went RESULT-level with the TriesDispenser
705    // refactor, so the old `errors - failed_ops` derivation
706    // collapsed to ~0; the per-attempt failure count now lives in
707    // `attempt_failure`, and `attempt_failed - failed_ops` is the
708    // true retry count (each non-terminal failed attempt spawned a
709    // retry).
710    let retries = attempt_failed.saturating_sub(failed_ops);
711
712    // Adapter-status chips: ` <name>:<rate>/s` per registered
713    // dispenser counter. `collect_status_counters` aggregates
714    // every dispenser's typed counters into a flat
715    // `(name, total)` list — same data the inline thread used
716    // to read directly from `progress_metrics.dispensers`,
717    // exposed through the public accessor.
718    let mut adapter_counters_text = String::new();
719    let counters = progress_metrics.collect_status_counters();
720    for (name, total) in &counters {
721        // Internal counters (`_batch_writes`) feed derived metrics only —
722        // never their own chip. See `is_internal_counter`.
723        if is_internal_counter(name) {
724            continue;
725        }
726        let item_rate = if elapsed_secs > 0.0 {
727            *total as f64 / elapsed_secs
728        } else {
729            0.0
730        };
731        let rate_str = if item_rate >= 1_000_000.0 {
732            format!("{:.1}M", item_rate / 1_000_000.0)
733        } else if item_rate >= 1_000.0 {
734            format!("{:.1}K", item_rate / 1_000.0)
735        } else {
736            format!("{:.0}", item_rate)
737        };
738        adapter_counters_text.push_str(&format!(" {name}:{rate_str}/s"));
739    }
740
741    // Batch info: ` rows/batch:` = true average batch size (rows per
742    // successful batch op). Prefers `rows_inserted / batch_writes`
743    // when the CQL batch dispensers publish a `batch_writes` counter;
744    // otherwise falls back to the attempt-based `rows_inserted /
745    // stanzas_total`. See [`rows_per_batch`].
746    let stanzas = progress_metrics.stanzas_total.get();
747    let find_counter = |want: &str| counters.iter().find(|(n, _)| n == want).map(|(_, t)| *t);
748    let batch_info_text = rows_per_batch(
749        find_counter("rows_inserted"),
750        find_counter("_batch_writes"),
751        stanzas,
752    )
753    .map(|avg| format!(" rows/batch:{avg:.1}"))
754    .unwrap_or_default();
755
756    // Pre-rendered status-metric chip string.
757    let status_metric_chips = progress_metrics
758        .collect_status_values(status_metrics)
759        .concat();
760
761    // Activity name carries the leaf coord; the bare phase name is the
762    // readout's subject identity. (`phase_seq` / `depth_indent` now arrive
763    // as params — resolved race-safely by the caller.)
764    let bare_name = activity_name
765        .split_once(" (")
766        .map(|(n, _)| n)
767        .unwrap_or(activity_name);
768
769    let memo_snapshot: String = memo.load().as_str().to_string();
770    // Live latency percentiles for the open-ended chip (and any future
771    // consumer): a peek at the service-time HDR — no reset, cheap at
772    // display cadence.
773    let (lat_p50, lat_p99) = {
774        let snap = progress_metrics.service_time.peek_snapshot();
775        let h = &snap.histogram;
776        if h.is_empty() {
777            (0, 0)
778        } else {
779            (h.value_at_quantile(0.50), h.value_at_quantile(0.99))
780        }
781    };
782    InlineRefreshContext {
783        phase_name: bare_name.to_string(),
784        activity_name: activity_name.to_string(),
785        phase_seq,
786        phase_labels: String::new(),
787        cycles_completed: ops_completed,
788        cycles_total: total_extent,
789        ops_started: started,
790        ops_finished: finished,
791        ops_ok: successes,
792        skips: progress_metrics.skips_total.get(),
793        errors,
794        retries,
795        attempt_ok,
796        attempt_failed,
797        concurrency,
798        elapsed_secs,
799        consumed,
800        rows_consumed,
801        rows_total,
802        status_metric_chips,
803        adapter_counters_text,
804        batch_info_text,
805        depth_indent,
806        refresh_tick,
807        use_color: crate::observer::use_color(),
808        memo: memo_snapshot,
809        progress_override: progress_metrics.progress_override(),
810        progress_override_elapsed: progress_metrics.progress_override_elapsed_secs(),
811        open_ended,
812        lat_p50_nanos: lat_p50,
813        lat_p99_nanos: lat_p99,
814    }
815}
816
817#[cfg(test)]
818mod tests {
819    #[test]
820    fn eta_prefers_measured_basis_when_override_present() {
821        // 25% done after 60s of measured work → 180s remain,
822        // regardless of the standing-still cycle accounting.
823        let ctx = super::InlineRefreshContext {
824            phase_name: String::new(),
825            activity_name: String::new(),
826            phase_seq: None,
827            phase_labels: String::new(),
828            cycles_completed: 3,
829            cycles_total: 4,
830            ops_started: 4,
831            ops_finished: 3,
832            ops_ok: 3,
833            skips: 0,
834            errors: 0,
835            retries: 0,
836            attempt_ok: 3,
837            attempt_failed: 0,
838            concurrency: 1,
839            elapsed_secs: 600.0,
840            consumed: 3,
841            rows_consumed: 0,
842            rows_total: 0,
843            status_metric_chips: String::new(),
844            adapter_counters_text: String::new(),
845            batch_info_text: String::new(),
846            depth_indent: String::new(),
847            refresh_tick: 0,
848            use_color: false,
849            memo: String::new(),
850            progress_override: Some(0.25),
851            progress_override_elapsed: Some(60.0),
852            open_ended: false,
853            lat_p50_nanos: 0,
854            lat_p99_nanos: 0,
855        };
856        use crate::readouts::ReadoutContext;
857        let eta = ctx.eta_secs().expect("measured ETA");
858        assert!((eta - 180.0).abs() < 1e-9, "eta={eta}");
859        // Without the elapsed companion, fall back to cycle basis.
860        let ctx2 = super::InlineRefreshContext {
861            progress_override_elapsed: None,
862            ..ctx
863        };
864        let eta2 = ctx2.eta_secs().expect("cycle ETA");
865        assert!((eta2 - 200.0).abs() < 1e-9, "eta2={eta2}");
866    }
867
868    #[test]
869    fn eta_uses_row_basis_for_cursor_phases() {
870        // Cursor phase, ops stride 100 rows each: 2M of 10M rows in
871        // 200s → 8M remain at 10K rows/s → 800s. The op basis
872        // (10K ops finished vs a 10M extent) would claim ~200,000s —
873        // the stride-factor overstatement this pins against.
874        let ctx = super::InlineRefreshContext {
875            phase_name: String::new(),
876            activity_name: String::new(),
877            phase_seq: None,
878            phase_labels: String::new(),
879            cycles_completed: 10_000,
880            cycles_total: 10_000_000,
881            ops_started: 10_000,
882            ops_finished: 10_000,
883            ops_ok: 10_000,
884            skips: 0,
885            errors: 0,
886            retries: 0,
887            attempt_ok: 10_000,
888            attempt_failed: 0,
889            concurrency: 1,
890            elapsed_secs: 200.0,
891            consumed: 10_000,
892            rows_consumed: 2_000_000,
893            rows_total: 10_000_000,
894            status_metric_chips: String::new(),
895            adapter_counters_text: String::new(),
896            batch_info_text: String::new(),
897            depth_indent: String::new(),
898            refresh_tick: 0,
899            use_color: false,
900            memo: String::new(),
901            progress_override: None,
902            progress_override_elapsed: None,
903            open_ended: false,
904            lat_p50_nanos: 0,
905            lat_p99_nanos: 0,
906        };
907        use crate::readouts::ReadoutContext;
908        let eta = ctx.eta_secs().expect("row-basis ETA");
909        assert!((eta - 800.0).abs() < 1e-6, "eta={eta}");
910        // No rows consumed yet → unknown, not a fabricated op-basis ETA.
911        let ctx2 = super::InlineRefreshContext {
912            rows_consumed: 0,
913            ..ctx
914        };
915        assert!(
916            ctx2.eta_secs().is_none(),
917            "zero-row cursor phase must have no ETA"
918        );
919    }
920
921    /// The phase-end ✓ line meters a batched phase by rows: 11,623
922    /// ops of 70 rows against a 1M-row cursor is 81% done, which the
923    /// op basis rendered as 1% (a live load read as stalled).
924    #[test]
925    fn phase_end_progress_uses_row_basis_for_cursor_phases() {
926        let ctx = super::ActivityReadoutContext {
927            phase_name: "load".into(),
928            phase_seq: None,
929            phase_labels: String::new(),
930            cycles_completed: 11_623,
931            cycles_total: 1_000_000,
932            ops_ok: 11_623,
933            skips: 0,
934            errors: 0,
935            retries: 0,
936            concurrency: 1,
937            elapsed_secs: 1.0,
938            consumed: 813_610,
939            rows_consumed: 813_610,
940            rows_total: 1_000_000,
941            status_metric_chips: String::new(),
942            depth_indent: String::new(),
943            use_color: false,
944            memo: String::new(),
945            outcome: crate::phase_outcome::Outcome::failed(),
946            outcome_errors: Vec::new(),
947            outcome_resume_cursor: None,
948            open_ended: false,
949        };
950        use crate::readouts::ReadoutContext;
951        let f = ctx.progress_fraction().expect("a bounded phase");
952        assert!((f - 0.81361).abs() < 1e-9, "fraction={f}");
953    }
954
955    use super::{is_internal_counter, rows_per_batch};
956
957    /// The leading-underscore convention: `_batch_writes` is an internal
958    /// denominator (hidden from the chip row), while a plain counter like
959    /// `rows_inserted` is a visible throughput chip. The chip-render loops
960    /// filter on exactly this predicate.
961    #[test]
962    fn internal_counter_is_underscore_prefixed() {
963        assert!(is_internal_counter("_batch_writes"));
964        assert!(!is_internal_counter("rows_inserted"));
965        assert!(!is_internal_counter("queries"));
966    }
967
968    /// With a `batch_writes` counter present, `rows/batch` is the true
969    /// average batch size (`rows_inserted / batch_writes`), NOT the
970    /// attempt-based `rows_inserted / stanzas_total`. Here 1000 rows
971    /// across 5 successful batch ops ⇒ 200.0, even though 40 op
972    /// attempts (stanzas) were recorded — the stanzas formula would
973    /// have wrongly shown 25.0.
974    #[test]
975    fn prefers_batch_writes_over_stanzas() {
976        let avg = rows_per_batch(Some(1000), Some(5), 40);
977        assert_eq!(avg, Some(200.0));
978    }
979
980    /// Without a `batch_writes` counter (non-CQL / older paths), the
981    /// formula falls back to `rows_inserted / stanzas_total`.
982    #[test]
983    fn falls_back_to_stanzas_without_batch_writes() {
984        let avg = rows_per_batch(Some(1000), None, 40);
985        assert_eq!(avg, Some(25.0));
986    }
987
988    /// `batch_writes = 0` behaves like "not present" — the counter is
989    /// only published once it has ticked, but guard against a zero
990    /// denominator either way and use the fallback.
991    #[test]
992    fn zero_batch_writes_uses_fallback() {
993        let avg = rows_per_batch(Some(1000), Some(0), 40);
994        assert_eq!(avg, Some(25.0));
995    }
996
997    /// No batched write observed (avg would be ≤1 row/op) ⇒ no chip.
998    #[test]
999    fn no_batch_observed_is_none() {
1000        // batch_writes path: rows == batches ⇒ average of 1, not a batch.
1001        assert_eq!(rows_per_batch(Some(5), Some(5), 40), None);
1002        // stanzas fallback: rows == stanzas ⇒ not a batch.
1003        assert_eq!(rows_per_batch(Some(40), None, 40), None);
1004        // no rows_inserted counter at all ⇒ nothing to show.
1005        assert_eq!(rows_per_batch(None, Some(5), 40), None);
1006    }
1007}