Skip to main content

nmbrs_runtime/
activity.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Activity: the unit of concurrent execution.
5
6use std::sync::Arc;
7use std::sync::atomic::Ordering;
8use std::time::{Duration, Instant};
9
10use nmbrs_metrics::instruments::counter::Counter;
11use nmbrs_metrics::instruments::histogram::Histogram;
12use nmbrs_metrics::instruments::outcome::{MetricDetail, MetricDetailConfig, OutcomeInstrument};
13use nmbrs_metrics::instruments::timer::Timer;
14use nmbrs_metrics::labels::Labels;
15use nmbrs_metrics::snapshot::MetricSet;
16use nmbrs_rate::RateLimiter;
17
18use crate::adapter::{DriverAdapter, OpDispenser};
19// CycleSource removed — all iteration goes through DataSourceFactory
20use crate::opseq::{OpSequence, SequencerType};
21use crate::validation;
22
23/// The settings an activity's execution resolves for it, passed to
24/// [`Activity::with_resolution`].
25pub struct ActivityResolution<'a> {
26    /// HDR significant digits every histogram the activity owns is
27    /// built at (`hdr.sigdigs`, SRD 40).
28    pub sigdigs: u8,
29    /// The error policy, shared with the parent scope.
30    pub error_policy: Arc<crate::error_policy::ErrorPolicy>,
31    /// The phase node's kernel; `None` off the executor's phase path.
32    pub phase_kernel: Option<Arc<crate::scope_kernel::ScopeKernel>>,
33    /// Counter-vs-timer detail for the op-outcome instruments (SRD-91).
34    pub metric_detail: &'a MetricDetailConfig,
35}
36
37/// Configuration for an activity.
38pub struct ActivityConfig {
39    pub name: String,
40    pub cycles: u64,
41    /// Number of fibers (tokio tasks) executing stanzas concurrently.
42    pub concurrency: usize,
43    /// Target ops/sec for the single activity-level rate
44    /// limiter. `None` disables rate limiting. There is one
45    /// rate limiter per activity — no separate stanza-rate
46    /// mechanism.
47    pub rate: Option<f64>,
48    pub sequencer: SequencerType,
49    pub error_spec: String,
50    /// Error-rate circuit breaker: fail the phase early when the
51    /// fraction of errored ops exceeds this threshold (e.g. `0.1`
52    /// = 10%). Evaluated only after at least 50 ops (the floor in
53    /// `StopConditionDecl::error_rate_guard`) so a small phase can't
54    /// trip on a single error. `None` disables it; a value `>= 1.0` also
55    /// effectively disables it (the rate never exceeds 1.0).
56    /// Resolved per phase as the workload's `error_rate_max:` field
57    /// over the session-wide default. Installed as the default SRD-83
58    /// stop condition (`error_rate > error_rate_max`).
59    pub error_rate_max: Option<f64>,
60    /// SRD-83 — the phase's declared stop-condition predicates (the
61    /// `when:` of each `stop_when:` entry). Compiled into scope-bound
62    /// `ScopedPredicate`s alongside the default error-rate condition and
63    /// evaluated per tick.
64    pub stop_when: Vec<crate::stop_conditions::StopConditionDecl>,
65    /// SRD-83 §throttle — the phase's adaptive backpressure governor
66    /// spec: keep the windowed attempt-failure fraction under a bound
67    /// by walking a dynamic control (`concurrency`/`rate`). Evaluated
68    /// on the same drain-loop tick as the stop conditions.
69    pub throttle: Option<nmbrs_workload::model::ThrottleSpec>,
70    /// Inherited total-attempts budget for this activity's ops (phase
71    /// `tries:` or the workload-root `tries` param). An op's own `tries:`
72    /// field overrides it. `None` = no budget in scope → ops WITHOUT their
73    /// own `tries:` run single-attempt with no tries wrapper (SRD-82 Part 3b
74    /// sigil). `0` = ops fail without executing; `1` = explicit
75    /// single-attempt.
76    pub tries: Option<u32>,
77    /// Retry-backoff overrides from the phase-level `tries:` map form
78    /// (`tries: {count, backoff: {ratio, min, max}}`). `None` = none
79    /// declared at the phase → the tries wrapper falls back to the op's
80    /// standalone `retry_backoff*` params, then the built-in defaults.
81    pub tries_backoff: Option<nmbrs_workload::model::BackoffSpec>,
82    /// Maximum number of ops within a stanza that execute concurrently.
83    pub stanza_concurrency: usize,
84    /// Source factory for data-driven phases. When present, fibers pull
85    /// from this source instead of the cycle counter. Each fiber creates
86    /// its own reader via `create_reader()`.
87    pub source_factory: Option<Arc<dyn polydat::iteration::source::DataSourceFactory>>,
88    /// Suppress the inline stderr progress line (TUI handles
89    /// display). Wrapped in `Arc<AtomicBool>` so the runner can
90    /// flip it at runtime — when the user dismisses the TUI
91    /// mid-run (`q` keypress), this flag drops to `false` and
92    /// the status thread resumes emission, making the
93    /// experience feel like tui=off was set from the start.
94    /// A bare `bool` would have baked the TUI-mode value in at
95    /// activity construction, so post-dismissal there'd be no
96    /// progress display at all.
97    pub suppress_status_line: Arc<std::sync::atomic::AtomicBool>,
98    /// Names of relevancy / live aggregate metrics to surface on
99    /// the inline progress line and the per-phase ✓ DONE summary.
100    /// Empty → no extra metrics are shown (status line carries
101    /// only the universal counters). Set per-phase via the YAML
102    /// `status_metrics: [name]` field; workload-level phases that
103    /// compute relevancy must opt in explicitly — nothing is
104    /// presumed to be present.
105    pub status_metrics: Vec<String>,
106    /// Full root-first coordinate label (e.g.
107    /// `(profile=label_00), (bucket=1, kind=READ)`) for this
108    /// phase's iteration. Used by the ✓ DONE summary line to
109    /// show the same identity the per-phase header would carry,
110    /// so the completed-status line stands alone — no separate
111    /// phase-starting row needed.
112    pub phase_labels: String,
113    /// Pre-map sequence number `[N/total]` for this phase. Same
114    /// numbering the TUI tree row and post-run summary use.
115    /// `None` ⇒ inline-CLI form / pre-map didn't produce a seq.
116    pub phase_seq: Option<(usize, usize)>,
117    /// Resolved `readouts:` slot bindings from the workload
118    /// (SRD-63 §5). Empty → all slots fall through to the
119    /// hard-coded built-in defaults (`phase_outcome` at
120    /// `on_phase_end`, `phase_status` at `on_update`).
121    pub readouts: nmbrs_workload::model::ReadoutsBindings,
122    /// CLI `--readout=<body>` override (SRD-63 §8).
123    /// Applies to the `on_update` slot only; replaces
124    /// (or with `+` prefix, appends to) whatever the
125    /// workload + default path resolved.
126    pub cli_readout_override: Option<String>,
127    /// Per-session SQLite writer. Used by Push 6's snapshot
128    /// store — every binder.fire captures its rendered
129    /// output via `upsert_readout_snapshot` so replay /
130    /// scrollback can reproduce the line later. `None`
131    /// means snapshot capture is skipped (no session db
132    /// — short test fixtures, in-memory sessions).
133    pub snapshot_writer:
134        Option<Arc<std::sync::Mutex<Option<nmbrs_metrics::reporters::sqlite::SqliteReporter>>>>,
135    /// Session-level dryrun mode (`silent` / `emit` / `json`),
136    /// or `None` for a normal run.
137    ///
138    /// `dryrun=cycle` means **full construction of an executable
139    /// cycle path** — real adapter, real cluster connection, real
140    /// prepared statements, real metadata — and then suppression
141    /// of only the outbound `execute()` at cycle time via the
142    /// outermost `DryRunWrapper`. The wrapper is triggered by an
143    /// injected `dryrun:` op-template parameter, and this field is
144    /// the signal that drives that injection. There is no
145    /// substitution of the adapter itself; the adapter lifecycle
146    /// runs end-to-end, so the typed lvalue contract the adapter
147    /// reifies at `map_op` time (CQL: prepare + metadata) is
148    /// available under dryrun exactly as it is under a real run.
149    pub dry_run_mode: Option<String>,
150    /// `dryrun=dispenser`: when true, `run_with_adapters`
151    /// returns cleanly after every op template's dispenser is
152    /// constructed (adapter `map_op` fires, the wrapper plan
153    /// resolves and wraps, the per-template pull plan seals).
154    /// No fiber pool is spawned, no cycles run. Lets the
155    /// operator verify the full construction pipeline ran
156    /// without paying any per-cycle cost.
157    ///
158    /// Set from `ExecCtx::diag.depth` at phase-attach time —
159    /// `< Cycle` flips this on, `>= Cycle` leaves it off.
160    pub stop_after_dispenser_init: bool,
161}
162
163impl Default for ActivityConfig {
164    fn default() -> Self {
165        Self {
166            name: "default".into(),
167            cycles: 1,
168            concurrency: 1,
169            rate: None,
170            sequencer: SequencerType::Bucket,
171            error_spec: ".*:warn,stop".into(),
172            error_rate_max: None,
173            stop_when: Vec::new(),
174            throttle: None,
175            // Default 0 — retries are opt-in via the workload `retries:` param
176            // (runner default is also 0). Matches the effective pre-wrapper
177            // behaviour (retries previously required a policy `retry`
178            // classification, off by default).
179            tries: None,
180            tries_backoff: None,
181            stanza_concurrency: 1,
182            source_factory: None,
183            suppress_status_line: Arc::new(std::sync::atomic::AtomicBool::new(false)),
184            status_metrics: Vec::new(),
185            phase_labels: String::new(),
186            phase_seq: None,
187            readouts: nmbrs_workload::model::ReadoutsBindings::default(),
188            cli_readout_override: None,
189            snapshot_writer: None,
190            dry_run_mode: None,
191            stop_after_dispenser_init: false,
192        }
193    }
194}
195
196/// Standard metrics for an activity. Shared via Arc so the metrics
197/// scheduler can capture snapshots while executor tasks record.
198///
199/// Fields are `Arc<Counter>` / `Arc<Timer>` / `Arc<Histogram>` so
200/// the same instrument is held both here (for per-cycle record
201/// access) and in the activity's `Component` instrument registry
202/// (for the cadence reporter's per-tick capture). Per-cycle code
203/// continues calling `metrics.cycles_total.inc()` etc. through
204/// `Arc`'s `Deref`.
205///
206/// Static instruments (the fields below) register on the component
207/// from [`ActivityMetrics::register_on`] called by
208/// [`Activity::attach_component`]. Dynamic per-error-type counters
209/// and adapter-specific metrics flow through the
210/// [`nmbrs_metrics::component::DynamicCapture`] hook implemented
211/// for [`ActivityMetricsDynamic`].
212///
213/// Late-bound, optional shared dispenser list. Wrapped in a `Mutex`
214/// because it is set once after dispenser creation (post-init) and
215/// read by the dynamic-capture hook thereafter.
216type SharedDispensers = std::sync::Mutex<Option<Arc<Vec<Arc<dyn crate::adapter::OpDispenser>>>>>;
217
218pub struct ActivityMetrics {
219    pub service_time: Arc<Timer>,
220    pub wait_time: Arc<Timer>,
221    pub response_time: Arc<Timer>,
222    /// Number of tries per op (1 = succeeded first try, 2+ = retried).
223    /// Distribution shape reveals incremental saturation.
224    pub tries_histogram: Arc<Histogram>,
225    /// Every op dispatched (incl. skips) — the rate driver. Distinct
226    /// from `result_total`, which excludes skips. SRD-91.
227    pub cycles_total: Arc<Counter>,
228    pub skips_total: Arc<Counter>,
229    // ── SRD-91 op-outcome taxonomy ────────────────────────────────
230    // Two layers that reconcile (the redundancy IS the validation):
231    //   • executor layer — `attempt_*` / `result_*`, counted in the
232    //     stanza hot loop;
233    //   • error-handler layer — `errors_total` + the per-type
234    //     breakdown, counted per failed attempt at error dispatch.
235    // Invariants:
236    //   attempt_total == attempt_success.count + attempt_failure.count
237    //   result_total  == result_success.count  + result_failure.count
238    //   cycles_total  == result_total + skips_total
239    //   errors_total  == Σ per-type == attempt_failure.count
240    //                    (when the policy counts every error)
241    /// Per-ATTEMPT total — one increment per `dispenser.execute`,
242    /// including retries.
243    pub attempt_total: Arc<Counter>,
244    /// Per-ATTEMPT outcomes (+ attempt latency when Timed). The count
245    /// is available in either detail mode — see [`OutcomeInstrument`].
246    pub attempt_success: OutcomeInstrument,
247    pub attempt_failure: OutcomeInstrument,
248    /// Per-OP terminal total — executed results only (success +
249    /// failure; excludes skips). Distinct from `cycles_total` by the
250    /// skip count.
251    pub result_total: Arc<Counter>,
252    /// Per-OP terminal outcomes (+ op latency when Timed).
253    /// `result_success` replaces the former `result_success_time`
254    /// timer and the unexported `successes_total` counter — its
255    /// `count()` IS the terminal-success count.
256    pub result_success: OutcomeInstrument,
257    pub result_failure: OutcomeInstrument,
258    /// Error-handler-layer tally: one increment per failed attempt at
259    /// error dispatch (per-attempt, so retries DO count here), keyed
260    /// by the handler-classified name for the per-type breakdown. The
261    /// per-op error rate uses `result_failure` instead, keeping it in
262    /// `[0,1]`. SRD-91.
263    pub errors_total: Arc<Counter>,
264    pub stanzas_total: Arc<Counter>,
265    /// Daemon ops that exited cleanly via stop-signal cancellation
266    /// at phase shutdown (the trigger-and-observe happy path).
267    /// Counts increment on `DaemonExit::Cancelled` only — natural
268    /// completions are tracked through `result_success` /
269    /// `result_failure` on the underlying op path. Visibility on
270    /// this counter lets the operator distinguish "phase exited
271    /// with N daemons cancelled" from "phase exited with no
272    /// daemons in flight" without re-reading session.log.
273    pub daemon_cancelled_total: Arc<Counter>,
274    /// Daemon ops whose shutdown failed: returned an error during
275    /// running or shutdown, panicked, or missed the grace window.
276    /// Each increment is paired with the activity's stop_flag
277    /// being set + a stop_reason being recorded.
278    pub daemon_errors_total: Arc<Counter>,
279    /// Number of ops dispatched to adapters (monotonic).
280    pub ops_started: std::sync::atomic::AtomicU64,
281    /// Number of ops returned from adapters (monotonic).
282    pub ops_finished: std::sync::atomic::AtomicU64,
283    pub result_elements: Arc<Counter>,
284    pub result_bytes: Arc<Counter>,
285    /// Derived phase-progress override, in parts-per-million of the
286    /// completion fraction (0..=1_000_000); `u64::MAX` = unset. When
287    /// set, status surfaces render THIS fraction for the phase's
288    /// completion bar / percentage instead of the cycles-based
289    /// `cycles_completed / total_extent` — load-bearing for phases
290    /// whose single long op measures its own progress (e.g. a
291    /// `poll:` await publishing `completion_ratio` from
292    /// `system_views.sstable_tasks`), where the cycle count pins the
293    /// bar at 0% for the whole wait. Stored as integer ppm so the
294    /// producer/consumer handoff stays a lock-free atomic.
295    pub progress_override_ppm: std::sync::atomic::AtomicU64,
296    /// Elapsed milliseconds of the producer that published
297    /// [`Self::progress_override_ppm`] (e.g. the poll's own elapsed),
298    /// `u64::MAX` = unset. Carried so displays can derive an ETA on the
299    /// measured basis — `elapsed × (1−f)/f` — instead of the cycle
300    /// accounting, which stands still for a single long measured op.
301    pub progress_override_elapsed_ms: std::sync::atomic::AtomicU64,
302    /// Per-error-type counters, keyed by error_name.
303    /// Created on demand when a new error type is first seen.
304    /// Captured via the [`DynamicCapture`] hook — the registry on
305    /// `Component` only holds instruments known at init.
306    error_type_counts: std::sync::Mutex<std::collections::HashMap<String, Arc<Counter>>>,
307    labels: Labels,
308    /// Dispensers for adapter-specific metrics capture. Set after dispenser creation.
309    dispensers: SharedDispensers,
310    /// Shared handles to the per-template validation metrics. Populated
311    /// after executor setup so the progress thread can read live
312    /// relevancy aggregates (recall-over-last-N, all-time mean) without
313    /// draining the precision accumulators.
314    validation_metrics:
315        std::sync::Mutex<Option<Arc<Vec<Arc<crate::validation::ValidationMetrics>>>>>,
316}
317
318/// Resolve the SRD-91 op-outcome detail config from the single
319/// `metrics_detail` param. The value is a comma-separated list: a bare
320/// token sets the global default (`counts` / `timers`), and a
321/// `family:mode` token overrides one instrument. Example:
322/// `metrics_detail=timers,attempt_success:counts,attempt_failure:counts`.
323/// Absent or unparseable tokens fall back to the default (timers).
324pub(crate) fn metric_detail_from_params(
325    params: &std::collections::HashMap<String, String>,
326) -> MetricDetailConfig {
327    let Some(spec) = params.get("metrics_detail") else {
328        return MetricDetailConfig::default();
329    };
330    let mut default = MetricDetail::default();
331    let mut overrides: Vec<(String, MetricDetail)> = Vec::new();
332    for tok in spec.split(',') {
333        let tok = tok.trim();
334        if tok.is_empty() {
335            continue;
336        }
337        if let Some((family, mode)) = tok.split_once(':') {
338            if let Some(d) = MetricDetail::parse(mode) {
339                overrides.push((family.trim().to_string(), d));
340            }
341        } else if let Some(d) = MetricDetail::parse(tok) {
342            default = d;
343        }
344    }
345    let mut cfg = MetricDetailConfig::new(default);
346    for (family, detail) in overrides {
347        cfg = cfg.with_override(family, detail);
348    }
349    cfg
350}
351
352impl ActivityMetrics {
353    pub fn new(labels: &Labels) -> Self {
354        Self::with_sigdigs(
355            labels,
356            nmbrs_metrics::instruments::histogram::DEFAULT_HDR_SIGDIGS,
357            &MetricDetailConfig::default(),
358        )
359    }
360
361    /// Construct activity metrics using an explicit HDR
362    /// significant-digits precision for every histogram and
363    /// timer below. The runner resolves `hdr.sigdigs` from the
364    /// session root via
365    /// [`nmbrs_metrics::instruments::histogram::resolve_hdr_sigdigs`]
366    /// once per activity and threads it here (SRD 40 §"HDR
367    /// significant digits — subtree-scoped setting").
368    pub fn with_sigdigs(labels: &Labels, sigdigs: u8, detail: &MetricDetailConfig) -> Self {
369        // Outcome instruments choose counter-vs-timer per family (global
370        // default + override), SRD-91. Default is Timers, preserving the
371        // historical always-on latency distributions.
372        let outcome = |name: &str| {
373            OutcomeInstrument::new(labels.with("name", name), sigdigs, detail.for_family(name))
374        };
375        Self {
376            service_time: Arc::new(Timer::with_sigdigs(
377                labels.with("name", "cycles_servicetime"),
378                sigdigs,
379            )),
380            wait_time: Arc::new(Timer::with_sigdigs(
381                labels.with("name", "cycles_waittime"),
382                sigdigs,
383            )),
384            response_time: Arc::new(Timer::with_sigdigs(
385                labels.with("name", "cycles_responsetime"),
386                sigdigs,
387            )),
388            tries_histogram: Arc::new(
389                nmbrs_metrics::instruments::histogram::Histogram::with_sigdigs(
390                    labels.with("name", "tries"),
391                    sigdigs,
392                ),
393            ),
394            cycles_total: Arc::new(Counter::new(labels.with("name", "cycles_total"))),
395            skips_total: Arc::new(Counter::new(labels.with("name", "skips_total"))),
396            attempt_total: Arc::new(Counter::new(labels.with("name", "attempt_total"))),
397            attempt_success: outcome("attempt_success"),
398            attempt_failure: outcome("attempt_failure"),
399            result_total: Arc::new(Counter::new(labels.with("name", "result_total"))),
400            result_success: outcome("result_success"),
401            result_failure: outcome("result_failure"),
402            errors_total: Arc::new(Counter::new(labels.with("name", "errors_total"))),
403            stanzas_total: Arc::new(Counter::new(labels.with("name", "stanzas_total"))),
404            daemon_cancelled_total: Arc::new(Counter::new(
405                labels.with("name", "daemon_cancelled_total"),
406            )),
407            daemon_errors_total: Arc::new(Counter::new(labels.with("name", "daemon_errors_total"))),
408            ops_started: std::sync::atomic::AtomicU64::new(0),
409            ops_finished: std::sync::atomic::AtomicU64::new(0),
410            result_elements: Arc::new(Counter::new(labels.with("name", "result_elements"))),
411            result_bytes: Arc::new(Counter::new(labels.with("name", "result_bytes"))),
412            progress_override_ppm: std::sync::atomic::AtomicU64::new(u64::MAX),
413            progress_override_elapsed_ms: std::sync::atomic::AtomicU64::new(u64::MAX),
414            error_type_counts: std::sync::Mutex::new(std::collections::HashMap::new()),
415            labels: labels.clone(),
416            dispensers: std::sync::Mutex::new(None),
417            validation_metrics: std::sync::Mutex::new(None),
418        }
419    }
420
421    /// Register every static instrument on `component` and install
422    /// a [`DynamicCapture`](nmbrs_metrics::component::DynamicCapture)
423    /// hook for the dynamic surface (per-error-type
424    /// counters and adapter-specific metrics from registered dispensers).
425    ///
426    /// Called once from [`Activity::attach_component`]. After this
427    /// point:
428    /// - The cadence reporter's tree walk picks up every static
429    ///   instrument here through `component.capture_delta`.
430    /// - Per-cycle code continues recording through this struct's
431    ///   typed `Arc` fields — same `Arc` that the registry holds.
432    pub fn register_on(
433        self: &Arc<Self>,
434        component: &mut nmbrs_metrics::component::Component,
435    ) -> Result<(), String> {
436        use nmbrs_metrics::component::InstrumentRef;
437        // Order mirrors the historical capture_delta emission so
438        // metric_family ordering stays stable for downstream
439        // consumers. SRD-91 outcome instruments register via
440        // `instrument_ref()` (a counter or summary family per the
441        // resolved detail mode).
442        component.register_instrument(
443            "cycles_servicetime",
444            InstrumentRef::Timer(self.service_time.clone()),
445        )?;
446        component.register_instrument(
447            "cycles_waittime",
448            InstrumentRef::Timer(self.wait_time.clone()),
449        )?;
450        component.register_instrument(
451            "cycles_responsetime",
452            InstrumentRef::Timer(self.response_time.clone()),
453        )?;
454        component.register_instrument("result_success", self.result_success.instrument_ref())?;
455        component.register_instrument("result_failure", self.result_failure.instrument_ref())?;
456        component.register_instrument(
457            "result_total",
458            InstrumentRef::Counter(self.result_total.clone()),
459        )?;
460        component.register_instrument(
461            "cycles_total",
462            InstrumentRef::Counter(self.cycles_total.clone()),
463        )?;
464        component.register_instrument(
465            "skips_total",
466            InstrumentRef::Counter(self.skips_total.clone()),
467        )?;
468        component.register_instrument(
469            "errors_total",
470            InstrumentRef::Counter(self.errors_total.clone()),
471        )?;
472        component.register_instrument(
473            "attempt_total",
474            InstrumentRef::Counter(self.attempt_total.clone()),
475        )?;
476        component.register_instrument("attempt_success", self.attempt_success.instrument_ref())?;
477        component.register_instrument("attempt_failure", self.attempt_failure.instrument_ref())?;
478        component.register_instrument(
479            "stanzas_total",
480            InstrumentRef::Counter(self.stanzas_total.clone()),
481        )?;
482        component.register_instrument(
483            "daemon_cancelled_total",
484            InstrumentRef::Counter(self.daemon_cancelled_total.clone()),
485        )?;
486        component.register_instrument(
487            "daemon_errors_total",
488            InstrumentRef::Counter(self.daemon_errors_total.clone()),
489        )?;
490        component.register_instrument(
491            "result_elements",
492            InstrumentRef::Counter(self.result_elements.clone()),
493        )?;
494        component.register_instrument(
495            "result_bytes",
496            InstrumentRef::Counter(self.result_bytes.clone()),
497        )?;
498        component.register_instrument(
499            "tries",
500            InstrumentRef::Histogram(self.tries_histogram.clone()),
501        )?;
502
503        component.set_dynamic_capture(Arc::new(ActivityMetricsDynamic {
504            metrics: self.clone(),
505            prev_counters: std::sync::Mutex::new(std::collections::HashMap::new()),
506        }));
507        Ok(())
508    }
509
510    /// Return the number of cycles completed so far.
511    ///
512    /// Reads from the `cycles_total` counter atomically. Used by the
513    /// progress reporter thread to display live throughput.
514    pub fn cycles_completed(&self) -> u64 {
515        self.cycles_total.get()
516    }
517
518    /// Publish (or clear, with `None`) the derived phase-progress
519    /// override. `Some(f)` is clamped to `[0.0, 1.0]` and stored in
520    /// ppm; see the field doc on [`Self::progress_override_ppm`].
521    /// Clearing also clears the producer-elapsed companion.
522    pub fn set_progress_override(&self, fraction: Option<f64>) {
523        let ppm = match fraction {
524            Some(f) => (f.clamp(0.0, 1.0) * 1_000_000.0).round() as u64,
525            None => u64::MAX,
526        };
527        self.progress_override_ppm
528            .store(ppm, std::sync::atomic::Ordering::Relaxed);
529        if fraction.is_none() {
530            self.progress_override_elapsed_ms
531                .store(u64::MAX, std::sync::atomic::Ordering::Relaxed);
532        }
533    }
534
535    /// As [`Self::set_progress_override`], additionally recording the
536    /// producer's own elapsed seconds at publish time. Displays derive
537    /// the measured-basis ETA from the pair: `elapsed × (1−f)/f`.
538    pub fn set_progress_override_with_elapsed(&self, fraction: f64, elapsed_secs: f64) {
539        self.set_progress_override(Some(fraction));
540        let ms = (elapsed_secs.max(0.0) * 1000.0).round() as u64;
541        self.progress_override_elapsed_ms
542            .store(ms.min(u64::MAX - 1), std::sync::atomic::Ordering::Relaxed);
543    }
544
545    /// The derived phase-progress override as a fraction in
546    /// `[0.0, 1.0]`, or `None` when no producer has published one.
547    pub fn progress_override(&self) -> Option<f64> {
548        let ppm = self
549            .progress_override_ppm
550            .load(std::sync::atomic::Ordering::Relaxed);
551        (ppm != u64::MAX).then(|| (ppm.min(1_000_000)) as f64 / 1_000_000.0)
552    }
553
554    /// The producer-elapsed seconds recorded with the override, or
555    /// `None` when unset (no producer, or a producer that publishes
556    /// the fraction only).
557    pub fn progress_override_elapsed_secs(&self) -> Option<f64> {
558        let ms = self
559            .progress_override_elapsed_ms
560            .load(std::sync::atomic::Ordering::Relaxed);
561        (ms != u64::MAX).then(|| ms as f64 / 1000.0)
562    }
563
564    /// Increment counter for a specific error type. Creates the
565    /// counter on first occurrence of each error name. The new
566    /// counter is read by the
567    /// [`DynamicCapture`](nmbrs_metrics::component::DynamicCapture)
568    /// hook on every capture tick — registration on `Component` is implicit
569    /// through the hook, not a per-name `register_instrument` call.
570    /// Top-N error types by count, rendered `name=count` comma-joined —
571    /// empty string when no typed errors were recorded. Gives failure
572    /// messages their WHAT (which error families drove the counters)
573    /// without a metrics query.
574    pub fn top_error_types(&self, n: usize) -> String {
575        let map = self
576            .error_type_counts
577            .lock()
578            .unwrap_or_else(|e| e.into_inner());
579        let mut v: Vec<(String, u64)> = map
580            .iter()
581            .map(|(k, c)| (k.clone(), c.get()))
582            .filter(|(_, c)| *c > 0)
583            .collect();
584        v.sort_by_key(|e| std::cmp::Reverse(e.1));
585        v.truncate(n);
586        v.iter()
587            .map(|(k, c)| format!("{k}={c}"))
588            .collect::<Vec<_>>()
589            .join(", ")
590    }
591
592    pub fn count_error_type(&self, error_name: &str) {
593        let mut map = self
594            .error_type_counts
595            .lock()
596            .unwrap_or_else(|e| e.into_inner());
597        let counter = map.entry(error_name.to_string()).or_insert_with(|| {
598            Arc::new(Counter::new(
599                self.labels.with("name", format!("errors.{error_name}")),
600            ))
601        });
602        counter.inc();
603    }
604
605    /// Capture an absolute snapshot (counters at their current value,
606    /// timer histograms drained as deltas).
607    ///
608    /// Used by the legacy per-activity capture thread. For the component
609    /// tree scheduler, use
610    /// [`capture_delta`](nmbrs_metrics::component::Component::capture_delta)
611    /// instead.
612    pub fn capture(&self, interval: std::time::Duration) -> MetricSet {
613        use nmbrs_metrics::snapshot::split_name_label;
614        let service_snap = self.service_time.snapshot();
615        let wait_snap = self.wait_time.snapshot();
616        let response_snap = self.response_time.snapshot();
617        let tries_snap = self.tries_histogram.snapshot();
618        let now = Instant::now();
619        let mut snap = MetricSet::at(now, interval);
620
621        let (n, lbl) = split_name_label(self.service_time.labels());
622        snap.insert_histogram(n, lbl, service_snap.histogram, now);
623        let (n, lbl) = split_name_label(self.wait_time.labels());
624        snap.insert_histogram(n, lbl, wait_snap.histogram, now);
625        let (n, lbl) = split_name_label(self.response_time.labels());
626        snap.insert_histogram(n, lbl, response_snap.histogram, now);
627        // result_success: a histogram when Timed, a plain count when
628        // Counted (SRD-91 detail mode).
629        match &self.result_success {
630            OutcomeInstrument::Timed(t) => {
631                let (n, lbl) = split_name_label(t.labels());
632                snap.insert_histogram(n, lbl, t.snapshot().histogram, now);
633            }
634            OutcomeInstrument::Counted(c) => {
635                let (n, lbl) = split_name_label(c.labels());
636                snap.insert_counter(n, lbl, c.get(), now);
637            }
638        }
639
640        let (n, lbl) = split_name_label(self.cycles_total.labels());
641        snap.insert_counter(n, lbl, self.cycles_total.get(), now);
642        let (n, lbl) = split_name_label(self.skips_total.labels());
643        snap.insert_counter(n, lbl, self.skips_total.get(), now);
644        let (n, lbl) = split_name_label(self.errors_total.labels());
645        snap.insert_counter(n, lbl, self.errors_total.get(), now);
646        let (n, lbl) = split_name_label(self.stanzas_total.labels());
647        snap.insert_counter(n, lbl, self.stanzas_total.get(), now);
648        let (n, lbl) = split_name_label(self.daemon_cancelled_total.labels());
649        snap.insert_counter(n, lbl, self.daemon_cancelled_total.get(), now);
650        let (n, lbl) = split_name_label(self.daemon_errors_total.labels());
651        snap.insert_counter(n, lbl, self.daemon_errors_total.get(), now);
652        let (n, lbl) = split_name_label(self.result_elements.labels());
653        snap.insert_counter(n, lbl, self.result_elements.get(), now);
654        let (n, lbl) = split_name_label(self.result_bytes.labels());
655        snap.insert_counter(n, lbl, self.result_bytes.get(), now);
656        let (n, lbl) = split_name_label(self.tries_histogram.labels());
657        snap.insert_histogram(n, lbl, tries_snap, now);
658
659        let error_counts = self
660            .error_type_counts
661            .lock()
662            .unwrap_or_else(|e| e.into_inner());
663        for counter in error_counts.values() {
664            let (n, lbl) = split_name_label(counter.labels());
665            snap.insert_counter(n, lbl, counter.get(), now);
666        }
667
668        snap
669    }
670
671    /// Register dispensers for adapter-specific metrics capture.
672    pub fn set_dispensers(&self, dispensers: Arc<Vec<Arc<dyn crate::adapter::OpDispenser>>>) {
673        *self.dispensers.lock().unwrap_or_else(|e| e.into_inner()) = Some(dispensers);
674    }
675
676    /// Register the per-template validation metrics so the progress
677    /// thread can read live relevancy aggregates.
678    pub fn set_validation_metrics(&self, vms: Arc<Vec<Arc<crate::validation::ValidationMetrics>>>) {
679        *self
680            .validation_metrics
681            .lock()
682            .unwrap_or_else(|e| e.into_inner()) = Some(vms);
683    }
684
685    /// Snapshot live relevancy aggregates from every registered
686    /// validation-metrics instance (one per op template that declared
687    /// `relevancy:`). Non-destructive — safe to call every frame.
688    pub fn collect_relevancy_live(&self) -> Vec<crate::validation::RelevancyLive> {
689        let mut out = Vec::new();
690        if let Ok(guard) = self.validation_metrics.lock()
691            && let Some(ref vms) = *guard
692        {
693            for vm in vms.iter() {
694                out.extend(vm.live_snapshot());
695            }
696        }
697        out
698    }
699
700    /// Collect every status-line value whose name matches one of
701    /// `patterns`. Patterns are glob-style (`*` for any run of
702    /// characters, `?` for a single character; literal otherwise),
703    /// matched against the canonical names below. Returns formatted
704    /// ` name:value` strings ready to concatenate into the inline
705    /// progress / DONE summary line, in pattern declaration order
706    /// with duplicates suppressed.
707    ///
708    /// Supported metric families:
709    /// - **Relevancy aggregates** — one entry per registered
710    ///   `relevancy.functions:` (e.g. `recall`, `precision`,
711    ///   `f1`). The relevancy cutoff rides on the metric's
712    ///   `k` / `r` labels rather than the family name.
713    ///   Value: `total_mean × 100` as a percent.
714    /// - **Latency** — `latency_p50`, `latency_p99`, `latency_max`,
715    ///   `latency_mean`, sourced from `service_time` (the per-op
716    ///   timer, exclusive of wait time). Value: auto-scaled
717    ///   duration via [`nmbrs_metrics::reporters::summary::format_duration`].
718    pub fn collect_status_values(&self, patterns: &[String]) -> Vec<String> {
719        if patterns.is_empty() {
720            return Vec::new();
721        }
722        // Build the candidate list once. Order is stable so
723        // pattern ordering, not iteration order, drives the
724        // output sequence.
725        let mut candidates: Vec<(String, String)> = Vec::new();
726        for live in self.collect_relevancy_live() {
727            // Zero evaluations (e.g. every op `if:`-skipped) means
728            // there is no measurement — omit the chip rather than
729            // fabricating `recall:0.00%` from an empty aggregate.
730            if live.total_count == 0 {
731                continue;
732            }
733            candidates.push((live.name, format!("{:.2}%", live.total_mean * 100.0)));
734        }
735        let snap = self.service_time.peek_snapshot();
736        let h = &snap.histogram;
737        if !h.is_empty() {
738            let fmt = nmbrs_metrics::reporters::summary::format_duration;
739            candidates.push((
740                "latency_p50".to_string(),
741                fmt(h.value_at_quantile(0.50) as f64),
742            ));
743            candidates.push((
744                "latency_p99".to_string(),
745                fmt(h.value_at_quantile(0.99) as f64),
746            ));
747            candidates.push(("latency_max".to_string(), fmt(h.max() as f64)));
748            candidates.push(("latency_mean".to_string(), fmt(h.mean())));
749        }
750        // KEY-METRIC accent: `status_metrics:` selection is the
751        // workload author saying "this is the number I'm running the
752        // test for" — the chip gets its own bright palette slot
753        // (bold bright magenta; used by nothing else on the line) so
754        // it reads first among the dim bookkeeping counters.
755        let color = crate::observer::use_color();
756        let accent = if color { "\x1b[1;95m" } else { "" };
757        let reset = if color { "\x1b[0m" } else { "" };
758        let mut out: Vec<String> = Vec::new();
759        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
760        for pat in patterns {
761            for (name, val) in &candidates {
762                if !seen.contains(name.as_str()) && glob_match(pat, name) {
763                    seen.insert(name.clone());
764                    let label = chip_display_label(name);
765                    out.push(format!(" {accent}{label}:{val}{reset}"));
766                }
767            }
768        }
769        out
770    }
771
772    /// The PRIMARY key metric as a raw numeric sample: the first
773    /// `status_metrics:` pattern's first match, in the same
774    /// candidate order [`Self::collect_status_values`] uses
775    /// (relevancy aggregates as percent, then service-time
776    /// quantiles as milliseconds). Feeds the key-metric row's
777    /// gutter cell TREND (SRD-92 R4): the cell shows the metric's
778    /// history as a sparkline — the current value's single
779    /// placement is the chips text in the row body. `None` when
780    /// nothing matches or nothing has been measured yet.
781    pub fn collect_status_primary(&self, patterns: &[String]) -> Option<(String, f64)> {
782        if patterns.is_empty() {
783            return None;
784        }
785        let mut candidates: Vec<(String, f64)> = Vec::new();
786        for live in self.collect_relevancy_live() {
787            if live.total_count == 0 {
788                continue;
789            }
790            candidates.push((live.name, live.total_mean * 100.0));
791        }
792        let snap = self.service_time.peek_snapshot();
793        let h = &snap.histogram;
794        if !h.is_empty() {
795            let ms = |n: f64| n / 1e6;
796            candidates.push((
797                "latency_p50".to_string(),
798                ms(h.value_at_quantile(0.50) as f64),
799            ));
800            candidates.push((
801                "latency_p99".to_string(),
802                ms(h.value_at_quantile(0.99) as f64),
803            ));
804            candidates.push(("latency_max".to_string(), ms(h.max() as f64)));
805            candidates.push(("latency_mean".to_string(), ms(h.mean())));
806        }
807        for pat in patterns {
808            for (name, val) in &candidates {
809                if glob_match(pat, name) {
810                    return Some((name.clone(), *val));
811                }
812            }
813        }
814        None
815    }
816
817    /// Collect status counters from all registered dispensers.
818    pub fn collect_status_counters(&self) -> Vec<(String, u64)> {
819        let mut counters = Vec::new();
820        if let Ok(guard) = self.dispensers.lock()
821            && let Some(ref disps) = *guard
822        {
823            for disp in disps.iter() {
824                for (name, total) in disp.status_counters() {
825                    counters.push((name.to_string(), total));
826                }
827            }
828        }
829        counters
830    }
831}
832
833/// Map a canonical status-chip metric name to its short display
834/// label. Keeps the underlying pattern-matching identity stable
835/// (workloads' `status_metrics: ["latency_*"]` keeps working)
836/// while the operator-facing chip stays terse — `P50` / `P99` /
837/// `Pmax` / `Pmean` instead of `latency_p50` / etc. Identity
838/// passthrough for any name without a shortcut.
839fn chip_display_label(name: &str) -> &str {
840    match name {
841        "latency_p50" => "P50",
842        "latency_p99" => "P99",
843        "latency_max" => "Pmax",
844        "latency_mean" => "Pmean",
845        other => other,
846    }
847}
848
849/// [`DynamicCapture`] adapter for [`ActivityMetrics`]. Captures the
850/// dynamic surface — per-error-type counters and adapter-specific
851/// metrics from registered dispensers — that isn't known at
852/// `register_on` time and therefore can't live in the static
853/// component instrument registry.
854struct ActivityMetricsDynamic {
855    metrics: Arc<ActivityMetrics>,
856    /// Per-counter previous-value baseline for delta emission on
857    /// the `drain=true` path. Keyed by `counter.labels().identity_hash()`.
858    /// Mirrors the per-component baseline that `Component` keeps for
859    /// registered counters; per-error-type counters live outside
860    /// the registry so the baseline travels with the hook.
861    ///
862    /// Why deltas: `MetricSet::combine_into` for Counter is
863    /// `total = a.total.saturating_add(b.total)` — the cascade
864    /// coalesce path treats Counter.total as the per-interval
865    /// delta and SUMS across intervals. Emitting absolutes here
866    /// would inflate as the cascade coalesces.
867    prev_counters: std::sync::Mutex<std::collections::HashMap<u64, u64>>,
868}
869
870impl nmbrs_metrics::component::DynamicCapture for ActivityMetricsDynamic {
871    fn capture_into(&self, out: &mut MetricSet, now: Instant, drain: bool) {
872        use nmbrs_metrics::snapshot::{MetricType, MetricValue, split_name_label};
873
874        // Per-error-type counters.
875        // - drain=true (cadence path): emit deltas vs. the stored
876        //   baseline so cascade coalesce sums across intervals
877        //   without inflation.
878        // - drain=false (peek path): emit absolute totals.
879        let error_counts = self
880            .metrics
881            .error_type_counts
882            .lock()
883            .unwrap_or_else(|e| e.into_inner());
884        if drain {
885            let mut prev = self.prev_counters.lock().unwrap_or_else(|e| e.into_inner());
886            for counter in error_counts.values() {
887                let (name, lbl) = split_name_label(counter.labels());
888                let current = counter.get();
889                let key = counter.labels().identity_hash();
890                let previous = prev.insert(key, current).unwrap_or(0);
891                out.insert_counter(name, lbl, current.saturating_sub(previous), now);
892            }
893        } else {
894            for counter in error_counts.values() {
895                let (name, lbl) = split_name_label(counter.labels());
896                out.insert_counter(name, lbl, counter.get(), now);
897            }
898        }
899
900        // Adapter-specific metrics from each registered dispenser.
901        // Passthrough — the adapter decides delta vs. absolute
902        // semantics for its own metrics.
903        if let Some(ref disps) = *self
904            .metrics
905            .dispensers
906            .lock()
907            .unwrap_or_else(|e| e.into_inner())
908        {
909            for dispenser in disps.iter() {
910                for (family, metric_labels, value) in dispenser.adapter_metrics() {
911                    let mtype = match &value {
912                        MetricValue::Counter(_) => MetricType::Counter,
913                        MetricValue::Gauge(_) => MetricType::Gauge,
914                        MetricValue::Histogram(_) => MetricType::Summary,
915                        MetricValue::BucketedHistogram(_) => MetricType::Histogram,
916                        MetricValue::Info(_) => MetricType::Info,
917                        MetricValue::StateSet(_) => MetricType::StateSet,
918                    };
919                    out.insert_metric(family, mtype, metric_labels, value, now);
920                }
921            }
922        }
923    }
924}
925
926/// A running activity.
927pub struct Activity {
928    pub config: ActivityConfig,
929    pub labels: Labels,
930    pub metrics: Arc<ActivityMetrics>,
931    pub op_sequence: OpSequence,
932    /// SRD-83 — this phase node's own scope kernel (the structural
933    /// walk's `cached_kernel`). Stop-condition predicates bind to THIS
934    /// native scope as it sits, not a conjured root. `None` when the
935    /// phase has no installed kernel (then no conditions evaluate).
936    pub phase_kernel: Option<Arc<crate::scope_kernel::ScopeKernel>>,
937    /// SRD-82 — the phase shell's `crate::error_policy::ErrorPolicy`
938    /// (op router + aggregate guard), resolved at scope-init from the
939    /// parent policy so equal configs share one instance. Built
940    /// standalone only on the test/library path ([`Self::with_params`]).
941    pub error_policy: Arc<crate::error_policy::ErrorPolicy>,
942    /// Source factory — creates per-fiber readers. All phases go through
943    /// sources. `cycles: N` desugars to `range(0, N)`.
944    source_factory: Arc<dyn polydat::iteration::source::DataSourceFactory>,
945    /// Resolved workload parameters (constant per run).
946    pub workload_params: Arc<std::collections::HashMap<String, String>>,
947    /// Shared flag: set to true when a `stop` error handler fires.
948    /// All fibers check this and exit their loop when set.
949    pub stop_flag: Arc<std::sync::atomic::AtomicBool>,
950    /// Per-execution walk-stop flag (SRD-82 Part 4), cloned from this
951    /// execution's `WorkloadShell`. Distinct from `stop_flag` (which is
952    /// this phase's OWN stop): set when the scenario WALK halts — a
953    /// sibling phase failed (a fault) or a stop condition tripped — so
954    /// in-flight fibers abort cooperatively and a concurrent
955    /// (`Bounded(N>1)`) sibling phase stops instead of draining. `None`
956    /// outside a walk (tests, the library shim) → never aborts.
957    pub walk_stop: Option<Arc<std::sync::atomic::AtomicBool>>,
958    /// SRD-82 Part 6 — set ONLY for a daemon phase: the daemon-group
959    /// completion flag, latched by the scenario shell once the scope's
960    /// foreground phases finish. A daemon phase's fibers poll it at their
961    /// cooperative boundaries and exit, so the daemon stops when the
962    /// foreground it shadows completes. `None` for foreground phases.
963    pub daemon_stop: Option<Arc<std::sync::atomic::AtomicBool>>,
964    /// First error message that triggered `stop_flag` — captured
965    /// once (the first stopping error wins, subsequent fibers'
966    /// errors don't overwrite). Surfaced in the phase-level
967    /// error so the user doesn't have to grep the per-cycle
968    /// log to learn what actually stopped the run.
969    pub stop_reason: Arc<std::sync::Mutex<Option<String>>>,
970    /// SRD-83 Part 5 — the two-axis Outcome of the FIRST stop-condition
971    /// trip that stopped this phase, latched together with `stop_reason`
972    /// (same first-stopper-wins discipline, written inside the same slot
973    /// win). A `stop` effect latches Interrupted+Succeeded — a clean
974    /// early halt whose partial result the phase keeps; `fail`/`abort`
975    /// latch Interrupted+Failed. The executor reads this at phase end so
976    /// the shell adopts the condition's DECLARED outcome instead of
977    /// deriving failure from the bare stop flag. `None` whenever the
978    /// stop came from any other source (error router `stop` verb, walk
979    /// stop, poll timeout, Ctrl-C) — those keep failure semantics.
980    pub stop_outcome: Arc<std::sync::Mutex<Option<crate::phase_outcome::Outcome>>>,
981    /// SRD-76 — chronologically ordered per-cycle error
982    /// records. Populated by the per-cycle dispatch path
983    /// (alongside the existing `stop_reason` formatted
984    /// string) so the executor can drain a structured
985    /// list into `PhaseOutcome.errors` at phase end. The
986    /// `stop_reason` string stays — it's the single
987    /// load-bearing format the executor reads to compose
988    /// the `phase 'X' stopped by error handler:` log
989    /// line. This buffer is the orthogonal structured
990    /// projection.
991    pub phase_errors: Arc<std::sync::Mutex<Vec<crate::phase_outcome::PhaseErrorDetail>>>,
992    /// Final validation metrics frame, populated after all cycles complete.
993    /// Read by the metrics capture thread after the activity finishes.
994    pub validation_frame: Arc<std::sync::Mutex<Option<MetricSet>>>,
995    /// Optional handle to this activity's component in the session tree.
996    /// Set by the runner via [`Self::attach_component`] before
997    /// execution; when present, the executor declares the
998    /// `concurrency` control on it (SRD 23) and wires the
999    /// `crate::fiber_pool::ConcurrencyApplier` so runtime writes
1000    /// resize the fiber pool.
1001    pub component: Option<Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>>,
1002    /// SRD-32a Push 3 — workload-root wrapper-composition
1003    /// override. When populated (from the workload's
1004    /// `wrappers: { order: [...] }` block), every op
1005    /// template that doesn't carry its own
1006    /// per-template override uses this innermost-to-outermost
1007    /// list as its composition order. Validated against the
1008    /// per-op triggered set at cascade time; mismatch is a
1009    /// hard error per SRD-32a §"Workload-level override".
1010    pub wrappers_override: Option<Vec<String>>,
1011    /// SRD-32a Push 3 — CLI `--wrap-default-order` override.
1012    /// Replaces the resolver's built-in `DEFAULT_ORDER`
1013    /// tiebreaker for this activity. `None` ⇒ resolver uses
1014    /// the built-in order. Distinct from
1015    /// `wrappers_override`: that pins the per-op stack;
1016    /// this changes the tiebreaker used when constraints
1017    /// leave order ambiguous.
1018    pub wrap_default_order: Option<Vec<String>>,
1019    /// Shared retry-exemplar sampling config (`exec_events`): every
1020    /// tries wrapper in this activity that does NOT pin its own
1021    /// `retry_exemplar_*` op params samples through this cell, so
1022    /// the `retry_exemplar_rate` / `retry_exemplar_max_hz` dynamic
1023    /// controls (declared in [`Self::attach_component`]) move them
1024    /// all with one atomic store — push-on-set, no per-op control
1025    /// traffic, and the read only happens on the retry path.
1026    pub exemplar_config: Arc<crate::exec_events::ExemplarConfig>,
1027    /// Shared per-phase retry advisory gate (`exec_events`): one
1028    /// first-sighting advisory per error class per phase, capped —
1029    /// the default-on signal that the retry loop started absorbing
1030    /// errors. Ops opt out with `retry_advisory: false`.
1031    pub advisory_gate: Arc<crate::exec_events::AdvisoryGate>,
1032    /// Phase memo — a short operator-visible string that the
1033    /// `memo` wrapper publishes via `before:` / `after:`
1034    /// templates. Read by the inline-status readout and
1035    /// rendered as `[[ <memo> ]]` above the status line when
1036    /// non-empty. Lock-free atomic so the inline thread can
1037    /// load it every tick without blocking the executor.
1038    /// Default empty.
1039    pub memo: Arc<arc_swap::ArcSwap<String>>,
1040    /// Phase gutter — the contextual left-gutter cell content that
1041    /// the `gutter` wrapper publishes (distinct from `memo`, which
1042    /// owns the `[[ ... ]]` header line). `None` ⇒ the display
1043    /// derives the cell automatically (completion bar for metered
1044    /// phases, latency trend for daemons); `Some` overrides that
1045    /// derivation with the workload-declared spec. Lock-free
1046    /// atomic for the same reason as `memo`.
1047    pub gutter: Arc<arc_swap::ArcSwapOption<crate::wrappers::gutter::GutterSpec>>,
1048    /// The op-declared DURING-execution gutter template (kind +
1049    /// template), retained for the guaranteed one-final-update at
1050    /// phase end when no `final:` form is declared.
1051    pub gutter_template: std::sync::Mutex<Option<crate::wrappers::gutter::GutterTemplate>>,
1052    /// The op-declared `final:` gutter template — evaluated once at
1053    /// phase end (wires first, status-metric aggregates as fallback)
1054    /// and rendered as the ✓ outcome detail line's gutter cell.
1055    pub gutter_final_template: std::sync::Mutex<Option<crate::wrappers::gutter::GutterTemplate>>,
1056    /// SRD-75 phase-poll context. When present, the fiber
1057    /// loop checks the predicate after each source-exhaustion
1058    /// event; if false and the timeout hasn't elapsed, the
1059    /// source factory rewinds and the loop continues.
1060    /// `None` ⇒ no phase-poll (standard activity semantics).
1061    /// Set by the executor at run-phase entry; not part of
1062    /// the YAML-derived `ActivityConfig`.
1063    pub phase_poll: Option<PhasePollContext>,
1064}
1065
1066/// Runtime context for SRD-75 phase-level poll. Carried on
1067/// `Activity` when the phase declares a `poll:` block;
1068/// consumed by the fiber loop after each source-exhaustion
1069/// event to decide whether to terminate (predicate satisfied
1070/// or timeout) or rewind and run another iteration.
1071#[derive(Clone)]
1072pub struct PhasePollContext {
1073    /// Handle to the phase scope kernel. After each iteration the fiber loop
1074    /// resolves [`crate::wrappers::condition::UNTIL_BINDING`] through
1075    /// `CycleWires` over the per-fiber kernel — the same call an op-level
1076    /// `poll:` makes — and ends the loop when it reads truthy per
1077    /// [`crate::wrappers::condition::is_truthy`]. `lookup` would not do: the
1078    /// predicate is a DYNAMIC binding fed by per-iteration capture writes, so
1079    /// it has to be pulled or it returns the last-evaluated value forever.
1080    pub kernel: Arc<crate::scope_kernel::ScopeKernel>,
1081    /// Sleep between iterations (after a predicate check
1082    /// returns "not done").
1083    pub interval: std::time::Duration,
1084    /// Wall-clock cap on the whole poll loop. Computed at
1085    /// run-phase entry as `Instant::now() + timeout_ms`.
1086    pub deadline: std::time::Instant,
1087    /// `Instant` the loop started — used to compute the
1088    /// elapsed-time value emitted under `metric_name`
1089    /// (if set) on successful completion.
1090    pub started_at: std::time::Instant,
1091    /// Optional named metric to emit on successful loop
1092    /// completion (predicate fired). Value is the elapsed
1093    /// wall-clock decoded per the existing `_ns` / `_us` /
1094    /// `_ms` / `_s` / `_m` / `_h` suffix convention. `None`
1095    /// ⇒ no metric written.
1096    pub metric_name: Option<String>,
1097    /// Tolerated consecutive retryable inner-op errors
1098    /// before the loop propagates the error. Mirrors the
1099    /// per-op `PollingDispenser` `max_error_retries`
1100    /// semantics. Default `0` (strict).
1101    pub max_error_retries: u32,
1102    /// What to do when the `deadline` fires without
1103    /// satisfying the predicate. SRD-75 §"on_timeout":
1104    /// - `Error` (default) — set the activity's
1105    ///   stop_flag + stop_reason. The phase returns an
1106    ///   error; the scenario walker's error-routing
1107    ///   policy decides whether sibling phases continue.
1108    /// - `Abort` — additionally call
1109    ///   `session_signals::request_stop()` so the whole
1110    ///   scenario terminates. The workload-author
1111    ///   declares the predicate's satisfaction as a
1112    ///   precondition for any downstream phase being
1113    ///   meaningful; a stuck synchronizer invalidates
1114    ///   the rest of the run.
1115    pub on_timeout: PhasePollTimeoutPolicy,
1116    /// SRD-75 (C5) — strict-gate selectors: each must resolve to a
1117    /// registered instrument before the gate's predicate is trusted.
1118    /// While any selector is unresolved the gate HOLDS (the predicate
1119    /// is not consulted — an unregistered family reads 0.0, which
1120    /// could satisfy a `>=`-shaped predicate spuriously); past
1121    /// [`Self::require_grace`] an unresolved selector is a hard
1122    /// `poll_require` failure.
1123    pub require: Vec<String>,
1124    /// Grace deadline for [`Self::require`] resolution: the first
1125    /// poll interval after loop start (late registration is normal —
1126    /// a producing daemon registers its instruments as it spins up).
1127    pub require_grace: std::time::Instant,
1128}
1129
1130/// SRD-75 `on_timeout` policy — see [`PhasePollContext::on_timeout`].
1131#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1132pub enum PhasePollTimeoutPolicy {
1133    /// Phase fails; scenario walker's error-routing policy
1134    /// decides downstream behaviour.
1135    #[default]
1136    Error,
1137    /// Phase fails AND `session_signals::request_stop()`
1138    /// is called — the scenario walker observes the
1139    /// global stop on its next iteration check and
1140    /// terminates the whole run.
1141    Abort,
1142}
1143
1144/// Invoke [`DriverAdapter::declare_controls`] for each unique adapter
1145/// instance against the given parent component, deduping by
1146/// `Arc`-pointer identity. The same adapter `Arc` may be entered
1147/// into the map under multiple alias keys; this guarantees each
1148/// physical instance gets exactly one declaration call per
1149/// invocation of this helper.
1150///
1151/// Called from two sites:
1152///
1153/// 1. The phase executor at component-attach time, so
1154///    `dryrun=controls` walks a populated tree before any
1155///    cycles run.
1156/// 2. [`Activity::run_with_adapters`] at run start, so adapters
1157///    that only ever materialize at run time still get declared.
1158///
1159/// Adapter implementations are expected to be idempotent — calling
1160/// this helper twice against the same parent must not produce
1161/// duplicate subcomponents or duplicate-name control declarations.
1162pub fn declare_adapter_controls(
1163    adapters: &std::collections::HashMap<String, Arc<dyn DriverAdapter>>,
1164    component: &Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
1165) {
1166    let mut seen: Vec<*const dyn DriverAdapter> = Vec::new();
1167    for adapter in adapters.values() {
1168        let ptr = Arc::as_ptr(adapter);
1169        if seen.contains(&ptr) {
1170            continue;
1171        }
1172        seen.push(ptr);
1173        adapter.declare_controls(component);
1174    }
1175}
1176
1177impl Activity {
1178    pub fn new(config: ActivityConfig, parent_labels: &Labels, op_sequence: OpSequence) -> Self {
1179        Self::with_params(
1180            config,
1181            parent_labels,
1182            op_sequence,
1183            std::collections::HashMap::new(),
1184        )
1185    }
1186
1187    pub fn with_params(
1188        config: ActivityConfig,
1189        parent_labels: &Labels,
1190        op_sequence: OpSequence,
1191        params: std::collections::HashMap<String, String>,
1192    ) -> Self {
1193        // Library / test path: no session root policy, so build a
1194        // standalone (un-shared) policy from the config. The real
1195        // execution path resolves the shared instance from the parent
1196        // policy and passes it to `with_resolution`.
1197        let error_policy =
1198            crate::error_policy::ErrorPolicy::standalone(crate::error_policy::PolicyConfig::new(
1199                config.error_spec.clone(),
1200                config.error_rate_max,
1201            ));
1202        let metric_detail = metric_detail_from_params(&params);
1203        Self::with_resolution(
1204            config,
1205            parent_labels,
1206            op_sequence,
1207            params,
1208            ActivityResolution {
1209                sigdigs: nmbrs_metrics::instruments::histogram::DEFAULT_HDR_SIGDIGS,
1210                error_policy,
1211                // This shim is the no-phase-kernel path (tests / library use);
1212                // the executor's run_phase path passes the phase node's kernel.
1213                phase_kernel: None,
1214                metric_detail: &metric_detail,
1215            },
1216        )
1217    }
1218
1219    /// Build an activity from the settings its execution resolved
1220    /// (see [`ActivityResolution`]). Used by the executor after it
1221    /// resolves `hdr.sigdigs` from the session root (SRD 40) and the
1222    /// phase's shared error policy and kernel. Callers that don't
1223    /// resolve from a tree use [`Self::with_params`], which defaults to
1224    /// [`nmbrs_metrics::instruments::histogram::DEFAULT_HDR_SIGDIGS`]
1225    /// and a standalone policy.
1226    pub fn with_resolution(
1227        config: ActivityConfig,
1228        parent_labels: &Labels,
1229        op_sequence: OpSequence,
1230        params: std::collections::HashMap<String, String>,
1231        resolution: ActivityResolution<'_>,
1232    ) -> Self {
1233        let ActivityResolution {
1234            sigdigs,
1235            error_policy,
1236            phase_kernel,
1237            metric_detail,
1238        } = resolution;
1239        let labels = parent_labels.clone();
1240        // SRD-91 — counter-vs-timer detail for the op-outcome instruments,
1241        // resolved by the caller from the run's effective params (the
1242        // executor passes the CLI-overlaid set; the library shim derives
1243        // from its own params). Default: timers.
1244        let metrics = Arc::new(ActivityMetrics::with_sigdigs(
1245            &labels,
1246            sigdigs,
1247            metric_detail,
1248        ));
1249        // All phases go through sources. cycles: N desugars to range(0, N).
1250        // Named cursors in Polydat provide their own factory via config.source_factory.
1251        let source_factory: Arc<dyn polydat::iteration::source::DataSourceFactory> =
1252            config.source_factory.clone().unwrap_or_else(|| {
1253                Arc::new(polydat::iteration::source::RangeSourceFactory::named(
1254                    "cycles",
1255                    0,
1256                    config.cycles,
1257                ))
1258            });
1259
1260        Self {
1261            config,
1262            labels,
1263            metrics,
1264            op_sequence,
1265            error_policy,
1266            phase_kernel,
1267            source_factory,
1268            workload_params: Arc::new(params),
1269            stop_flag: Arc::new(std::sync::atomic::AtomicBool::new(false)),
1270            walk_stop: None,
1271            daemon_stop: None,
1272            stop_reason: Arc::new(std::sync::Mutex::new(None)),
1273            stop_outcome: Arc::new(std::sync::Mutex::new(None)),
1274            phase_errors: Arc::new(std::sync::Mutex::new(Vec::new())),
1275            validation_frame: Arc::new(std::sync::Mutex::new(None)),
1276            component: None,
1277            wrappers_override: None,
1278            wrap_default_order: None,
1279            exemplar_config: Arc::new(crate::exec_events::ExemplarConfig::new(0.0, 5.0)),
1280            advisory_gate: Arc::new(crate::exec_events::AdvisoryGate::new()),
1281            memo: Arc::new(arc_swap::ArcSwap::from_pointee(String::new())),
1282            gutter: Arc::new(arc_swap::ArcSwapOption::empty()),
1283            gutter_template: std::sync::Mutex::new(None),
1284            gutter_final_template: std::sync::Mutex::new(None),
1285            phase_poll: None,
1286        }
1287    }
1288
1289    /// Whether this execution's scenario walk has halted (SRD-82 Part
1290    /// 4). Fibers poll this at their cooperative boundaries, alongside
1291    /// `stop_flag` and `session_signals::stop_requested()`, to abort an
1292    /// in-flight phase when a sibling failed or a stop condition
1293    /// tripped. `false` when no walk-stop flag is wired (tests / shim).
1294    #[inline]
1295    pub fn walk_stop_requested(&self) -> bool {
1296        self.walk_stop
1297            .as_ref()
1298            .is_some_and(|f| f.load(std::sync::atomic::Ordering::Relaxed))
1299    }
1300
1301    /// Whether this (daemon) phase's group has signalled completion
1302    /// (SRD-82 Part 6) — the scenario shell latches `daemon_stop` once
1303    /// the scope's foreground phases finish, and the daemon's fibers poll
1304    /// this to exit. `false` for a foreground phase (no flag wired).
1305    #[inline]
1306    pub fn daemon_stop_requested(&self) -> bool {
1307        self.daemon_stop
1308            .as_ref()
1309            .is_some_and(|f| f.load(std::sync::atomic::Ordering::Relaxed))
1310    }
1311
1312    /// SRD-92 Step 0 — the cooperative-stop view at a loop BREAK boundary:
1313    /// the activity `stop_flag`, the global / per-execution session stop,
1314    /// the SRD-83 `walk_stop`, and the SRD-82 P6 `daemon_stop`. Replaces the
1315    /// scattered per-flag loads at the fiber boundaries. (The
1316    /// failure-determining return deliberately uses a different set that
1317    /// EXCLUDES `daemon_stop` — see
1318    /// [`crate::session_signals::StopView::abnormal`].)
1319    #[inline]
1320    pub fn stopped(&self) -> bool {
1321        self.stop_flag.load(std::sync::atomic::Ordering::Relaxed)
1322            || crate::session_signals::stop_requested()
1323            || self.walk_stop_requested()
1324            || self.daemon_stop_requested()
1325    }
1326
1327    /// The portable [`StopView`](crate::session_signals::StopView) for this
1328    /// activity — handed to the `while:` wrapper (a `Send + 'static`
1329    /// dispenser that cannot borrow the activity) so its loop observes the
1330    /// full stop set, not just `stop_flag`. Built once at wrapper
1331    /// construction, after `walk_stop` / `daemon_stop` are set in `run_phase`.
1332    pub fn stop_view(&self) -> crate::session_signals::StopView {
1333        crate::session_signals::StopView::new(
1334            Some(self.stop_flag.clone()),
1335            self.walk_stop.clone(),
1336            self.daemon_stop.clone(),
1337        )
1338    }
1339
1340    /// SRD-32a Push 3 — set the workload-root wrapper-
1341    /// composition override on this activity. Pass `None` to
1342    /// clear; pass `Some(order)` to install. The order list
1343    /// is innermost-to-outermost; per-op `wrappers:` blocks
1344    /// shadow this entry entirely.
1345    pub fn set_wrappers_override(&mut self, order: Option<Vec<String>>) {
1346        self.wrappers_override = order;
1347    }
1348
1349    /// SRD-32a Push 3 — set the resolver's default-order
1350    /// tiebreaker for this activity (CLI
1351    /// `--wrap-default-order`). `None` ⇒ the resolver uses
1352    /// its built-in `DEFAULT_ORDER` list.
1353    pub fn set_wrap_default_order(&mut self, order: Option<Vec<String>>) {
1354        self.wrap_default_order = order;
1355    }
1356
1357    /// Attach this activity to its component in the session tree.
1358    /// The runner creates the component and installs it here so
1359    /// `run_with_*` can register appliers on the activity's
1360    /// declared controls.
1361    ///
1362    /// Structural control declarations happen here — not at run
1363    /// time — so `dryrun=controls` (and every other pre-execution
1364    /// discovery path) sees the activity's controls without
1365    /// needing to start any cycles. Appliers that depend on
1366    /// run-time state (the fiber pool, the rate limiter) are
1367    /// registered later in `run_with_adapters`.
1368    pub fn attach_component(
1369        &mut self,
1370        component: Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
1371    ) {
1372        use crate::control_catalog::{CONCURRENCY, RATE};
1373        // Derive both controls from their single-source capability descriptors
1374        // (SRD-23) — name, range, and gauge come from the same `ControlDesc`
1375        // that `describe controls` reads, so the discovery surface and the
1376        // live knob can't drift. The instance-specific appliers (fiber-pool
1377        // resize, rate limiter) are registered later in `run_with_adapters`.
1378        let concurrency_control = CONCURRENCY.build_u32(self.config.concurrency as u32);
1379        component
1380            .read()
1381            .unwrap_or_else(|e| e.into_inner())
1382            .controls()
1383            .declare(concurrency_control);
1384
1385        // Declare a `rate` control whenever the activity config has a rate
1386        // set. Its reified gauge projects ops/sec so metric sinks and the
1387        // f64-writable surface (TUI `e` prompt, web POST, Polydat
1388        // `control_set`, `optimize.servo: rate`) all read and write the same
1389        // unit. The [`RateLimiterApplier`] gets registered at run time once
1390        // the limiter exists (see `run_with_adapters`).
1391        if let Some(rate) = self.config.rate {
1392            let rate_control = RATE.build_rate(rate);
1393            component
1394                .read()
1395                .unwrap_or_else(|e| e.into_inner())
1396                .controls()
1397                .declare(rate_control);
1398        }
1399
1400        // Retry-exemplar sampling (SRD-82 Part 3b / `exec_events`):
1401        // both knobs are push-on-set — the applier is one atomic
1402        // store into the activity's shared `ExemplarConfig`, which
1403        // every unpinned tries wrapper reads (only on its retry
1404        // path). Ops that pin `retry_exemplar_*` params hold private
1405        // cells the controls deliberately do not move — authored
1406        // matter wins, the live control moves the rest.
1407        {
1408            use crate::control_catalog::{RETRY_EXEMPLAR_MAX_HZ, RETRY_EXEMPLAR_RATE};
1409            use nmbrs_metrics::controls::SyncApplier;
1410            let cfg = self.exemplar_config.clone();
1411            let rate_control = RETRY_EXEMPLAR_RATE.build_f64(0.0);
1412            rate_control.register_applier(SyncApplier::new(move |v: f64| {
1413                cfg.set_rate(v);
1414                Ok(())
1415            }));
1416            component
1417                .read()
1418                .unwrap_or_else(|e| e.into_inner())
1419                .controls()
1420                .declare(rate_control);
1421
1422            let cfg = self.exemplar_config.clone();
1423            let hz_control = RETRY_EXEMPLAR_MAX_HZ.build_f64(5.0);
1424            hz_control.register_applier(SyncApplier::new(move |v: f64| {
1425                cfg.set_max_hz(v);
1426                Ok(())
1427            }));
1428            component
1429                .read()
1430                .unwrap_or_else(|e| e.into_inner())
1431                .controls()
1432                .declare(hz_control);
1433        }
1434        // Register every static instrument owned by ActivityMetrics
1435        // on this component so the cadence reporter's tree walk
1436        // sees them. Failures here are programming errors
1437        // (duplicate family on the activity's own component) —
1438        // panic so the issue surfaces during init.
1439        {
1440            let mut guard = component.write().unwrap_or_else(|e| e.into_inner());
1441            self.metrics
1442                .register_on(&mut guard)
1443                .expect("ActivityMetrics::register_on failed on a fresh activity component");
1444        }
1445        self.component = Some(component);
1446    }
1447
1448    /// Get a shared reference to the metrics for external capture.
1449    pub fn shared_metrics(&self) -> Arc<ActivityMetrics> {
1450        self.metrics.clone()
1451    }
1452
1453    /// Run the activity with a single adapter for all ops.
1454    pub async fn run_with_driver(
1455        self,
1456        adapter: Arc<dyn DriverAdapter>,
1457        op_builder: Arc<crate::synthesis::OpBuilder>,
1458    ) -> bool {
1459        let mut adapters = std::collections::HashMap::new();
1460        let name = adapter.name().to_string();
1461        adapters.insert(name.clone(), adapter);
1462        self.run_with_adapters(adapters, &name, op_builder).await
1463    }
1464
1465    /// Run the activity with multiple adapters (SRD 38/40).
1466    ///
1467    /// Each op template's `adapter` param selects which adapter to use.
1468    /// Templates without an explicit adapter use `default_adapter`.
1469    /// At init time: maps each template to a dispenser from the
1470    /// appropriate adapter. Per fiber: creates a FiberBuilder. Per
1471    /// cycle: resolves fields via GK, executes via dispenser.
1472    /// Returns true if the activity was stopped by an error handler.
1473    pub async fn run_with_adapters(
1474        self,
1475        adapters: std::collections::HashMap<String, Arc<dyn DriverAdapter>>,
1476        default_adapter: &str,
1477        op_builder: Arc<crate::synthesis::OpBuilder>,
1478    ) -> bool {
1479        let activity = Arc::new(self);
1480        let program = op_builder.program();
1481
1482        // Init time: map each template to a dispenser from its adapter,
1483        // then wrap with result traverser for consumption/capture.
1484        //
1485        // Dryrun injection: when the session is in dryrun mode
1486        // (`config.dry_run_mode` is `Some(mode)`), inject a logical
1487        // `dryrun: <mode>` parameter into every op template's
1488        // `params` map BEFORE the wrapping cascade sees them. This
1489        // triggers the outermost `DryRunWrapper` to install for
1490        // every op; the wrapper short-circuits at cycle time and
1491        // suppresses only the outbound `execute()`.
1492        //
1493        // The real adapter's full lifecycle still runs (connect,
1494        // prepare, metadata) — `dryrun=cycle` means "construct a
1495        // fully-executable cycle path, then suppress only the
1496        // outbound call." So `dry_run_mode` is sourced from the
1497        // session config, NOT from any adapter substitution.
1498        let dryrun_mode: Option<String> = activity.config.dry_run_mode.clone();
1499        let templates_owned: Vec<nmbrs_workload::model::ParsedOp>;
1500        let templates: &[nmbrs_workload::model::ParsedOp] =
1501            if let Some(mode) = dryrun_mode.as_deref() {
1502                templates_owned = activity
1503                    .op_sequence
1504                    .templates()
1505                    .iter()
1506                    .map(|t| {
1507                        let mut clone = t.clone();
1508                        clone
1509                            .params
1510                            .insert("dryrun".into(), serde_json::Value::String(mode.to_string()));
1511                        // dryrun=fields also forces the fields wrapper
1512                        // on so the rendered op text reaches stdout
1513                        // even though DRYRUN short-circuits the
1514                        // adapter call. The fields wrapper is composed
1515                        // OUTER of dryrun (see
1516                        // wrapper_resolver::DEFAULT_ORDER), so its
1517                        // pre-execute render runs first; the
1518                        // subsequent DRYRUN short-circuit suppresses
1519                        // the real adapter call.
1520                        if mode == "fields" {
1521                            clone
1522                                .params
1523                                .insert("fields".into(), serde_json::Value::Bool(true));
1524                        }
1525                        clone
1526                    })
1527                    .collect();
1528                // The user passed `dryrun=<mode>` on the CLI — they
1529                // already know what they asked for. Keep the
1530                // marker-injection record at Debug so step-through /
1531                // session-log audits can still find it without
1532                // narrating it back on stderr every phase.
1533                crate::diag!(
1534                    crate::observer::LogLevel::Debug,
1535                    "dryrun={mode}: injected marker into {n} op template(s)",
1536                    mode = mode,
1537                    n = templates_owned.len()
1538                );
1539                &templates_owned[..]
1540            } else {
1541                activity.op_sequence.templates()
1542            };
1543
1544        // Validate all bind points are resolvable before execution
1545        let program_for_op = |name: &str| op_builder.program_for_op(name);
1546        if let Err(e) = crate::synthesis::validate_bind_points(templates, &program_for_op) {
1547            crate::diag!(crate::observer::LogLevel::Error, "error: {e}");
1548            return true;
1549        }
1550
1551        // Adapter-level dynamic controls (SRD 23). The phase
1552        // executor already declared adapter controls at attach
1553        // time so `dryrun=controls` saw them; calling again here
1554        // is the safety net for adapters that materialize only
1555        // at run time. Adapter `declare_controls` impls are
1556        // contractually idempotent — see `declare_adapter_controls`.
1557        if let Some(component) = activity.component.as_ref() {
1558            declare_adapter_controls(&adapters, component);
1559        }
1560
1561        let traversal_stats = Arc::new(crate::wrappers::TraversalStats {
1562            metrics: activity.metrics.clone(),
1563        });
1564
1565        // SRD-32a — wrapper registry + resolver. The
1566        // registry is fixed at link time (every `inventory::
1567        // submit!` block in the binary contributes one
1568        // entry); the resolver carries the validated
1569        // default-order tiebreaker. Both are built once
1570        // here and reused for every op template in this
1571        // activity.
1572        let wrapper_registry = crate::wrapper_registry::WrapperRegistry::from_inventory();
1573        // SRD-32a Push 3 — CLI `--wrap-default-order` replaces
1574        // the resolver's built-in tiebreaker. When unset, the
1575        // resolver builds with its DEFAULT_ORDER. The CLI list
1576        // is validated against the constraint graph at
1577        // construction; an inconsistent list aborts the run.
1578        let wrapper_resolver = match &activity.wrap_default_order {
1579            Some(order) => {
1580                let names: Vec<&str> = order.iter().map(|s| s.as_str()).collect();
1581                crate::wrapper_resolver::WrapperResolver::from_names(&names, &wrapper_registry)
1582            }
1583            None => crate::wrapper_resolver::WrapperResolver::with_default_order(&wrapper_registry),
1584        };
1585        let wrapper_resolver = match wrapper_resolver {
1586            Ok(r) => r,
1587            Err(e) => {
1588                crate::diag!(
1589                    crate::observer::LogLevel::Error,
1590                    "error: wrapper default-order is inconsistent with the \
1591                     registered wrapper graph: {e}. CLI `--wrap-default-order` \
1592                     and the built-in default both must satisfy every \
1593                     registered constraint."
1594                );
1595                return true;
1596            }
1597        };
1598
1599        let mut dispensers: Vec<Arc<dyn OpDispenser>> = Vec::new();
1600        let mut validation_metrics: Vec<Arc<validation::ValidationMetrics>> = Vec::new();
1601        // SRD-40b §6/§7 — one `Component` per **op dispenser**
1602        // (= per op template), not per op execution. Op
1603        // dispensers are the durable CNS layer of the nmbrs
1604        // runtime; per-cycle op invocations are stack-ephemeral
1605        // and inherit the dispenser's component implicitly via
1606        // the wrapper-stack closure capture. Each component
1607        // carries `op=<template.name>` labels (child of the
1608        // activity component) so SRD-40b §7.2's duplicate-
1609        // family check (`Component::register_instrument`)
1610        // sees one dimensional cell per dispenser, surviving
1611        // for the run's duration. Held here to keep the Arc
1612        // alive.
1613        let mut dispenser_components: Vec<
1614            std::sync::Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
1615        > = Vec::new();
1616        // Per-template wrapper pull plan. Wrapper-side reads
1617        // (validation, conditional, throttle) go through this
1618        // `PullPlan` against the firing fiber's state — see
1619        // SRD 31 §"Pull plan vs bind plan". Adapter-side reads
1620        // moved to the generic `crate::wires::WireSource` surface
1621        // at SRD-68 Push 5; the legacy `field_pulls` /
1622        // `bind_plans` / `batch_configs` lists are retired.
1623        let mut pull_plans_per_template: Vec<crate::fixture::PullPlan> = Vec::new();
1624        for template in templates {
1625            // Resolve adapter: per-template override or default
1626            let adapter_name = template
1627                .params
1628                .get("adapter")
1629                .and_then(|v| v.as_str())
1630                .unwrap_or(default_adapter);
1631            let adapter = match adapters.get(adapter_name) {
1632                Some(a) => a,
1633                None => {
1634                    let available = adapters.keys().cloned().collect::<Vec<_>>().join(", ");
1635                    crate::diag!(
1636                        crate::observer::LogLevel::Error,
1637                        "error: unknown adapter '{adapter_name}' for op '{}' (available: {available})",
1638                        template.name
1639                    );
1640                    return true; // signal stop — cannot proceed without the adapter
1641                }
1642            };
1643
1644            if template.params.contains_key("batch") {
1645                crate::diag!(
1646                    crate::observer::LogLevel::Debug,
1647                    "[activity] op '{}' has batch param: {:?}",
1648                    template.name,
1649                    template.params.get("batch")
1650                );
1651            }
1652            // SRD 30 §"Core-first field processing": if the adapter
1653            // declares its known op fields, every key in
1654            // `template.op` must be one of them. Core has already
1655            // stripped its own fields during parse (activity_params
1656            // in nmbrs-workload), so anything left is an adapter
1657            // concern. Unknown fields are a typo or a misplaced
1658            // core directive — fail loudly rather than silently
1659            // dropping the field.
1660            if let Some(known) = adapter.known_op_fields() {
1661                let unknown: Vec<&String> = template
1662                    .op
1663                    .keys()
1664                    .filter(|k| !known.contains(&k.as_str()))
1665                    .collect();
1666                if !unknown.is_empty() {
1667                    let list = unknown
1668                        .iter()
1669                        .map(|s| s.as_str())
1670                        .collect::<Vec<_>>()
1671                        .join(", ");
1672                    crate::diag!(
1673                        crate::observer::LogLevel::Error,
1674                        "error: adapter '{}' does not recognize op fields [{list}] on op '{}'; known fields: [{}]",
1675                        adapter.name(),
1676                        template.name,
1677                        known.join(", "),
1678                    );
1679                    return true; // stop — misconfiguration
1680                }
1681            }
1682
1683            // Same idea for `template.params`: validate against
1684            // a closed vocabulary so silent-ignore traps like
1685            // `evaluations: { relevancy: ... }` (wrapper keys
1686            // the runtime never reads) cannot hide a
1687            // misconfigured op. Allowed keys are the union of:
1688            //   1. core op-level params consumed by the runtime
1689            //      (validation, batching, polling, weighting,
1690            //      adapter selection) — `CORE_OP_PARAMS`.
1691            //   2. workload/CLI-level params that the parser
1692            //      blast-merges into every op's params at parse
1693            //      time — `runner::KNOWN_PARAMS`.
1694            //   3. user-declared workload params from the
1695            //      workload's top-level `params:` block (e.g.
1696            //      `table`, `keyspace`, `num_items`). The parser
1697            //      threads these into every op's params during
1698            //      doc → block → op merge, where they're meant
1699            //      for `{name}` interpolation in op templates.
1700            //      Visible here as `activity.workload_params`.
1701            //   4. adapter-specific params declared via
1702            //      `DriverAdapter::known_op_params()`.
1703            // Anything else is a typo / misplaced wrapper / dead
1704            // YAML and is rejected.
1705            {
1706                let allowed_extras = adapter.known_op_params();
1707                let workload_keys = &activity.workload_params;
1708                // A params key is legitimate if it is (1) a non-wrapper
1709                // core param, (2) a wrapper field declared via the
1710                // registry's `owned_fields` — the durable, type-safe
1711                // route that replaced the fragile "it's also a CLI
1712                // param" coincidence for fields like `errors`/`tries`,
1713                // (3) a CLI param blast-merged into every op's params at
1714                // parse time, (4) an adapter-declared extra, or (5) a
1715                // workload-level param.
1716                let unknown_params: Vec<&String> = template
1717                    .params
1718                    .keys()
1719                    .filter(|k| {
1720                        !crate::validation::CORE_OP_PARAMS.contains(&k.as_str())
1721                            && !wrapper_registry.owns_field(k)
1722                            && !crate::runner::is_cli_param(k)
1723                            && !allowed_extras.contains(&k.as_str())
1724                            && !workload_keys.contains_key(k.as_str())
1725                    })
1726                    .collect();
1727                if !unknown_params.is_empty() {
1728                    let list = unknown_params
1729                        .iter()
1730                        .map(|s| s.as_str())
1731                        .collect::<Vec<_>>()
1732                        .join(", ");
1733                    let wrapper_vocab = wrapper_registry
1734                        .all_owned_fields()
1735                        .into_iter()
1736                        .collect::<Vec<_>>()
1737                        .join(", ");
1738                    crate::diag!(
1739                        crate::observer::LogLevel::Error,
1740                        "error: op '{}' has unknown params keys [{list}] — \
1741                         not a core op param, not a wrapper field, not \
1742                         declared by adapter '{}', and not a workload-level \
1743                         param. Known core op params: [{}]. Wrapper fields: \
1744                         [{}]. Adapter extras: [{}]. Did you misspell a \
1745                         wrapper key (e.g. `verify:` / `poll:` / `readout:`) \
1746                         or nest something under a key the runtime doesn't \
1747                         read?",
1748                        template.name,
1749                        adapter.name(),
1750                        crate::validation::CORE_OP_PARAMS.join(", "),
1751                        wrapper_vocab,
1752                        allowed_extras.join(", "),
1753                    );
1754                    return true; // stop — misconfiguration
1755                }
1756            }
1757
1758            // SRD-32a Push 2 — field ownership and misplaced-
1759            // field guard. The wrapper registry knows which
1760            // `params:` keys each wrapper consumes
1761            // (`owned_fields`) and what makes the wrapper
1762            // trigger. A field that's owned by a wrapper that
1763            // ISN'T triggered is misplaced — silently ignoring
1764            // it would mask a typo or a half-applied
1765            // configuration. Example: `poll_interval_ms: 5000`
1766            // on an op without `poll:` is a misconfiguration —
1767            // the operator probably meant to enable polling
1768            // but forgot the trigger.
1769            //
1770            // The closed-vocabulary check above catches "I
1771            // don't recognise this key at all"; THIS check
1772            // catches "I recognise the key but it has no effect
1773            // here." Both surface as hard errors.
1774            //
1775            // Note: we cross-check against `template.params`
1776            // for keys. The registry's owned_fields includes
1777            // a few names that live elsewhere on `ParsedOp`
1778            // (`if` → `template.condition`, `delay` →
1779            // `template.delay`); those happen to BE their
1780            // wrapper's trigger field too, so when set the
1781            // outer `(reg.triggers)(template)` short-circuits
1782            // and we never reach the params-key check for
1783            // them. The set is small enough that we don't
1784            // need a separate "where does this field live"
1785            // helper.
1786            {
1787                let violations = wrapper_registry
1788                    .misplaced_fields(crate::wrapper_registry::WrapperSubject::Op(template));
1789                if !violations.is_empty() {
1790                    for (wrapper, field) in &violations {
1791                        crate::diag!(
1792                            crate::observer::LogLevel::Error,
1793                            "error: op '{}': field `{field}` is owned by wrapper \
1794                             `{wrapper}`, but the trigger condition for `{wrapper}` \
1795                             is not satisfied (no trigger field set on this op). \
1796                             Either remove `{field}` or add the wrapper's trigger \
1797                             field. SRD-32a §\"Field ownership and parse-time \
1798                             validation\".",
1799                            template.name
1800                        );
1801                    }
1802                    return true; // stop — misconfiguration
1803                }
1804            }
1805
1806            // Per-op dispenser-init contract: `map_op` owns the
1807            // typed-binder verification for ITS op as part of
1808            // completing the currying stack — it constructs any
1809            // binders from the adapter's protocol-side metadata,
1810            // verifies them against `parent` via
1811            // `polydat::binder::verify_against_kernel`, and
1812            // surfaces any violation as `Err`. No
1813            // outside-the-dispenser-init phase for binders; the
1814            // map_op return signals the result.
1815            match adapter
1816                .map_op(template, op_builder.canonical_kernel_for_op(&template.name))
1817                .await
1818            {
1819                Ok(d) => {
1820                    let raw: Arc<dyn OpDispenser> = Arc::from(d);
1821
1822                    // Open the per-template scope fixture (SRD 32
1823                    // §"Init-Time Fixture and Consumer Self-
1824                    // Registration"). Each wrapper below registers
1825                    // its own Polydat name dependencies; the fixture is
1826                    // sealed after the wrapper chain is complete and
1827                    // the resulting PullPlan drives cycle-time reads.
1828                    //
1829                    // SRD-13d Phase 9 — when this op-template
1830                    // materialised its own kernel, the fixture
1831                    // builds its plan against THAT program so
1832                    // pulls resolve in the op-template scope.
1833                    // Flattened op-templates fall back to the
1834                    // activity-wide program (same scope as before
1835                    // Phase 9 landed).
1836                    let template_program = op_builder.program_for_op(&template.name);
1837                    let mut fx = crate::fixture::ScopeFixture::new(template_program.clone());
1838
1839                    // SRD-32a — resolve which wrappers fire and
1840                    // in what order. The plan is innermost-first;
1841                    // `traverse` is always inner. The cascade
1842                    // below dispatches to the existing per-
1843                    // wrapper `wrap()` factory based on the plan
1844                    // entries' names. Plan order matches the
1845                    // built-in default order, which mirrors the
1846                    // pre-SRD-32a hand-rolled cascade — existing
1847                    // tests exercise the same composition.
1848                    //
1849                    // SRD-32a Push 3 — override precedence:
1850                    //   1. Per-op `template.wrappers.order` shadows everything else.
1851                    //   2. Else workload-root `activity.wrappers_override`.
1852                    //   3. Else the resolver's default-order tiebreaker.
1853                    // Per-op shadows root entirely (no merge).
1854                    let per_op_override = template
1855                        .wrappers
1856                        .as_ref()
1857                        .filter(|c| !c.order.is_empty())
1858                        .map(|c| c.order.clone());
1859                    let effective_override =
1860                        per_op_override.or_else(|| activity.wrappers_override.clone());
1861                    let plan = match effective_override {
1862                        Some(order) => {
1863                            let order_strs: Vec<&str> = order.iter().map(|s| s.as_str()).collect();
1864                            wrapper_resolver.resolve_with_order(
1865                                crate::wrapper_registry::WrapperSubject::Op(template),
1866                                &wrapper_registry,
1867                                &order_strs,
1868                            )
1869                        }
1870                        None => wrapper_resolver.resolve(
1871                            crate::wrapper_registry::WrapperSubject::Op(template),
1872                            &wrapper_registry,
1873                        ),
1874                    };
1875                    let plan = match plan {
1876                        Ok(p) => p,
1877                        Err(e) => {
1878                            crate::diag!(
1879                                crate::observer::LogLevel::Error,
1880                                "error: op '{}': wrapper resolution failed: {e}",
1881                                template.name
1882                            );
1883                            return true;
1884                        }
1885                    };
1886
1887                    // SRD-32a §"Composition telemetry" — emit one
1888                    // Info-level line per assigned wrapper so
1889                    // operators can see, at session start, exactly
1890                    // which wrappers shape each op and how. Trivial
1891                    // wrappers (e.g. always-on `traverse`) return
1892                    // `None` from `describe_assignment` and are
1893                    // dropped from this list.
1894                    let assignments: Vec<(crate::wrapper_registry::WrapperName, String)> = plan
1895                        .iter_innermost_first()
1896                        .filter_map(|reg| {
1897                            (reg.describe_assignment)(crate::wrapper_registry::WrapperSubject::Op(
1898                                template,
1899                            ))
1900                            .map(|s| (reg.name, s))
1901                        })
1902                        .collect();
1903                    if !assignments.is_empty() {
1904                        // Per-op wrapper assignments are a diagnostic
1905                        // useful when chasing a wrapper-composition
1906                        // bug, not part of normal operator output.
1907                        // `nmbrs describe` renders the same stack on
1908                        // demand (see crates/nmbrs/src/describe.rs); session.log
1909                        // still captures this for postmortem.
1910                        crate::diag!(
1911                            crate::observer::LogLevel::Debug,
1912                            "op '{}' wrappers (innermost → outermost):",
1913                            template.name
1914                        );
1915                        for (i, (_, line)) in assignments.iter().enumerate() {
1916                            crate::diag!(crate::observer::LogLevel::Debug, "  {}. {}", i + 1, line);
1917                        }
1918                    }
1919
1920                    // SRD-82 Part 3b — resolve THIS op's error policy BEFORE
1921                    // the retry activation check, so the policy's `retry` verb
1922                    // can inject a retry budget (the errors→retry bridge). An
1923                    // op-template `errors:` derives a child of the phase
1924                    // policy (value-equality shared across ops declaring the
1925                    // same spec); no override inherits the phase policy by
1926                    // reference. The policy drives the OUTERMOST error-handler
1927                    // wrapper placed after the plan cascade below.
1928                    let op_error_policy =
1929                        match template.params.get("errors").and_then(|v| v.as_str()) {
1930                            Some(spec) => activity.error_policy.resolve_child(Some(
1931                                crate::error_policy::PolicyConfig::new(
1932                                    spec,
1933                                    activity.config.error_rate_max,
1934                                ),
1935                            )),
1936                            None => activity.error_policy.clone(),
1937                        };
1938
1939                    // Tries wrapper — CONDITIONAL innermost wrapper (SRD-82
1940                    // Part 3b): `tries:` is its sigil, the TOTAL attempts the
1941                    // op may make. A budget resolves from, in order: the op's
1942                    // own `tries:` field; the inherited phase/root `tries`
1943                    // (config — the phase FIELD must beat a scope wire, since
1944                    // a workload-root `tries` param also lands in GK scope as
1945                    // a constant and would otherwise shadow an explicit
1946                    // phase-level `tries: 1` pin); a `tries` wire defined in
1947                    // the op's scope (bindings); or a `retry`/`retry(N)` verb
1948                    // in the op's error policy (the injection bridge — N
1949                    // additional attempts → N+1 total; `errors:` and `tries:`
1950                    // stay orthogonal surfaces). No budget anywhere OR
1951                    // `tries: 1` → NO wrapper → single attempt (the
1952                    // error-handler wrapper records the tallies). `tries: 0`
1953                    // constructs the wrapper in its fail-without-executing
1954                    // mode. When constructed it owns the attempt loop, the
1955                    // `attempt_*` counters, and the per-attempt panic catch.
1956                    // Op `tries:` accepts the sugared number/string AND the
1957                    // map form `{count: N, backoff: {...}}` — read `count`
1958                    // from the map. Falls back to the phase/root `tries`, an
1959                    // in-scope `tries` wire, then an `errors:` retry-verb
1960                    // budget.
1961                    let op_tries: Option<u32> = template
1962                        .params
1963                        .get("tries")
1964                        .and_then(|v| match v {
1965                            serde_json::Value::Number(n) => n.as_u64().map(|n| n as u32),
1966                            serde_json::Value::String(s) => s.trim().parse::<u32>().ok(),
1967                            serde_json::Value::Object(m) => {
1968                                m.get("count").and_then(|c| c.as_u64()).map(|n| n as u32)
1969                            }
1970                            _ => None,
1971                        })
1972                        .or(activity.config.tries)
1973                        .or_else(|| {
1974                            raw.canonical_kernel()
1975                                .and_then(|k| {
1976                                    use polydat::kernel::interp::Lookup as _;
1977                                    polydat::kernel::interp::KernelLookup::new(k.as_ref())
1978                                        .lookup("tries")
1979                                })
1980                                .and_then(|v| match v {
1981                                    polydat::ast::Value::U64(n) => Some(n as u32),
1982                                    _ => None,
1983                                })
1984                        })
1985                        .or_else(|| {
1986                            op_error_policy
1987                                .router
1988                                .retry_verb_budget()
1989                                .map(|additional| additional.saturating_add(1))
1990                        });
1991                    let has_tries_wrapper = matches!(op_tries, Some(n) if n != 1);
1992                    // Retry pacing (compaction-demo diagnosis: an immediate
1993                    // `continue` retry loop hammers a dying server). Resolve
1994                    // (min, max, ratio) by precedence, highest first:
1995                    //   1. op `tries:` map `backoff: {ratio, min, max}`
1996                    //   2. op standalone `retry_backoff*` params (back-compat)
1997                    //   3. phase `tries:` map backoff (activity config)
1998                    //   4. built-in defaults: 100ms base, 10s cap, 2.0 ratio.
1999                    // `retry_backoff: 0` (base == 0) disables pacing.
2000                    let json_to_ms = |v: &serde_json::Value| -> Option<u64> {
2001                        match v {
2002                            serde_json::Value::Number(n) => n.as_u64().map(|n| n.to_string()),
2003                            serde_json::Value::String(s) => Some(s.clone()),
2004                            _ => None,
2005                        }
2006                        .and_then(|s| crate::timeval::parse_time_ms(&s).ok())
2007                    };
2008                    let mut backoff_base_ms: u64 = 100;
2009                    let mut backoff_max_ms: u64 = 10_000;
2010                    let mut backoff_ratio: f64 = 2.0;
2011                    // (3) phase-level map backoff
2012                    if let Some(bo) = activity.config.tries_backoff.as_ref() {
2013                        if let Some(r) = bo.ratio {
2014                            backoff_ratio = r;
2015                        }
2016                        if let Some(m) = bo
2017                            .min
2018                            .as_deref()
2019                            .and_then(|s| crate::timeval::parse_time_ms(s).ok())
2020                        {
2021                            backoff_base_ms = m;
2022                        }
2023                        if let Some(m) = bo
2024                            .max
2025                            .as_deref()
2026                            .and_then(|s| crate::timeval::parse_time_ms(s).ok())
2027                        {
2028                            backoff_max_ms = m;
2029                        }
2030                    }
2031                    // (1)/(2) op-level: the `tries:` map backoff wins; absent
2032                    // that, the standalone `retry_backoff*` params.
2033                    let op_map_backoff = template
2034                        .params
2035                        .get("tries")
2036                        .and_then(|v| v.as_object())
2037                        .and_then(|m| m.get("backoff"))
2038                        .and_then(|v| v.as_object());
2039                    if let Some(bo) = op_map_backoff {
2040                        if let Some(r) = bo.get("ratio").and_then(|v| v.as_f64()) {
2041                            backoff_ratio = r;
2042                        }
2043                        if let Some(m) = bo.get("min").and_then(&json_to_ms) {
2044                            backoff_base_ms = m;
2045                        }
2046                        if let Some(m) = bo.get("max").and_then(&json_to_ms) {
2047                            backoff_max_ms = m;
2048                        }
2049                    } else {
2050                        if let Some(m) = template.params.get("retry_backoff").and_then(&json_to_ms)
2051                        {
2052                            backoff_base_ms = m;
2053                        }
2054                        if let Some(m) = template
2055                            .params
2056                            .get("retry_backoff_max")
2057                            .and_then(&json_to_ms)
2058                        {
2059                            backoff_max_ms = m;
2060                        }
2061                        if let Some(r) = template
2062                            .params
2063                            .get("retry_backoff_ratio")
2064                            .and_then(|v| v.as_f64())
2065                        {
2066                            backoff_ratio = r;
2067                        }
2068                    }
2069                    // Retry-error counter-exemplars (`exec_events`): the
2070                    // fraction of caught-and-retried errors sampled onto
2071                    // the structured event sink (default 0.0 = off), and
2072                    // the emission-frequency ceiling that squelches spam.
2073                    // Standalone params, same channel as `retry_backoff*`.
2074                    let json_to_f64 = |v: &serde_json::Value| -> Option<f64> {
2075                        match v {
2076                            serde_json::Value::Number(n) => n.as_f64(),
2077                            serde_json::Value::String(s) => s.trim().parse::<f64>().ok(),
2078                            _ => None,
2079                        }
2080                    };
2081                    let pinned = template.params.contains_key("retry_exemplar_rate")
2082                        || template.params.contains_key("retry_exemplar_max_hz");
2083                    let sampler = if pinned {
2084                        // Authored pin: a private cell the dynamic
2085                        // controls deliberately do not move.
2086                        let exemplar_rate = template
2087                            .params
2088                            .get("retry_exemplar_rate")
2089                            .and_then(&json_to_f64)
2090                            .unwrap_or(0.0);
2091                        let exemplar_max_hz = template
2092                            .params
2093                            .get("retry_exemplar_max_hz")
2094                            .and_then(&json_to_f64)
2095                            .unwrap_or(5.0);
2096                        crate::exec_events::ExemplarSampler::pinned(exemplar_rate, exemplar_max_hz)
2097                    } else {
2098                        // Default: the activity's shared cell — the
2099                        // `retry_exemplar_rate`/`_max_hz` dynamic
2100                        // controls move every sampler built here with
2101                        // one atomic store.
2102                        crate::exec_events::ExemplarSampler::shared(
2103                            activity.exemplar_config.clone(),
2104                        )
2105                    };
2106                    // Default-on advisory; `retry_advisory: false` opts
2107                    // this op out of the shared gate. The value's form is
2108                    // checked at load (construction `OP_ACTIVITY_ELEMENTS`),
2109                    // so only a boolean reaches here.
2110                    let advisory_on = template
2111                        .params
2112                        .get("retry_advisory")
2113                        .map(|v| {
2114                            nmbrs_workload::boolean::json_bool("retry_advisory", v) != Ok(false)
2115                        })
2116                        .unwrap_or(true);
2117                    let advisory = advisory_on.then(|| activity.advisory_gate.clone());
2118                    let raw = match op_tries {
2119                        Some(n) if n != 1 => crate::wrappers::TriesDispenser::wrap(
2120                            raw,
2121                            n,
2122                            activity.metrics.clone(),
2123                            backoff_base_ms,
2124                            backoff_max_ms,
2125                            backoff_ratio,
2126                            activity.stop_view(),
2127                            template.name.clone(),
2128                            sampler,
2129                            advisory,
2130                        ),
2131                        _ => raw,
2132                    };
2133
2134                    // Wrap with traversal. Traversal does not read Polydat
2135                    // values; no fixture registration needed. Always present per
2136                    // the registry's always-true trigger.
2137                    let mut current: Arc<dyn OpDispenser> =
2138                        crate::wrappers::TraversingDispenser::wrap(
2139                            raw,
2140                            template,
2141                            traversal_stats.clone(),
2142                        );
2143                    // Late-bound handoff from the metrics arm (outside poll in
2144                    // the cascade, so it runs AFTER the poll arm below) to the
2145                    // poll dispenser: the op's compiled gauge slots, re-published
2146                    // per poll iteration so drains feed the store live.
2147                    let poll_iteration_gauges: Arc<
2148                        arc_swap::ArcSwapOption<Vec<crate::wrappers::metrics::MetricSlot>>,
2149                    > = Arc::new(arc_swap::ArcSwapOption::empty());
2150
2151                    // SRD-40b §6/§7 — one `Component` per dispenser
2152                    // carrying `op=<template.name>`, a child of the
2153                    // activity's, so the duplicate-family check sees one
2154                    // dimensional cell per dispenser. Made for an op that
2155                    // declares metrics or places its own measurements
2156                    // (`cell:`), and before the wrappers, because two of
2157                    // them record into the op's cells: validation, inside,
2158                    // and metrics, outside.
2159                    let op_component = (!template.metrics.is_empty() || !template.cell.is_empty())
2160                        .then(|| {
2161                            let labels = nmbrs_metrics::labels::Labels::of("op", &template.name);
2162                            let component = std::sync::Arc::new(std::sync::RwLock::new(
2163                                nmbrs_metrics::component::Component::new(
2164                                    labels,
2165                                    std::collections::HashMap::new(),
2166                                ),
2167                            ));
2168                            if let Some(parent) = activity.component.as_ref() {
2169                                nmbrs_metrics::component::attach(parent, &component);
2170                            }
2171                            component
2172                        });
2173                    let op_cells = match &op_component {
2174                        Some(component) => {
2175                            match crate::op_cells::OpCells::for_op(template, component, &mut fx) {
2176                                Ok(cells) => cells,
2177                                Err(e) => {
2178                                    crate::diag!(
2179                                        crate::observer::LogLevel::Error,
2180                                        "error: op '{}': {e}",
2181                                        template.name
2182                                    );
2183                                    return true;
2184                                }
2185                            }
2186                        }
2187                        None => None,
2188                    };
2189
2190                    // Apply each remaining wrapper in plan order.
2191                    // Skip `traverse`; it's already constructed.
2192                    for reg in plan.iter_innermost_first() {
2193                        if reg.name == crate::wrappers::traverse::NAME {
2194                            continue;
2195                        }
2196                        let stop = match reg.name {
2197                            crate::wrappers::delay::NAME => {
2198                                let spec = template
2199                                    .delay
2200                                    .as_ref()
2201                                    .expect("delay triggered → delay set");
2202                                let trim = |s: &str| -> String {
2203                                    let t = s.trim();
2204                                    t.strip_prefix('{')
2205                                        .and_then(|s| s.strip_suffix('}'))
2206                                        .unwrap_or(t)
2207                                        .to_string()
2208                                };
2209                                let wrap_result = match spec {
2210                                    nmbrs_workload::model::DelaySpec::Before(name) => {
2211                                        let name = trim(name);
2212                                        crate::wrappers::DelayDispenser::wrap(
2213                                            current.clone(),
2214                                            &name,
2215                                            &mut fx,
2216                                        )
2217                                    }
2218                                    nmbrs_workload::model::DelaySpec::BeforeAfter {
2219                                        before,
2220                                        after,
2221                                    } => {
2222                                        let before = before.as_deref().map(trim);
2223                                        let after = after.as_deref().map(trim);
2224                                        crate::wrappers::DelayDispenser::wrap_before_after(
2225                                            current.clone(),
2226                                            before.as_deref(),
2227                                            after.as_deref(),
2228                                            &mut fx,
2229                                        )
2230                                    }
2231                                };
2232                                match wrap_result {
2233                                    Ok(d) => {
2234                                        current = d;
2235                                        false
2236                                    }
2237                                    Err(e) => {
2238                                        crate::diag!(
2239                                            crate::observer::LogLevel::Error,
2240                                            "error: op '{}': {e}",
2241                                            template.name
2242                                        );
2243                                        true
2244                                    }
2245                                }
2246                            }
2247                            crate::validation::WRAPPER_NAME => {
2248                                match crate::validation::ValidatingDispenser::wrap_in_cells(
2249                                    current.clone(),
2250                                    template,
2251                                    &activity.labels,
2252                                    Some(&program),
2253                                    &mut fx,
2254                                    op_cells.clone(),
2255                                ) {
2256                                    Ok((d, vm)) => {
2257                                        if let Some(vm) = vm {
2258                                            validation_metrics.push(vm);
2259                                        }
2260                                        current = d;
2261                                        false
2262                                    }
2263                                    Err(e) => {
2264                                        crate::diag!(
2265                                            crate::observer::LogLevel::Error,
2266                                            "error: op '{}': {e}",
2267                                            template.name
2268                                        );
2269                                        true
2270                                    }
2271                                }
2272                            }
2273                            crate::wrappers::poll::NAME => {
2274                                // Poll config reader: `poll:` is either
2275                                // a string (mode only, all-defaults) or
2276                                // a map (`{mode, until, interval_ms,
2277                                // timeout_ms, metric_name,
2278                                // max_error_retries}`). All
2279                                // poll knobs live UNDER `poll:` — no
2280                                // flat `poll_*` prefix keys at op
2281                                // level, so the wrapper's namespace
2282                                // doesn't collide with adapter fields
2283                                // (e.g. HTTP's `request_timeout_ms`).
2284                                let poll_val = template.params.get("poll");
2285                                let cfg = poll_val.and_then(|v| v.as_object());
2286                                let get_u64 = |k: &str, default: u64| -> u64 {
2287                                    cfg.and_then(|m| m.get(k))
2288                                        .and_then(|v| {
2289                                            v.as_u64().or_else(|| {
2290                                                v.as_str().and_then(|s| s.parse::<u64>().ok())
2291                                            })
2292                                        })
2293                                        .unwrap_or(default)
2294                                };
2295                                let get_u32 = |k: &str, default: u32| -> u32 {
2296                                    cfg.and_then(|m| m.get(k))
2297                                        .and_then(|v| {
2298                                            v.as_u64().map(|n| n as u32).or_else(|| {
2299                                                v.as_str().and_then(|s| s.parse::<u32>().ok())
2300                                            })
2301                                        })
2302                                        .unwrap_or(default)
2303                                };
2304                                let get_str = |k: &str| -> Option<String> {
2305                                    cfg.and_then(|m| m.get(k))
2306                                        .and_then(|v| v.as_str())
2307                                        .map(|s| s.to_string())
2308                                };
2309                                let interval = get_u64("interval_ms", 1000);
2310                                let timeout = get_u64("timeout_ms", 300_000);
2311                                // SRD-03 §"Status-Determination
2312                                // Invariant — Retries Within": bounded
2313                                // retry budget for retryable inner
2314                                // errors. Default 0 (strict). Operators
2315                                // raise this when long fixture readiness
2316                                // checks tolerate transient blips.
2317                                let max_error_retries = get_u32("max_error_retries", 0);
2318                                let metric_name = get_str("metric_name");
2319                                // `memo` / `progress` — live-status templates
2320                                // re-rendered per poll iteration against the
2321                                // wires: `memo` publishes the measured values
2322                                // to the activity memo (default: append
2323                                // `measured N row(s)…` to the base memo);
2324                                // `progress` parses to an f64 fraction that
2325                                // drives the phase completion bar via the
2326                                // derived-progress override.
2327                                let each_memo = get_str("memo");
2328                                let progress_template = get_str("progress");
2329                                // The op's `gutter:` DURING form rides into the poll
2330                                // loop for per-iteration refresh — the GutterDispenser
2331                                // itself publishes only once, when the (potentially
2332                                // hours-long) drain op completes.
2333                                // `on_done` — values written to the wires on the
2334                                // TERMINATING poll, before its metrics publish.
2335                                // A remote view of in-flight work (a compactions
2336                                // view, a job queue) shows what is RUNNING, so
2337                                // "done" arrives as an empty result and the
2338                                // finished item's attributes are already gone.
2339                                // This proxies the completed measurement we could
2340                                // not observe: `on_done: {completion_ratio: 1.0}`
2341                                // makes the final sample say what the view no
2342                                // longer can.
2343                                let on_done = crate::wrappers::poll::parse_on_done(cfg);
2344                                // `until:` — a polydat predicate replacing the
2345                                // empty-result check. Scope synthesis lowered the
2346                                // expression into this node's kernel; the
2347                                // wrapper only needs to know that it exists.
2348                                let until = cfg
2349                                    .and_then(|m| m.get("until"))
2350                                    .and_then(|v| v.as_str())
2351                                    .is_some_and(|s| !s.trim().is_empty());
2352                                let each_gutter = crate::wrappers::gutter::parse_templates(
2353                                    template.params.get("gutter"),
2354                                )
2355                                .during;
2356                                let (d, _pm) = crate::wrappers::PollingDispenser::wrap_with_status(
2357                                    current.clone(),
2358                                    interval,
2359                                    timeout,
2360                                    max_error_retries,
2361                                    metric_name,
2362                                    each_memo,
2363                                    Some(activity.memo.clone()),
2364                                    progress_template,
2365                                    Some(activity.metrics.clone()),
2366                                    each_gutter,
2367                                    Some(activity.gutter.clone()),
2368                                    Some(poll_iteration_gauges.clone()),
2369                                    on_done.clone(),
2370                                    until,
2371                                    activity.stop_view(),
2372                                );
2373                                crate::diag!(
2374                                    crate::observer::LogLevel::Debug,
2375                                    "  op '{}': polling enabled (interval={}ms, timeout={}ms, max_error_retries={}, done_on={}, on_done={:?})",
2376                                    template.name,
2377                                    interval,
2378                                    timeout,
2379                                    max_error_retries,
2380                                    if until {
2381                                        "until-predicate".to_string()
2382                                    } else {
2383                                        "empty-result".to_string()
2384                                    },
2385                                    on_done
2386                                        .iter()
2387                                        .map(|(k, v)| format!("{k}={v}"))
2388                                        .collect::<Vec<_>>()
2389                                );
2390                                current = d;
2391                                false
2392                            }
2393                            crate::wrappers::r#if::NAME => {
2394                                // `if:` short-circuits before the
2395                                // inner cascade — load-bearing for
2396                                // the recent fix that pulls polling
2397                                // inside `if`. Resolver order
2398                                // mirrors that.
2399                                let cond = template
2400                                    .condition
2401                                    .as_deref()
2402                                    .expect("if triggered → condition set");
2403                                let cond_name = cond
2404                                    .trim()
2405                                    .strip_prefix('{')
2406                                    .and_then(|s| s.strip_suffix('}'))
2407                                    .unwrap_or(cond.trim());
2408                                match crate::wrappers::ConditionalDispenser::wrap(
2409                                    current.clone(),
2410                                    cond_name,
2411                                    activity.metrics.clone(),
2412                                    &mut fx,
2413                                ) {
2414                                    Ok(d) => {
2415                                        current = d;
2416                                        false
2417                                    }
2418                                    Err(e) => {
2419                                        crate::diag!(
2420                                            crate::observer::LogLevel::Error,
2421                                            "error: op '{}': {e}",
2422                                            template.name
2423                                        );
2424                                        true
2425                                    }
2426                                }
2427                            }
2428                            crate::wrappers::r#while::NAME => {
2429                                // `while:` loops the inner until the
2430                                // synthesised `__while` predicate
2431                                // flips falsy or the activity stops.
2432                                // The op-kernel synthesiser appended
2433                                // `__while := <expr>` to the kernel's
2434                                // result bindings — that's how the
2435                                // expression's free identifiers got
2436                                // their extern slots.
2437                                match crate::wrappers::WhileWrapper::wrap(
2438                                    current.clone(),
2439                                    activity.stop_view(),
2440                                    &mut fx,
2441                                ) {
2442                                    Ok(d) => {
2443                                        current = d;
2444                                        false
2445                                    }
2446                                    Err(e) => {
2447                                        crate::diag!(
2448                                            crate::observer::LogLevel::Error,
2449                                            "error: op '{}': {e}",
2450                                            template.name
2451                                        );
2452                                        true
2453                                    }
2454                                }
2455                            }
2456                            crate::wrappers::rate::NAME => {
2457                                // Per-op rate limiter, independent
2458                                // of the activity-level rate AND of
2459                                // every other op's per-op limiter.
2460                                // Each instance owns its own
2461                                // RateLimiter.
2462                                let rate_spec =
2463                                    template.rate.as_deref().expect("rate triggered → rate set");
2464                                match crate::wrappers::OpRateWrapper::wrap(
2465                                    current.clone(),
2466                                    rate_spec,
2467                                ) {
2468                                    Ok(d) => {
2469                                        current = d;
2470                                        false
2471                                    }
2472                                    Err(e) => {
2473                                        crate::diag!(
2474                                            crate::observer::LogLevel::Error,
2475                                            "error: op '{}': {e}",
2476                                            template.name
2477                                        );
2478                                        true
2479                                    }
2480                                }
2481                            }
2482                            crate::wrappers::fields::NAME
2483                                if let Err(e) = crate::wrappers::fields::check_fields_value(
2484                                    &template.params,
2485                                ) =>
2486                            {
2487                                crate::diag!(
2488                                    crate::observer::LogLevel::Error,
2489                                    "error: op '{}': {e}",
2490                                    template.name
2491                                );
2492                                true
2493                            }
2494                            crate::wrappers::fields::NAME => {
2495                                // Capture op_fields so the fields
2496                                // wrapper can render the rendered op
2497                                // text at cycle time. Stable
2498                                // insertion order isn't guaranteed by
2499                                // HashMap, but ParsedOp.op is small
2500                                // enough that a deterministic
2501                                // alphabetical sort keeps the printed
2502                                // output stable across runs.
2503                                let mut op_fields: Vec<(String, serde_json::Value)> = template
2504                                    .op
2505                                    .iter()
2506                                    .map(|(k, v)| (k.clone(), v.clone()))
2507                                    .collect();
2508                                op_fields.sort_by(|a, b| a.0.cmp(&b.0));
2509                                current = crate::wrappers::FieldsDispenser::wrap_with_op_fields(
2510                                    current.clone(),
2511                                    &template.name,
2512                                    op_fields,
2513                                );
2514                                false
2515                            }
2516                            crate::wrappers::result::NAME => {
2517                                // SRD-40b §5: result-as-GK adapter —
2518                                // exposes captured result fields to
2519                                // the op's Polydat scope via
2520                                // `OpResult.captures` so metric
2521                                // expressions (and any later wrappers)
2522                                // can reference them by name. No-op
2523                                // when the op declares no `result:`
2524                                // wires.
2525                                current = crate::wrappers::ResultDispenser::wrap(
2526                                    current.clone(),
2527                                    template.result.as_ref(),
2528                                    template.abstract_interface.as_ref().map(|i| &i.results),
2529                                );
2530                                false
2531                            }
2532                            crate::wrappers::metrics::NAME => {
2533                                // The op's component, made above: the
2534                                // wrapper's trigger is the condition
2535                                // it was made under.
2536                                let dispenser_component = op_component.clone().expect(
2537                                    "the metrics wrapper triggers only for an op that \
2538                                     declares metrics or a cell, which has a component",
2539                                );
2540                                let wrap_result = {
2541                                    let mut guard = dispenser_component
2542                                        .write()
2543                                        .unwrap_or_else(|e| e.into_inner());
2544                                    crate::wrappers::MetricsDispenser::wrap_with_slots(
2545                                        current.clone(),
2546                                        &template.metrics,
2547                                        &mut guard,
2548                                        &dispenser_component,
2549                                        op_cells.clone(),
2550                                        &mut fx,
2551                                    )
2552                                };
2553                                match wrap_result {
2554                                    Ok(crate::wrappers::metrics::MetricsWrap {
2555                                        dispenser: d,
2556                                        slots,
2557                                    }) => {
2558                                        if let Some(slots) = slots {
2559                                            poll_iteration_gauges.store(Some(slots));
2560                                        }
2561                                        // Mark the dispenser
2562                                        // component Running so the
2563                                        // cadence reporter's
2564                                        // `capture_tree` walk visits
2565                                        // it on every tick.
2566                                        dispenser_component
2567                                            .write()
2568                                            .unwrap_or_else(|e| e.into_inner())
2569                                            .set_state(
2570                                                nmbrs_metrics::component::ComponentState::Running,
2571                                            );
2572                                        dispenser_components.push(dispenser_component);
2573                                        current = d;
2574                                        false
2575                                    }
2576                                    Err(e) => {
2577                                        crate::diag!(
2578                                            crate::observer::LogLevel::Error,
2579                                            "error: op '{}': {e}",
2580                                            template.name
2581                                        );
2582                                        true
2583                                    }
2584                                }
2585                            }
2586                            crate::wrappers::dryrun::NAME => {
2587                                // Outermost short-circuit. Activated
2588                                // by the injected `dryrun:` template
2589                                // parameter (per
2590                                // `run_with_adapters`'s session-
2591                                // startup injection step). The
2592                                // trigger fires only when the
2593                                // template carries the marker, so
2594                                // we know we're in dryrun mode just
2595                                // by being here.
2596                                //
2597                                // Architectural invariant: by sitting
2598                                // outermost in the cascade, the
2599                                // short-circuit returns BEFORE any
2600                                // inner wrapper (verify / metrics /
2601                                // poll / etc.) can observe the
2602                                // empty body the dryrun stand-in
2603                                // produces. The `forbids_outer` set
2604                                // on the DRYRUN registration pins
2605                                // this position structurally.
2606                                // DryRunWrapper has one job: short-circuit
2607                                // the outbound op. No display modes, no
2608                                // op-field snapshot, no extra work — the
2609                                // wrapper is supposed to do NOTHING MORE
2610                                // than wrap the op and not call it.
2611                                current = crate::wrappers::DryRunWrapper::wrap(current.clone());
2612                                false
2613                            }
2614                            crate::wrappers::memo::NAME => {
2615                                // Memo wrapper: parse `memo:` (string
2616                                // shorthand or `{before, after}` map),
2617                                // wrap with cloned ArcSwap handle.
2618                                let (before, after) = match template.params.get("memo") {
2619                                    Some(serde_json::Value::String(s)) => {
2620                                        // Shorthand: same template for
2621                                        // before AND after.
2622                                        (Some(s.clone()), Some(s.clone()))
2623                                    }
2624                                    Some(serde_json::Value::Object(obj)) => {
2625                                        let b = obj
2626                                            .get("before")
2627                                            .and_then(|v| v.as_str())
2628                                            .map(String::from);
2629                                        let a = obj
2630                                            .get("after")
2631                                            .and_then(|v| v.as_str())
2632                                            .map(String::from);
2633                                        (b, a)
2634                                    }
2635                                    _ => (None, None),
2636                                };
2637                                if before.is_none() && after.is_none() {
2638                                    crate::diag!(
2639                                        crate::observer::LogLevel::Warn,
2640                                        "op '{}': memo: requires at least one of \
2641                                         `before` / `after` (or a string shorthand)",
2642                                        template.name
2643                                    );
2644                                    false
2645                                } else {
2646                                    current = crate::wrappers::MemoDispenser::wrap(
2647                                        current.clone(),
2648                                        before,
2649                                        after,
2650                                        activity.memo.clone(),
2651                                    );
2652                                    false
2653                                }
2654                            }
2655                            crate::wrappers::gutter::NAME => {
2656                                // Gutter wrapper: parse `gutter:` (layout-
2657                                // string shorthand or `{bar}` / `{spark}`
2658                                // map), wrap with the activity's shared
2659                                // gutter slot.
2660                                let gutter = crate::wrappers::gutter::parse_templates(
2661                                    template.params.get("gutter"),
2662                                );
2663                                if gutter.during.is_none() && gutter.finish.is_none() {
2664                                    crate::diag!(
2665                                        crate::observer::LogLevel::Warn,
2666                                        "op '{}': gutter: requires a layout string, one of \
2667                                         `bar:` / `spark:` / `text:`, or a `final:` form",
2668                                        template.name
2669                                    );
2670                                    false
2671                                } else {
2672                                    if let Some(during) = gutter.during {
2673                                        *activity.gutter_template.lock().unwrap() =
2674                                            Some(during.clone());
2675                                        current = crate::wrappers::GutterDispenser::wrap(
2676                                            current.clone(),
2677                                            during,
2678                                            activity.gutter.clone(),
2679                                        );
2680                                    }
2681                                    if let Some(finish) = gutter.finish {
2682                                        *activity.gutter_final_template.lock().unwrap() =
2683                                            Some(finish);
2684                                    }
2685                                    false
2686                                }
2687                            }
2688                            crate::wrappers::readout::NAME => {
2689                                // Readout wrapper: op-level status leaf. Wrap the
2690                                // inner op with a lifecycle reporter keyed by the
2691                                // op-template name; the parent phase is resolved at
2692                                // run time from the task-local CURRENT_PHASE. Only
2693                                // `readout: visible` triggers it (see the wrapper's
2694                                // `triggers`), so this arm always wraps when reached.
2695                                current = crate::wrappers::ReadoutDispenser::wrap_with_measure(
2696                                    current.clone(),
2697                                    template.name.clone(),
2698                                    template
2699                                        .params
2700                                        .get("measure")
2701                                        .and_then(|v| v.as_str())
2702                                        .map(|s| s.to_string()),
2703                                );
2704                                crate::diag!(
2705                                    crate::observer::LogLevel::Debug,
2706                                    "  op '{}': readout visible (op-level status line)",
2707                                    template.name
2708                                );
2709                                false
2710                            }
2711                            crate::wrappers::errors::NAME => {
2712                                // SRD-82 Part 3b — hand-placed OUTERMOST after
2713                                // this loop (mirrors the hand-placed innermost
2714                                // tries). The plan entry records presence for
2715                                // telemetry / describe only.
2716                                false
2717                            }
2718                            crate::wrappers::tries::NAME => {
2719                                // SRD-82 Part 3b — hand-placed INNERMOST before
2720                                // this loop (the sigil resolution above). The
2721                                // plan entry records presence for telemetry /
2722                                // describe only.
2723                                false
2724                            }
2725                            other => {
2726                                crate::diag!(
2727                                    crate::observer::LogLevel::Error,
2728                                    "error: op '{}': resolver returned wrapper `{}` \
2729                                     with no dispatch handler in the cascade",
2730                                    template.name,
2731                                    other
2732                                );
2733                                true
2734                            }
2735                        };
2736                        if stop {
2737                            return true;
2738                        }
2739                    }
2740
2741                    // Dryrun short-circuit: when the session is in
2742                    // dryrun mode (`config.dry_run_mode` set), the
2743                    // dryrun template-parameter injection above put
2744                    // a `dryrun:` field on every op template; the
2745                    // wrapper resolver picks up that field and adds
2746                    // `DryRunWrapper` as the OUTERMOST layer. The
2747                    // wrapper never calls its inner — verify /
2748                    // metrics / poll / etc. observers don't fire,
2749                    // and the real adapter's `execute()` is
2750                    // suppressed. The real adapter itself still
2751                    // constructs in full (connect, prepare, gather
2752                    // metadata); only the per-cycle outbound call
2753                    // is short-circuited.
2754                    // SRD-82 Part 3b — the error handler is the OUTERMOST
2755                    // wrapper, hand-placed after the plan cascade (mirroring
2756                    // the hand-placed innermost retry wrapper), driven by the
2757                    // policy resolved BEFORE the retry check above. Only the
2758                    // op-error ROUTER is per-op — the aggregate rate breach
2759                    // stays the phase shell's `error_policy.guard`. The
2760                    // wrapper observes the stack's ONE terminal outcome per
2761                    // cycle: routes it, tallies result-level error counters,
2762                    // captures phase errors, and applies stop/fail effects.
2763                    // Its happy path is a single branch. When no retry
2764                    // wrapper is present it also records the single-attempt
2765                    // `attempt_*` tallies (`records_attempts`).
2766                    let current = crate::wrappers::ErrorHandlerDispenser::wrap(
2767                        current,
2768                        op_error_policy,
2769                        activity.metrics.clone(),
2770                        activity.phase_errors.clone(),
2771                        activity.stop_flag.clone(),
2772                        activity.stop_reason.clone(),
2773                        template.name.clone(),
2774                        /* records_attempts */ !has_tries_wrapper,
2775                    );
2776                    dispensers.push(current);
2777
2778                    // Seal the per-template fixture. The PullPlan
2779                    // drives cycle-time reads for every wrapper that
2780                    // registered (validation ground truth, conditional
2781                    // `if`, throttle `delay`). See SRD 31 §"Pull plan
2782                    // vs bind plan".
2783                    pull_plans_per_template.push(fx.seal());
2784                }
2785                Err(e) => {
2786                    crate::diag!(
2787                        crate::observer::LogLevel::Error,
2788                        "error: adapter.map_op failed for '{}': {e}",
2789                        template.name
2790                    );
2791                    return true;
2792                }
2793            }
2794        }
2795        let dispensers = Arc::new(dispensers);
2796        // Register dispensers for adapter-specific metrics capture
2797        activity.metrics.set_dispensers(dispensers.clone());
2798        let pull_plans_per_template = Arc::new(pull_plans_per_template);
2799
2800        // `dryrun=dispenser` exit point. Every op template's
2801        // dispenser is constructed (map_op succeeded, wrapper
2802        // plan resolved, pull plan sealed). Nothing else needs
2803        // to happen for the operator to know the construction
2804        // pipeline is healthy — return cleanly without spawning
2805        // the fiber pool or the progress thread.
2806        if activity.config.stop_after_dispenser_init {
2807            crate::diag!(
2808                crate::observer::LogLevel::Info,
2809                "dryrun=dispenser: {} op-template dispenser(s) constructed; \
2810                 stopping before cycle execution",
2811                dispensers.len()
2812            );
2813            return false;
2814        }
2815
2816        let validation_metrics = Arc::new(validation_metrics);
2817        // Share the validation-metrics handle with ActivityMetrics so
2818        // the progress thread (below) can read live relevancy aggregates.
2819        activity
2820            .metrics
2821            .set_validation_metrics(validation_metrics.clone());
2822
2823        // Single activity-level rate limiter. One ops-per-sec
2824        // ceiling gates every fiber; there is no separate
2825        // stanza-rate mechanism. Activities with no `rate`
2826        // configured skip construction cleanly.
2827        let rate_limiter = activity
2828            .config
2829            .rate
2830            .map(|r| Arc::new(RateLimiter::start(nmbrs_rate::RateSpec::new(r))));
2831
2832        // Register the [`RateLimiterApplier`] against the
2833        // already-declared `rate` control if both the control
2834        // and the limiter exist. The declaration happens in
2835        // [`Self::attach_component`] — this step only wires the
2836        // applier so a runtime write actually reconfigures the
2837        // running limiter.
2838        if let (Some(ac), Some(rl)) = (activity.component.as_ref(), rate_limiter.as_ref()) {
2839            let existing: Option<nmbrs_metrics::controls::Control<nmbrs_rate::RateSpec>> = ac
2840                .read()
2841                .unwrap_or_else(|e| e.into_inner())
2842                .controls()
2843                .get("rate");
2844            if let Some(ctl) = existing {
2845                ctl.register_applier(nmbrs_rate::RateLimiterApplier::new(Arc::clone(rl)));
2846            }
2847        }
2848
2849        // SRD-100 P2 — the inline-status refresh thread is RETIRED. The
2850        // live phase status is now folded at the display consumer from the
2851        // `active_phases` snapshot (the executor attaches each phase's
2852        // render handle on-task; see `RunObserver::phase_render_attach` and
2853        // `nmbrs_tui::status_fold`). This removes the last-writer race on the
2854        // single status slot, the `std::thread` cross-execution hazard (the
2855        // thread couldn't read the SRD-88 task-local channel), and the
2856        // per-phase-clear-wipes-peers bug. The phase-scoped values below
2857        // still feed the phase-END readout + outcome line.
2858        let activity_name = activity.config.name.clone();
2859        let suppress_progress = adapters.values().any(|a| a.name() == "plotter");
2860        let start_time = Instant::now();
2861        // Use source extent for progress (data-driven), not cycles
2862        let source_for_progress = activity.source_factory.clone();
2863        let total_extent = source_for_progress
2864            .global_extent()
2865            .unwrap_or(activity.config.cycles);
2866        // One Arc<str> shared by every fiber in this phase. The
2867        // Polydat runtime-context `phase()` node clones this per read
2868        // instead of per fiber, keeping the per-cycle cost O(1).
2869        let phase_name_arc: Arc<str> = Arc::from(activity_name.as_str());
2870
2871        // Daemon-op pool. Shared across cycle-pool fibers — each
2872        // fiber's stanza walk dispatches daemon ops by spawning
2873        // a fresh fiber onto this pool instead of running them
2874        // inline. The pool enforces per-op-name fiber caps; an
2875        // overflow is a workload-design error that fails the
2876        // phase. At phase exit the cycle-pool drain runs first,
2877        // then this pool's shutdown signals and waits on every
2878        // still-running daemon (see daemon-pool drain below).
2879        let daemon_pool = Arc::new(crate::daemon_pool::DaemonPool::new());
2880
2881        // SRD 23 §"Fiber executor": fiber lifecycle goes through
2882        // a [`FiberPool`] that the `ConcurrencyApplier` can
2883        // resize via the activity's `concurrency` control. Each
2884        // fiber receives its own stop-flag and exits
2885        // cooperatively at the next cycle boundary when flagged.
2886        let pool_spawner: crate::fiber_pool::FiberSpawner = {
2887            let activity = activity.clone();
2888            let dispensers_outer = dispensers.clone();
2889            let pull_plans_outer = pull_plans_per_template.clone();
2890            let op_builder_outer = op_builder.clone();
2891            let rate_limiter_outer = rate_limiter.clone();
2892            let phase_arc_outer = phase_name_arc.clone();
2893            let daemon_pool_outer = daemon_pool.clone();
2894            // SRD-89 — snapshot this phase's controls ONCE (walk-up from the
2895            // phase component), shared lock-free across all of the phase's
2896            // fibers. Carries live handles, so servo retargets are observed.
2897            let phase_controls_outer = activity
2898                .component
2899                .as_ref()
2900                .map(crate::polydat_nodes::runtime_context::snapshot_controls)
2901                .unwrap_or_else(crate::polydat_nodes::runtime_context::empty_controls);
2902            Box::new(move |stop: crate::fiber_pool::StopFlag| {
2903                let activity = activity.clone();
2904                let dispensers = dispensers_outer.clone();
2905                let pull_plans = pull_plans_outer.clone();
2906                let op_builder = op_builder_outer.clone();
2907                let rate_limiter = rate_limiter_outer.clone();
2908                let phase_arc = phase_arc_outer.clone();
2909                let daemon_pool = daemon_pool_outer.clone();
2910                let phase_controls = phase_controls_outer.clone();
2911                // SRD-88 — carry the per-execution context into the per-cycle
2912                // fiber: the adapter's op-output, log, stop, and exec-identity
2913                // resolve to THIS execution (so concurrent executions sharing a
2914                // session capture their own output / route their own log). A
2915                // no-op on the single-run path (no context scoped — A1).
2916                tokio::spawn(crate::execution_context::propagate(async move {
2917                    // Catch panics inside the fiber so they surface
2918                    // in diagnostics rather than silently terminating
2919                    // the task. Without this, a panic in any cycle's
2920                    // accessor / binder code would leave the fiber
2921                    // gone and the run still "active" from the
2922                    // perspective of the executor, hanging the TUI
2923                    // with no visible cause. The session log line
2924                    // captures location + message; the runtime's
2925                    // own panic reporting (if any) is unchanged.
2926                    use futures::FutureExt as _;
2927                    let activity_for_panic = activity.clone();
2928                    let activity_name_for_log = activity.config.name.clone();
2929                    let phase_arc_for_exec = phase_arc.clone();
2930                    let body = crate::polydat_nodes::runtime_context::with_fiber_context(
2931                        phase_arc,
2932                        phase_controls,
2933                        async move {
2934                            executor_task(
2935                                activity,
2936                                dispensers,
2937                                pull_plans,
2938                                op_builder,
2939                                rate_limiter,
2940                                stop,
2941                                daemon_pool,
2942                                phase_arc_for_exec,
2943                            )
2944                            .await;
2945                        },
2946                    );
2947                    let result = std::panic::AssertUnwindSafe(body).catch_unwind().await;
2948                    match result {
2949                        Ok(()) => {
2950                            // Normal fiber exit is silent — the
2951                            // session log used to record one
2952                            // line per fiber here at Debug, but
2953                            // with concurrency=N, that's N lines
2954                            // per phase boundary in session.log
2955                            // for no diagnostic value (the phase
2956                            // completion + duration already
2957                            // tells the user the fibers
2958                            // completed). Panic exits below
2959                            // remain Error-level.
2960                            let _ = activity_name_for_log;
2961                        }
2962                        Err(panic_payload) => {
2963                            let msg = panic_payload
2964                                .downcast_ref::<&'static str>()
2965                                .map(|s| (*s).to_string())
2966                                .or_else(|| panic_payload.downcast_ref::<String>().cloned())
2967                                .unwrap_or_else(|| "<non-string panic payload>".into());
2968                            crate::diag!(
2969                                crate::observer::LogLevel::Error,
2970                                "fiber panic in activity '{}': {}",
2971                                activity_name_for_log,
2972                                msg
2973                            );
2974                            // A panic is a first-class failure:
2975                            // give the run a headline cause
2976                            // (stop_reason) and a structured
2977                            // PhaseOutcome error, same as the
2978                            // stop-condition failure path.
2979                            // Without these the run dies with
2980                            // only a session-log line and no
2981                            // visible "why" at phase level.
2982                            if let Ok(mut slot) = activity_for_panic.stop_reason.lock()
2983                                && slot.is_none()
2984                            {
2985                                // Headline = first line; the full
2986                                // text lands in phase_errors below.
2987                                let first = msg.lines().next().unwrap_or(&msg);
2988                                *slot = Some(format!(
2989                                    "[panic] fiber panic in activity '{activity_name_for_log}': {first}"
2990                                ));
2991                            }
2992                            if let Ok(mut errs) = activity_for_panic.phase_errors.lock() {
2993                                errs.push(crate::phase_outcome::PhaseErrorDetail {
2994                                    class: "panic".into(),
2995                                    message: msg,
2996                                    op_name: None,
2997                                    cycle: None,
2998                                    op_template: None,
2999                                    op_resolved: None,
3000                                    at_nanos: std::time::SystemTime::now()
3001                                        .duration_since(std::time::UNIX_EPOCH)
3002                                        .map(|d| d.as_nanos() as u64)
3003                                        .unwrap_or(0),
3004                                    retryable: false,
3005                                });
3006                            }
3007                            // Mark stop_flag so other fibers and the
3008                            // executor's main loop see that something
3009                            // went wrong; the run will terminate at
3010                            // the next coordination point rather
3011                            // than continuing in a half-broken state.
3012                            activity_for_panic
3013                                .stop_flag
3014                                .store(true, std::sync::atomic::Ordering::Relaxed);
3015                        }
3016                    }
3017                }))
3018            })
3019        };
3020        let fiber_pool = Arc::new(crate::fiber_pool::FiberPool::new(pool_spawner));
3021
3022        // Register the pool's applier against the already-declared
3023        // `concurrency` control (see [`Self::attach_component`]).
3024        // At run time the applier is what turns a control write
3025        // into an actual fiber-pool resize. Without a component
3026        // attached (library-level tests that call `Activity::new`
3027        // directly) we skip registration — the pool still
3028        // operates, just without the runtime control surface.
3029        if let Some(ac) = activity.component.as_ref() {
3030            let existing: Option<nmbrs_metrics::controls::Control<u32>> = ac
3031                .read()
3032                .unwrap_or_else(|e| e.into_inner())
3033                .controls()
3034                .get("concurrency");
3035            if let Some(ctl) = existing {
3036                ctl.register_applier(crate::fiber_pool::ConcurrencyApplier::new(
3037                    fiber_pool.clone(),
3038                ));
3039            }
3040        }
3041
3042        // SRD-83 Part 9 — the adaptive backpressure governor, built
3043        // BEFORE the pool spawns so the phase OPENS at the slow-start
3044        // offer (default: the floor) instead of assaulting a fragile
3045        // target at the authored ceiling. Built after
3046        // `attach_component` declared the controls it walks.
3047        let mut throttle_governor = activity.config.throttle.as_ref().and_then(|spec| {
3048            crate::throttle::ThrottleGovernor::from_spec(
3049                spec,
3050                activity.component.as_ref(),
3051                &activity.config.name,
3052                activity.config.concurrency,
3053                activity.config.rate,
3054            )
3055        });
3056        let initial_fibers = throttle_governor
3057            .as_ref()
3058            .and_then(|g| g.initial_concurrency())
3059            .unwrap_or(activity.config.concurrency);
3060        fiber_pool.spawn_initial(initial_fibers);
3061        // Wait for fibers to exit by natural exhaustion (source
3062        // drained) or `stop_flag` set by the error router.
3063        // Runtime resize-down flags some of them earlier; those
3064        // exit at the next cycle boundary and the remainder
3065        // drain when the source is done.
3066        let mut last_seen_count = activity.config.concurrency;
3067        let mut last_seen_cycles = activity.metrics.cycles_completed();
3068        let mut stuck_since = std::time::Instant::now();
3069        let mut last_logged_count = activity.config.concurrency;
3070        // SRD-83 — compile this phase's stop conditions (the default
3071        // `error_rate > error_rate_max` plus any declared `stop_when:`
3072        // predicates) as scope-bound `ScopedPredicate`s, evaluated per tick
3073        // below. Fire at most once per phase.
3074        //
3075        // The predicates bind to this phase node's OWN scope kernel
3076        // (`activity.phase_kernel`, the structural walk's cached kernel),
3077        // so they read the phase's wires as they sit — no conjured root.
3078        // (Distribution to other shell levels via `each:` is the broader
3079        // SRD-83 shell-evaluation follow-up; this binds the phase-level
3080        // conditions to their native phase scope.)
3081        let mut policy_tripped = false;
3082        let phase_start = std::time::Instant::now();
3083        let mut stop_conditions = match &activity.phase_kernel {
3084            Some(kernel) => crate::stop_conditions::StopConditionSet::build_for_phase(
3085                kernel,
3086                &activity.config.stop_when,
3087            )
3088            .unwrap_or_else(|e| {
3089                // A predicate that won't compile is the workload author's
3090                // bug; dryrun is where it should be rejected. At runtime,
3091                // log loudly and run with no stop conditions rather than
3092                // abort the phase on a synthesis error.
3093                crate::diag!(
3094                    crate::observer::LogLevel::Error,
3095                    "activity '{}': stop-condition compile failed: {e}",
3096                    activity.config.name
3097                );
3098                crate::stop_conditions::StopConditionSet::empty()
3099            }),
3100            None => crate::stop_conditions::StopConditionSet::empty(),
3101        };
3102        loop {
3103            fiber_pool.reap_finished();
3104            let n = fiber_pool.tracked_count();
3105            if n == 0 {
3106                break;
3107            }
3108            if let Some(governor) = throttle_governor.as_mut() {
3109                governor.tick(
3110                    activity.metrics.attempt_success.count(),
3111                    activity.metrics.attempt_failure.count(),
3112                );
3113            }
3114            // Periodic stall detection. A real stall means
3115            // *neither* signal of progress has moved:
3116            //   - `tracked_count` only changes when a fiber
3117            //     exits. During steady-state rampup every fiber
3118            //     is alive and busy, so this stays constant
3119            //     even when work is flying.
3120            //   - `cycles_completed` increments per finished op,
3121            //     so it reflects actual throughput regardless of
3122            //     whether any fiber has exited yet.
3123            // Either signal moving resets the stuck timer; only
3124            // when both are flat for the full 30 s do we warn.
3125            let cycles = activity.metrics.cycles_completed();
3126            // SRD-83 — evaluate the phase's stop conditions against a
3127            // fresh runtime-state snapshot (the Tick firing event). The
3128            // first predicate that trips stops the shell: fibers drain at
3129            // their next cycle boundary and the phase-end outcome becomes
3130            // Failed. (The per-condition `effect` → two-axis Outcome
3131            // mapping lands with SRD-82 Part 1; for now a trip is Failed.)
3132            if !policy_tripped && !stop_conditions.is_empty() {
3133                // Read `error_count` BEFORE `op_count`, then take a FRESH
3134                // `op_count`: every terminal error also increments
3135                // `cycles_completed`, so a cycles read taken at-or-after the
3136                // errors read is always ≥ it — guaranteeing `error_count ≤
3137                // op_count` and thus `error_rate ≤ 1.0`. The reverse order (the
3138                // stuck-timer's earlier `cycles` snapshot for `op_count`, then a
3139                // later `errors_total` read) let an erroring op completing
3140                // between the two reads push `error_count` past the stale
3141                // `op_count`, momentarily yielding `error_rate > 1.0` and
3142                // SPURIOUSLY tripping the `error_rate > 1.0` guard under
3143                // saturation (where the true rate sits exactly at 1.0).
3144                // SRD-91: the stop-condition error rate is a per-OP
3145                // proportion in [0,1], so it reads the per-op terminal
3146                // failure count (`result_failure`), not the per-attempt
3147                // `errors_total` (which can exceed op_count under retries).
3148                let result_failure = activity.metrics.result_failure.count();
3149                let cycles_total = activity.metrics.cycles_completed();
3150                // Attempt-level tallies (resolved attempts only, per the
3151                // SRD-91 counters): the see-through-retries wires. Each
3152                // wire carries its instrument's name and raw count; any
3153                // rate is derived in the predicate text.
3154                let attempt_success = activity.metrics.attempt_success.count();
3155                let attempt_failure = activity.metrics.attempt_failure.count();
3156                let state = crate::stop_conditions::RuntimeState {
3157                    cycles_total,
3158                    result_failure,
3159                    elapsed_ms: phase_start.elapsed().as_millis() as u64,
3160                    // attempt_total counts at RESOLUTION (tries.rs), so
3161                    // the invariant total == success + failure holds;
3162                    // reading the two parts keeps one consistent view.
3163                    attempt_total: attempt_success + attempt_failure,
3164                    attempt_success,
3165                    attempt_failure,
3166                    ..Default::default()
3167                };
3168                if let Some((outcome, reason, target, cancel_ops)) =
3169                    stop_conditions.evaluate(&state)
3170                {
3171                    policy_tripped = true;
3172                    // SRD-83 Part 5 — honour the condition's effect. A
3173                    // `fail` effect records a phase error (the phase ends
3174                    // Failed); a `stop` effect is a clean halt (no error,
3175                    // the phase ends Completed). Either way the stop_flag
3176                    // drains the fibers at their next cycle boundary.
3177                    // Human-readable detail: the ACTUAL wire values that
3178                    // crossed the threshold (op_count / errors / error_rate /
3179                    // elapsed), so the failure says WHY, not just which
3180                    // predicate. The predicate itself rides the `[{reason}]`
3181                    // class prefix on the slot, so the message no longer
3182                    // repeats it (matches the `[class] message` convention
3183                    // used by the cycle-/daemon-error paths).
3184                    let actual = state.describe();
3185                    // Identity + attribution: the tripped message must say
3186                    // WHICH phase instance (labels carry the sweep cell /
3187                    // partition) and WHAT failed (top error types by
3188                    // count) — not just why the predicate fired.
3189                    let labels = &activity.config.phase_labels;
3190                    let where_part = if labels.is_empty() {
3191                        format!("phase '{}'", activity.config.name)
3192                    } else {
3193                        format!("phase '{}' ({labels})", activity.config.name)
3194                    };
3195                    let top_errs = activity.metrics.top_error_types(3);
3196                    let what_part = if top_errs.is_empty() {
3197                        String::new()
3198                    } else {
3199                        format!(" — top errors: {top_errs}")
3200                    };
3201                    if outcome.is_failure() {
3202                        let msg = format!(
3203                            "stop condition tripped in {where_part} — actual: {actual}{what_part} — failing phase"
3204                        );
3205                        crate::diag!(
3206                            crate::observer::LogLevel::Error,
3207                            "activity '{}': {reason} — {msg}",
3208                            activity.config.name
3209                        );
3210                        if let Ok(mut slot) = activity.stop_reason.lock()
3211                            && slot.is_none()
3212                        {
3213                            *slot = Some(format!("[{reason}] {msg}"));
3214                            // SRD-83 Part 5 — the first stopper owns the
3215                            // outcome as well as the reason: latch the
3216                            // condition's declared effect for the phase
3217                            // shell to adopt.
3218                            if let Ok(mut oc) = activity.stop_outcome.lock() {
3219                                *oc = Some(outcome.clone());
3220                            }
3221                        }
3222                        if let Ok(mut errs) = activity.phase_errors.lock() {
3223                            errs.push(crate::phase_outcome::PhaseErrorDetail {
3224                                class: reason,
3225                                message: msg,
3226                                op_name: None,
3227                                cycle: None,
3228                                op_template: None,
3229                                op_resolved: None,
3230                                at_nanos: std::time::SystemTime::now()
3231                                    .duration_since(std::time::UNIX_EPOCH)
3232                                    .map(|d| d.as_nanos() as u64)
3233                                    .unwrap_or(0),
3234                                retryable: false,
3235                            });
3236                        }
3237                    } else {
3238                        let msg = format!(
3239                            "stop condition tripped in {where_part} — actual: {actual}{what_part} — stopping phase"
3240                        );
3241                        crate::diag!(
3242                            crate::observer::LogLevel::Warn,
3243                            "activity '{}': {reason} — {msg}",
3244                            activity.config.name
3245                        );
3246                        if let Ok(mut slot) = activity.stop_reason.lock()
3247                            && slot.is_none()
3248                        {
3249                            *slot = Some(format!("[{reason}] {msg}"));
3250                            // SRD-83 Part 5 — a graceful `stop` effect:
3251                            // latch Interrupted+Succeeded so the phase
3252                            // shell ends this phase cleanly with its
3253                            // partial result instead of deriving failure
3254                            // from the bare stop flag.
3255                            if let Ok(mut oc) = activity.stop_outcome.lock() {
3256                                *oc = Some(outcome.clone());
3257                            }
3258                        }
3259                    }
3260                    // SRD-83 follow-up — route the action to its target scope.
3261                    // Detection happened here (phase); `target` (from `at:`,
3262                    // default = innermost of `per:`) says WHERE the stop lands.
3263                    // `Phase` halts just this phase (`stop_flag`); `Scenario`/
3264                    // `Workload` latch the workload `walk_stop` so the enclosing
3265                    // shell halts (which also drains this phase via
3266                    // `should_stop()`), leaving the session running. If no
3267                    // workload handle is wired (a standalone phase), fall back
3268                    // to the phase stop.
3269                    match target {
3270                        crate::stop_conditions::StopScope::Phase => {
3271                            activity.stop_flag.store(true, Ordering::Relaxed);
3272                        }
3273                        crate::stop_conditions::StopScope::Scenario
3274                        | crate::stop_conditions::StopScope::Workload => {
3275                            match &activity.walk_stop {
3276                                Some(walk) => walk.store(true, Ordering::Relaxed),
3277                                None => activity.stop_flag.store(true, Ordering::Relaxed),
3278                            }
3279                            // SRD-83 follow-up — a `Workload`-scope halt means
3280                            // "stop the whole run", exactly like a graceful
3281                            // (first) Ctrl-C. Latching `walk_stop` alone only
3282                            // retreats the scope walk lazily, so concurrent
3283                            // siblings (other scenarios, daemon probes, an
3284                            // already-dispatched phase) keep draining until the
3285                            // walk structurally unwinds them. Raising the global
3286                            // session stop makes every live fiber exit at its
3287                            // next cycle boundary — the same cooperative signal
3288                            // Ctrl-C level 1 raises. Cleanup is unchanged: the
3289                            // walk still returns normally and the runner's RAII
3290                            // shutdown guard runs the metrics/WAL/summary
3291                            // teardown. `Scenario` scope stays walk-local — it
3292                            // must halt only its own scenario, not the session.
3293                            // `abort` (cancel_ops) is handled below and
3294                            // supersedes this cooperative global stop.
3295                            if matches!(target, crate::stop_conditions::StopScope::Workload)
3296                                && !cancel_ops
3297                            {
3298                                crate::session_signals::request_stop();
3299                            }
3300                        }
3301                    }
3302                    // SRD-83 follow-up — `action: abort`. Beyond the
3303                    // cooperative halt above, jump STRAIGHT to the cancel-ops
3304                    // rung: `abort_shutdown()` raises the global session stop
3305                    // and drops in-flight op futures NOW — no cooperative
3306                    // drain, no 10s countdown. A stop driven by errors should
3307                    // not wait for doomed ops/phases to finish (a server sick
3308                    // enough to trip this will only ever end them by client
3309                    // timeout). Cleanup is still guaranteed: the walk unwinds
3310                    // normally into the runner's RAII shutdown guard, which
3311                    // runs the metrics/WAL/summary teardown (graceful SESSION
3312                    // shutdown). Not a force-exit — a further Ctrl-C is.
3313                    if cancel_ops {
3314                        crate::session_signals::abort_shutdown(
3315                            crate::session_signals::ShutdownOrigin::StopAction,
3316                        );
3317                    }
3318                }
3319            }
3320            let count_changed = n != last_seen_count;
3321            let cycles_changed = cycles != last_seen_cycles;
3322            if count_changed || cycles_changed {
3323                last_seen_count = n;
3324                last_seen_cycles = cycles;
3325                stuck_since = std::time::Instant::now();
3326                // Log progressing-but-slow drain: every time the
3327                // count changes we re-emit at debug so a stuck
3328                // run's session.log shows the slope (or lack of it)
3329                // without flooding when drain is fast.
3330                if count_changed
3331                    && (last_logged_count.saturating_sub(n) >= 10
3332                        || (n < 10 && n != last_logged_count))
3333                {
3334                    crate::diag!(
3335                        crate::observer::LogLevel::Debug,
3336                        "activity '{}': fiber drain at {n} (from {last_logged_count})",
3337                        activity.config.name
3338                    );
3339                    last_logged_count = n;
3340                }
3341            } else if stuck_since.elapsed() > std::time::Duration::from_secs(30) {
3342                // Distinguish "genuinely stuck" from "fiber is mid-op
3343                // on a long synchronous call." The latter case
3344                // (jolokia compaction, large schema migrations,
3345                // synchronous JMX exec) legitimately blocks one
3346                // fiber for many minutes without being a bug.
3347                // `ops_started > ops_finished` proves the fiber
3348                // is busy in the adapter — log at Debug so the
3349                // session.log timeline still records the slope,
3350                // but don't surface a Warn that operators read as
3351                // "something's wrong."
3352                let started = activity.metrics.ops_started.load(Ordering::Relaxed);
3353                let finished = activity.metrics.ops_finished.load(Ordering::Relaxed);
3354                let in_flight = started.saturating_sub(finished);
3355                if in_flight > 0 {
3356                    crate::diag!(
3357                        crate::observer::LogLevel::Debug,
3358                        "activity '{}': {n} fiber(s), {in_flight} op(s) in flight, \
3359                         {cycles} cycles completed, no fiber-count or cycle-count \
3360                         change for 30s (long-running op in progress)",
3361                        activity.config.name
3362                    );
3363                } else {
3364                    crate::diag!(
3365                        crate::observer::LogLevel::Warn,
3366                        "activity '{}': {n} fibers running, {cycles} cycles completed, \
3367                         no ops in flight, no progress for 30s — likely blocked on \
3368                         lock or IO",
3369                        activity.config.name
3370                    );
3371                }
3372                stuck_since = std::time::Instant::now();
3373            }
3374            tokio::time::sleep(Duration::from_millis(5)).await;
3375        }
3376        crate::diag!(
3377            crate::observer::LogLevel::Debug,
3378            "activity '{}': all fibers drained",
3379            activity.config.name
3380        );
3381
3382        // Daemon-pool drain. Cycle-pool reached zero (cursor
3383        // exhausted or stop signal honoured); now signal each
3384        // still-running daemon, wait its per-op grace window for
3385        // the in-flight future to drop, and aggregate outcomes.
3386        //
3387        // The outcomes split two ways: clean (Completed /
3388        // Cancelled) feed into the phase metrics counters;
3389        // unclean (Errored / TimedOut / Panicked) bubble up as
3390        // phase-stopping errors via the existing stop_flag +
3391        // stop_reason channel that cycle-pool errors use.
3392        if !daemon_pool.is_empty() {
3393            crate::diag!(
3394                crate::observer::LogLevel::Debug,
3395                "activity '{}': draining {} daemon(s)",
3396                activity.config.name,
3397                daemon_pool.len()
3398            );
3399            let outcomes = daemon_pool.shutdown().await;
3400            for (op_name, exit) in &outcomes {
3401                match exit {
3402                    crate::daemon_pool::DaemonExit::Completed => {
3403                        crate::diag!(
3404                            crate::observer::LogLevel::Debug,
3405                            "daemon op '{op_name}': completed"
3406                        );
3407                    }
3408                    crate::daemon_pool::DaemonExit::Cancelled => {
3409                        activity.metrics.daemon_cancelled_total.inc();
3410                        crate::diag!(
3411                            crate::observer::LogLevel::Debug,
3412                            "daemon op '{op_name}': cancelled at phase exit"
3413                        );
3414                    }
3415                    crate::daemon_pool::DaemonExit::Errored(e) => {
3416                        activity.metrics.daemon_errors_total.inc();
3417                        let inner = e.error();
3418                        crate::diag!(
3419                            crate::observer::LogLevel::Error,
3420                            "daemon op '{op_name}' errored: [{}] {}",
3421                            inner.error_name,
3422                            inner.message
3423                        );
3424                        if let Ok(mut slot) = activity.stop_reason.lock()
3425                            && slot.is_none()
3426                        {
3427                            *slot = Some(format!(
3428                                "[{}] daemon op '{op_name}': {}",
3429                                inner.error_name, inner.message,
3430                            ));
3431                        }
3432                    }
3433                    crate::daemon_pool::DaemonExit::TimedOut => {
3434                        activity.metrics.daemon_errors_total.inc();
3435                        crate::diag!(
3436                            crate::observer::LogLevel::Error,
3437                            "daemon op '{op_name}': did not acknowledge stop \
3438                             within grace window — phase fails"
3439                        );
3440                        if let Ok(mut slot) = activity.stop_reason.lock()
3441                            && slot.is_none()
3442                        {
3443                            *slot = Some(format!(
3444                                "[daemon_shutdown_timeout] daemon op \
3445                                 '{op_name}' did not acknowledge stop \
3446                                 within its grace window",
3447                            ));
3448                        }
3449                    }
3450                    crate::daemon_pool::DaemonExit::Panicked(msg) => {
3451                        activity.metrics.daemon_errors_total.inc();
3452                        crate::diag!(
3453                            crate::observer::LogLevel::Error,
3454                            "daemon op '{op_name}' panicked: {msg}"
3455                        );
3456                        if let Ok(mut slot) = activity.stop_reason.lock()
3457                            && slot.is_none()
3458                        {
3459                            *slot = Some(format!("[daemon_panic] daemon op '{op_name}': {msg}",));
3460                        }
3461                    }
3462                }
3463                // SRD-92: the "does this exit fail the phase?" rule lives
3464                // once in the DaemonExit taxonomy's own classifier — gate
3465                // the shared stop-flag latch on it rather than re-encoding
3466                // which variants fail by which arms call store().
3467                if exit.is_phase_error() {
3468                    activity.stop_flag.store(true, Ordering::Relaxed);
3469                }
3470            }
3471        }
3472
3473        // Final completion line — always emitted (one per phase),
3474        // not gated on TTY/extent. Replaces the old executor-side
3475        // `phase 'X' complete (Ns)` line. Honors the live
3476        // `suppress_status_line` flag (TUI takes over rendering)
3477        // and the global `suppress_progress` (e.g. CI / `--quiet`).
3478        if !suppress_progress && !activity.config.suppress_status_line.load(Ordering::Relaxed) {
3479            // Counter snapshots — the readout recomputes
3480            // pct / rate / ok_pct from these primitives, so
3481            // we don't pre-format them here. Retries are
3482            // derived per the existing convention (errors
3483            // minus the skips-adjusted failed-op count).
3484            let consumed = activity.source_factory.global_consumed();
3485            let ops_completed = activity.metrics.cycles_completed();
3486            // SRD-91: terminal-success count = `result_success.count()`;
3487            // `errors_total` is RESULT-level (one inc per terminal
3488            // failure) — it drives `e:` directly. Retries = failed
3489            // attempts that were NOT terminal, i.e. `attempt_failure
3490            // - failed_ops`; the old `errors_total - failed_ops`
3491            // collapsed to ~0 once `errors_total` went result-level
3492            // with the TriesDispenser refactor.
3493            let successes = activity.metrics.result_success.count();
3494            let errors = activity.metrics.errors_total.get();
3495            let elapsed = start_time.elapsed().as_secs_f64();
3496            let failed_ops = ops_completed
3497                .saturating_sub(successes)
3498                .saturating_sub(activity.metrics.skips_total.get());
3499            let retries = activity
3500                .metrics
3501                .attempt_failure
3502                .count()
3503                .saturating_sub(failed_ops);
3504            // Concurrency (fiber count) — the `c:N` tail mirrors
3505            // the live progress line so a completed phase reads
3506            // with the same shape as a running one.
3507            let concurrency = activity.config.concurrency;
3508            // Workload-emphasized metrics — same resolver as the
3509            // inline progress line, glob-matched against the
3510            // declared `status_metrics: [...]`. Empty list ⇒ no
3511            // metrics tail; nothing is presumed to be present.
3512            let relevancy_str: String = activity
3513                .metrics
3514                .collect_status_values(&activity.config.status_metrics)
3515                .concat();
3516            // SRD-100 P2 — no explicit status clear here. The consumer
3517            // folds `active_phases`, and the executor's `PhaseCompleted`
3518            // removes this phase from that map, so the status footer
3519            // self-clears for this phase on the next render tick (while
3520            // any concurrent phase's status survives — the old single-slot
3521            // `status(None)` wiped peers).
3522            // Render the ✓ DONE line via the readout engine.
3523            // SRD-63 / Push 1: the previous inline `format!()`
3524            // is now `phase_outcome.render()` driven by an
3525            // `ActivityReadoutContext` snapshot of the values
3526            // gathered above. Output is byte-equivalent.
3527            let phase_name_bare = activity
3528                .config
3529                .name
3530                .split_once(" (")
3531                .map(|(n, _)| n.to_string())
3532                .unwrap_or_else(|| activity.config.name.clone());
3533            // Phase-end: re-read the source's final extent.
3534            // For static cursors this equals the initial
3535            // `total_extent`; for extending cursors it's the
3536            // last grown value before the policy declined
3537            // further extension.
3538            let final_extent = source_for_progress
3539                .global_extent()
3540                .unwrap_or(activity.config.cycles);
3541            // SRD-76 — the activity-level binder fire happens
3542            // BEFORE the executor records its formal Failed /
3543            // Skipped decision. The activity knows only what it
3544            // measured: a clean completion if it ran to extent,
3545            // a stop-flag trip if the error router fired. Mirror
3546            // the stop_flag into the two-axis Outcome so the
3547            // readout doesn't render ✓ on a stopped phase. The
3548            // executor records the canonical outcome on the scene
3549            // tree; this surface is the realtime display projection.
3550            let outcome = if activity.stop_flag.load(Ordering::Relaxed) {
3551                crate::phase_outcome::Outcome::failed()
3552            } else {
3553                crate::phase_outcome::Outcome::completed()
3554            };
3555            let outcome_errors: Vec<crate::phase_outcome::PhaseErrorDetail> = activity
3556                .phase_errors
3557                .lock()
3558                .ok()
3559                .map(|g| g.clone())
3560                .unwrap_or_default();
3561            // Row-level cursor progress — only for a DECLARED cursor
3562            // (`config.source_factory` present). Plain `cycles:` phases
3563            // get a synthesized `range(0, cycles)` factory, so gate on
3564            // the config Option, not the resolved factory, to keep them
3565            // on the op-denominated `cycles:` chip. Both the final
3566            // on_update tick and the ✓ line read it: a batched phase's
3567            // ops are not its rows, and the ✓ line on the cycles basis
3568            // showed 1% for a load 81% done.
3569            let (final_rows_consumed, final_rows_total) = match &activity.config.source_factory {
3570                Some(_) => (
3571                    activity.source_factory.global_consumed(),
3572                    activity.source_factory.global_extent().unwrap_or(0),
3573                ),
3574                None => (0, 0),
3575            };
3576            let ctx = crate::readout_context::ActivityReadoutContext {
3577                phase_name: phase_name_bare,
3578                phase_seq: activity.config.phase_seq,
3579                phase_labels: activity.config.phase_labels.clone(),
3580                cycles_completed: ops_completed,
3581                cycles_total: final_extent,
3582                ops_ok: successes,
3583                skips: activity.metrics.skips_total.get(),
3584                errors,
3585                retries,
3586                concurrency,
3587                elapsed_secs: elapsed,
3588                consumed,
3589                rows_consumed: final_rows_consumed,
3590                rows_total: final_rows_total,
3591                status_metric_chips: relevancy_str,
3592                depth_indent: crate::scene_tree::running_phase_indent(),
3593                use_color: crate::observer::use_color(),
3594                memo: activity.memo.load().as_str().to_string(),
3595                outcome,
3596                outcome_errors,
3597                outcome_resume_cursor: None,
3598                open_ended: activity.daemon_stop.is_some(),
3599            };
3600            // SRD-63 §6.2 / Push 9c: synthesise one final
3601            // `on_update` tick before the DONE summary. The
3602            // inline thread (if running) fires every 500 ms
3603            // and may have missed the last 100-499 ms of
3604            // counter changes — and for short phases under
3605            // the TTY/extent threshold it never spawned at
3606            // all. This guarantees the snapshot store sees
3607            // the phase's end-of-life on_update render
3608            // matching what the user would have seen if the
3609            // refresh tick had aligned exactly with phase
3610            // termination.
3611            //
3612            // Renders silently (no eprint) — the DONE line
3613            // immediately following carries the visible
3614            // ✓ summary; we just want the snapshot row to
3615            // reflect end-state.
3616            {
3617                let (final_seq, final_depth) =
3618                    crate::readout_context::resolve_phase_coord_by_name(&activity.config.name);
3619                let final_ctx = crate::readout_context::build_inline_refresh_context(
3620                    &activity.metrics,
3621                    &activity.config.name,
3622                    activity.config.concurrency,
3623                    total_extent,
3624                    final_rows_consumed,
3625                    final_rows_total,
3626                    elapsed,
3627                    u64::MAX, // sentinel: spinner frame doesn't matter at end-of-phase
3628                    &activity.config.status_metrics,
3629                    activity.memo.as_ref(),
3630                    final_seq,
3631                    final_depth,
3632                    // End-of-phase: the subject is closed, never open-ended.
3633                    false,
3634                );
3635                let phase_status_default = {
3636                    let readout = crate::readouts::Registry::lookup("phase_status")
3637                        .expect("phase_status registered");
3638                    crate::readouts::BakedBody::from_single(readout, crate::readouts::Lod::Labeled)
3639                };
3640                if let Ok(mut binder) = crate::readouts::binder::build_event_binder_with_cli(
3641                    &activity.config.readouts,
3642                    crate::lifecycle::EventType::Update,
3643                    phase_status_default,
3644                    activity.config.cli_readout_override.as_deref(),
3645                ) {
3646                    use crate::readouts::ReadoutBinder;
3647                    let mut sink = crate::readouts::StringSink::with_capacity(192);
3648                    binder.fire(crate::lifecycle::EventType::Update, &final_ctx, &mut sink);
3649                    let rendered_final = sink.take();
3650                    crate::readouts::snapshot::capture(
3651                        activity.config.snapshot_writer.as_ref(),
3652                        crate::lifecycle::EventType::Update,
3653                        &final_ctx,
3654                        "binder",
3655                        crate::readouts::Lod::Labeled,
3656                        &rendered_final,
3657                    );
3658                }
3659            }
3660
3661            // gutter/final — the guaranteed ONE final gutter update.
3662            // A declared `final:` template is evaluated here, at phase
3663            // end (wires over the activity chain, status-metric
3664            // aggregates as fallback), and stored into the gutter slot
3665            // the display actor reads when stamping this phase's ✓
3666            // outcome DETAIL line. Without a `final:`, the slot already
3667            // holds the during-form's LAST PUBLISHED value (the
3668            // dispenser publishes on every op completion) — that last
3669            // computed value IS the final update; re-evaluating the
3670            // per-cycle template here would run it against a
3671            // degenerate end-of-phase context.
3672            {
3673                let fin = activity
3674                    .gutter_final_template
3675                    .lock()
3676                    .ok()
3677                    .and_then(|g| g.clone());
3678                if let Some(declared) = fin
3679                    && let Some(final_spec) =
3680                        evaluate_final_gutter(&activity, op_builder.source_kernel(), &declared)
3681                {
3682                    activity.gutter.store(Some(Arc::new(final_spec)));
3683                }
3684            }
3685
3686            // Build a one-shot binder for `on_phase_end`:
3687            // workload's `on_phase_end:` overrides if any,
3688            // else the default body — `phase_outcome` for the
3689            // normative ✓/✗ status line, followed by
3690            // `error_readout` which renders the per-error block
3691            // below it. `error_readout` is a no-op (zero bytes)
3692            // when the phase has no recorded errors, so the
3693            // default is safe for both success and failure
3694            // paths; failure paths get the structured error
3695            // block appended without the per-cycle warns
3696            // having to spam the screen mid-phase.
3697            let phase_outcome_default = {
3698                let phase_outcome = crate::readouts::Registry::lookup("phase_outcome")
3699                    .expect("phase_outcome registered");
3700                let error_readout = crate::readouts::Registry::lookup("error_readout")
3701                    .expect("error_readout registered");
3702                crate::readouts::BakedBody::from_steps(vec![
3703                    crate::readouts::binder::RenderStep::Render {
3704                        readout: phase_outcome,
3705                        lod: crate::readouts::Lod::Labeled,
3706                        layout: crate::readouts::binder::LayoutMode::Auto,
3707                        options: crate::readouts::ReadoutOptions::new(),
3708                        color: None,
3709                    },
3710                    crate::readouts::binder::RenderStep::Render {
3711                        readout: error_readout,
3712                        lod: crate::readouts::Lod::Labeled,
3713                        layout: crate::readouts::binder::LayoutMode::Auto,
3714                        options: crate::readouts::ReadoutOptions::new(),
3715                        color: None,
3716                    },
3717                ])
3718            };
3719            let rendered = match crate::readouts::build_event_binder(
3720                &activity.config.readouts,
3721                crate::lifecycle::EventType::PhaseEnd,
3722                phase_outcome_default,
3723            ) {
3724                Ok(mut binder) => {
3725                    use crate::readouts::ReadoutBinder;
3726                    let mut sink = crate::readouts::StringSink::with_capacity(160);
3727                    binder.fire(crate::lifecycle::EventType::PhaseEnd, &ctx, &mut sink);
3728                    sink.take()
3729                }
3730                Err(e) => {
3731                    crate::diag!(
3732                        crate::observer::LogLevel::Error,
3733                        "readouts: failed to bind on_phase_end — {e}"
3734                    );
3735                    String::new()
3736                }
3737            };
3738            // Push 6: capture the on_phase_end render to the
3739            // snapshot store. The DONE line is the canonical
3740            // "what the operator saw at completion" — replay
3741            // returns it byte-for-byte.
3742            if !rendered.is_empty() {
3743                crate::readouts::snapshot::capture(
3744                    activity.config.snapshot_writer.as_ref(),
3745                    crate::lifecycle::EventType::PhaseEnd,
3746                    &ctx,
3747                    "binder",
3748                    crate::readouts::Lod::Labeled,
3749                    &rendered,
3750                );
3751            }
3752            // `skipped_phases=elide|prune`: a FULLY-SKIPPED phase (every
3753            // cycle `if:`-gated off, nothing measured, no errors) leaves
3754            // no completion line — the snapshot store above still holds
3755            // the render for replay, but the live readout stays silent.
3756            // `mark` (the default) emits phase_outcome's explicit
3757            // `⊘ gated off` form instead.
3758            let fully_skipped = {
3759                let skips = activity.metrics.skips_total.get();
3760                skips > 0
3761                    && ops_completed > 0
3762                    && skips >= ops_completed
3763                    && successes == 0
3764                    && errors == 0
3765            };
3766            let elide_skipped = fully_skipped
3767                && matches!(
3768                    crate::observer::skipped_phase_display(),
3769                    crate::observer::SkippedPhaseDisplay::Elide
3770                        | crate::observer::SkippedPhaseDisplay::Prune
3771                );
3772            if !rendered.is_empty() && !elide_skipped {
3773                // SRD-81 push 1: the per-phase ✓ outcome is a typed
3774                // `PhaseOutcome` projection, not a generic diagnostic.
3775                // The terminal scrollback shows it; the TUI tree /
3776                // active-phase panel render it natively; the TUI log
3777                // panel (diagnostics-only) filters it out instead of
3778                // garbling the multi-line ANSI as one Span. (push 1b
3779                // replaces this pre-rendered string with a structured
3780                // marker the sinks render from the snapshot.)
3781                crate::observer::log_tagged(
3782                    crate::observer::LogLevel::Info,
3783                    crate::observer::EventTag::at(
3784                        crate::lifecycle::EventType::PhaseEnd,
3785                        crate::observer::EventCategory::Outcome,
3786                    ),
3787                    &rendered,
3788                );
3789            }
3790        }
3791
3792        // Print validation summary AND capture to the metrics
3793        // store in one pass. `snapshot()` drains the histogram
3794        // (delta semantics), so we must use the same snapshot
3795        // for both printing and SQLite capture.
3796        if !validation_metrics.is_empty() {
3797            let mut total_passed = 0u64;
3798            let mut total_failed = 0u64;
3799            let mut total_empty_rows = 0u64;
3800            let now = Instant::now();
3801            let mut final_snapshot = MetricSet::at(now, Duration::ZERO);
3802            let activity_labels = activity.labels.clone();
3803
3804            for vm in validation_metrics.iter() {
3805                total_passed += vm.passed();
3806                total_failed += vm.failed();
3807                total_empty_rows += vm.empty_rows();
3808
3809                for (name, stats) in &vm.relevancy_stats {
3810                    let snap = stats.snapshot();
3811                    if !snap.is_empty() {
3812                        let mean = snap.mean();
3813                        let p50 = snap.p50();
3814                        let p99 = snap.p99();
3815                        let min = snap.min();
3816                        let max = snap.max();
3817                        let n = snap.len();
3818                        // Relevancy stats (recall@k, precision@k, F1@k)
3819                        // are fractions in [0, 1]. Render as percent
3820                        // — the unit operators read these in.
3821                        // Underlying gauges below stay as fractions so
3822                        // downstream consumers (recall_summary,
3823                        // metrics scrapes) keep their existing scale.
3824                        // Indent matches the phase / DONE / complete
3825                        // lines so the relevancy summary nests under
3826                        // the phase row in tui=terminal output.
3827                        let depth_indent = crate::scene_tree::running_phase_indent();
3828                        let color = crate::observer::use_color();
3829                        let dim = if color { "\x1b[2m" } else { "" };
3830                        let bold = if color { "\x1b[1m" } else { "" };
3831                        let reset = if color { "\x1b[0m" } else { "" };
3832                        // SRD-92: a PhaseDetail projection — a detail
3833                        // row of the completion block above it, so the
3834                        // terminal sink renders it under the blank
3835                        // divider margin (no timing triad) and
3836                        // `completed_phases=headers` drops it.
3837                        crate::observer::log_tagged(
3838                            crate::observer::LogLevel::Info,
3839                            crate::observer::EventTag::at(
3840                                crate::lifecycle::EventType::PhaseEnd,
3841                                crate::observer::EventCategory::Evaluation,
3842                            ),
3843                            &format!(
3844                                "{depth_indent}{bold}{name}{reset}: mean={:.2}% {dim}p50={:.2}% p99={:.2}% min={:.2}% max={:.2}% (n={n}){reset}",
3845                                mean * 100.0,
3846                                p50 * 100.0,
3847                                p99 * 100.0,
3848                                min * 100.0,
3849                                max * 100.0,
3850                            ),
3851                        );
3852                        // Pick up `k`/`r` from the F64Stats's
3853                        // labels so per-phase summary gauges
3854                        // remain unique under OpenMetrics §4.5
3855                        // when multiple relevancy configs share
3856                        // a phase but differ in cutoff.
3857                        let stats_labels = stats.labels();
3858                        let k_label = stats_labels.get("k").map(str::to_string);
3859                        let r_label = stats_labels.get("r").map(str::to_string);
3860                        // Generic observability point: a relevancy
3861                        // function's per-phase summary has been
3862                        // computed and is about to be published
3863                        // as `{name}_{stat}` gauges. The trace
3864                        // fires for ANY relevancy function — the
3865                        // labels carry the publishing dimensions
3866                        // (phase, profile, …, k, r, n) from the
3867                        // surrounding scope, not from any
3868                        // workload-specific knowledge.
3869                        if crate::observer::trace_enabled() {
3870                            let mut trace_labels = activity_labels.with("n", n.to_string());
3871                            if let Some(k) = &k_label {
3872                                trace_labels = trace_labels.with("k", k);
3873                            }
3874                            if let Some(r) = &r_label {
3875                                trace_labels = trace_labels.with("r", r);
3876                            }
3877                            crate::observer::trace(
3878                                &trace_labels,
3879                                &format!(
3880                                    "event=relevancy.publish fn={name} n={n} \
3881                                     mean={mean:.6} p50={p50:.6} p99={p99:.6} \
3882                                     min={min:.6} max={max:.6}"
3883                                ),
3884                            );
3885                        }
3886                        for (stat, val) in [
3887                            ("mean", mean),
3888                            ("p50", p50),
3889                            ("p99", p99),
3890                            ("min", min),
3891                            ("max", max),
3892                        ] {
3893                            let mut gauge_labels = activity_labels.with("n", n.to_string());
3894                            if let Some(k) = &k_label {
3895                                gauge_labels = gauge_labels.with("k", k);
3896                            }
3897                            if let Some(r) = &r_label {
3898                                gauge_labels = gauge_labels.with("r", r);
3899                            }
3900                            final_snapshot.insert_gauge(
3901                                format!("{name}_{stat}"),
3902                                gauge_labels,
3903                                val,
3904                                now,
3905                            );
3906                        }
3907                    }
3908                }
3909            }
3910
3911            // Phase-level aggregate counters. One pair per phase
3912            // — `total_passed` / `total_failed` sum across every
3913            // op's `vm` so the metric instance is unique under
3914            // OpenMetrics §4.5 (LabelSets must be unique). The
3915            // earlier per-`vm` insertion path inserted N copies
3916            // with identical labels, which the snapshot
3917            // assembler now rejects as a duplicate. Per-op
3918            // breakdown isn't carried by the validation counters
3919            // anyway — the labels are activity-scope, not
3920            // op-scope.
3921            if total_passed > 0 || total_failed > 0 {
3922                final_snapshot.insert_counter(
3923                    "validations_passed",
3924                    activity_labels.clone(),
3925                    total_passed,
3926                    now,
3927                );
3928                final_snapshot.insert_counter(
3929                    "validations_failed",
3930                    activity_labels.clone(),
3931                    total_failed,
3932                    now,
3933                );
3934            }
3935
3936            // Scored cycles whose ground-truth row held no neighbor
3937            // (SRD-115 §4.5). Reported only when there were some: an
3938            // unfiltered run has none, and a zero-valued series on
3939            // every phase would be noise.
3940            if total_empty_rows > 0 {
3941                final_snapshot.insert_counter(
3942                    "relevancy_empty_rows",
3943                    activity_labels.clone(),
3944                    total_empty_rows,
3945                    now,
3946                );
3947            }
3948
3949            // Validation summary line: only emit when there are
3950            // failures. On clean runs the relevancy summary's
3951            // `n=N` already conveys "N validations passed", and
3952            // the `validation: N passed, 0 failed` line was just
3953            // duplicate text on every phase. On failure runs the
3954            // line is signal — promote it to Warn so it stands
3955            // out and route only when failed > 0.
3956            if total_failed > 0 {
3957                let depth_indent = crate::scene_tree::running_phase_indent();
3958                crate::diag!(
3959                    crate::observer::LogLevel::Warn,
3960                    "{depth_indent}validation: {} passed, {} FAILED",
3961                    total_passed,
3962                    total_failed
3963                );
3964            }
3965
3966            // The same statistics per cell, for each op that places its
3967            // measurements by dimension (`cell:` on the op, SRD-115
3968            // §4.4). The totals above are unchanged; these series sit a
3969            // tier below them and carry `op` and the coordinate.
3970            for vm in validation_metrics.iter() {
3971                if let Some(cells) = &vm.cells {
3972                    publish_op_cells(cells, &mut final_snapshot, now);
3973                }
3974            }
3975
3976            if !final_snapshot.is_empty() {
3977                activity
3978                    .validation_frame
3979                    .lock()
3980                    .unwrap_or_else(|e| e.into_inner())
3981                    .replace(final_snapshot);
3982            }
3983        }
3984
3985        // NOTE: this is the `stopped` RETURN that `run_phase` reads to
3986        // decide whether the phase FAILED — so it must reflect only
3987        // abnormal stops (the error-handler `stop_flag`, Ctrl-C, a walk
3988        // fault). A daemon phase's `daemon_stop` is a CLEAN termination
3989        // (Interrupted+Succeeded — the foreground it shadows finished),
3990        // so it drives the loop BREAKS below but is deliberately NOT a
3991        // fault. The daemon exclusion lives once in `StopView::abnormal`
3992        // (session_signals.rs) — this delegates to it rather than
3993        // re-deriving the rule (was a hand-rolled copy; SRD-92 dedup).
3994        activity.stop_view().abnormal()
3995    }
3996}
3997
3998/// Publish an op's per-cell relevancy statistics at phase end: the
3999/// `<function>_<stat>` gauges the phase totals publish, one set per
4000/// cell, labelled with the cell's labels (`op` and the coordinate
4001/// included), and one log line per cell.
4002///
4003/// A cell's failed validations and empty ground-truth rows are
4004/// published as counters when there were any, as the totals are.
4005fn publish_op_cells(cells: &crate::op_cells::OpCells, snapshot: &mut MetricSet, now: Instant) {
4006    let all = cells.cells();
4007    if all.is_empty() {
4008        return;
4009    }
4010    let depth_indent = crate::scene_tree::running_phase_indent();
4011    let dims: Vec<&str> = cells.dimensions().collect();
4012    crate::observer::log_tagged(
4013        crate::observer::LogLevel::Info,
4014        crate::observer::EventTag::at(
4015            crate::lifecycle::EventType::PhaseEnd,
4016            crate::observer::EventCategory::Evaluation,
4017        ),
4018        &format!(
4019            "{depth_indent}{op} by {dims}: {n} cells",
4020            op = cells.op(),
4021            dims = dims.join(", "),
4022            n = all.len(),
4023        ),
4024    );
4025    for cell in &all {
4026        let validation = cell.validation();
4027        let mut names: Vec<&String> = validation.relevancy_stats.keys().collect();
4028        names.sort();
4029        let mut parts: Vec<String> = Vec::new();
4030        for name in names {
4031            let stats = &validation.relevancy_stats[name];
4032            let snap = stats.snapshot();
4033            if snap.is_empty() {
4034                continue;
4035            }
4036            let n = snap.len();
4037            parts.push(format!("{name}={:.2}% (n={n})", snap.mean() * 100.0));
4038            let stats_labels = stats.labels();
4039            let mut gauge_labels = cell.labels().with("n", n.to_string());
4040            for key in ["k", "r"] {
4041                if let Some(value) = stats_labels.get(key) {
4042                    gauge_labels = gauge_labels.with(key, value);
4043                }
4044            }
4045            for (stat, value) in [
4046                ("mean", snap.mean()),
4047                ("p50", snap.p50()),
4048                ("p99", snap.p99()),
4049                ("min", snap.min()),
4050                ("max", snap.max()),
4051            ] {
4052                snapshot.insert_gauge(format!("{name}_{stat}"), gauge_labels.clone(), value, now);
4053            }
4054        }
4055        let failed = validation.failed();
4056        if failed > 0 {
4057            parts.push(format!("validations_failed={failed}"));
4058            snapshot.insert_counter("validations_failed", cell.labels().clone(), failed, now);
4059        }
4060        let empty = validation.empty_rows();
4061        if empty > 0 {
4062            parts.push(format!("empty_rows={empty}"));
4063            snapshot.insert_counter("relevancy_empty_rows", cell.labels().clone(), empty, now);
4064        }
4065        if parts.is_empty() {
4066            continue;
4067        }
4068        let coordinate: Vec<String> = dims
4069            .iter()
4070            .map(|dim| format!("{dim}={}", cell.coordinate().get(dim).unwrap_or("")))
4071            .collect();
4072        crate::observer::log_tagged(
4073            crate::observer::LogLevel::Info,
4074            crate::observer::EventTag::at(
4075                crate::lifecycle::EventType::PhaseEnd,
4076                crate::observer::EventCategory::Evaluation,
4077            ),
4078            &format!(
4079                "{depth_indent}  {}: {}",
4080                coordinate.join(" "),
4081                parts.join(" ")
4082            ),
4083        );
4084    }
4085}
4086
4087/// Executor task for the tiered DriverAdapter interface.
4088///
4089/// Each fiber has its own FiberBuilder (lock-free Polydat state).
4090/// Ops within a stanza are processed in dependency groups:
4091/// - Groups execute sequentially (captures flow between groups)
4092/// - Ops within a group execute concurrently (join_all)
4093///
4094/// Groups are determined at init time by analyzing capture
4095/// declarations and references across templates.
4096// `pull_plans`: per-template wrapper-side `PullPlan`s, sealed at init.
4097// Drives cycle-time reads for validation / conditional / throttle
4098// wrappers via memoized `PullHandle`s. See SRD 31 §"Pull plan vs bind
4099// plan".
4100/// One-shot daemon dispatch. Mirrors `executor_task`'s setup
4101/// (FiberBuilder + per-op kernel attach) but dispatches the
4102/// daemon's op exactly once, racing the in-flight future
4103/// against the per-daemon stop flag AND the activity-global
4104/// stop flag.
4105///
4106/// Cancellation path: when either flag flips, the
4107/// `dispenser.execute(...)` future is dropped at the next
4108/// await point — for the HTTP adapter that's mid-`send()`,
4109/// which propagates as a clean reqwest cancellation. The
4110/// daemon returns `DaemonExit::Cancelled`. The pool's grace
4111/// window (see `DaemonPool::shutdown`) gives the adapter time
4112/// to observe the drop and exit; deadlines past the grace
4113/// surface as `DaemonExit::TimedOut`.
4114///
4115/// Daemon ops increment `ops_started` / `ops_finished` like
4116/// any other op execution — the operator-visible op-count
4117/// surface stays consistent regardless of fiber kind. Service
4118/// + response timing is recorded the same way the cycle-pool
4119///   records it (one Instant pair around the execute), but no
4120///   rate-limiter acquire — daemons aren't subject to the
4121///   activity's ops-per-second ceiling.
4122async fn daemon_dispatch(
4123    activity: Arc<Activity>,
4124    dispensers: Arc<Vec<Arc<dyn OpDispenser>>>,
4125    pull_plans: Arc<Vec<crate::fixture::PullPlan>>,
4126    op_builder: Arc<crate::synthesis::OpBuilder>,
4127    template_idx: usize,
4128    op_name: String,
4129    stop: crate::daemon_pool::DaemonStopFlag,
4130) -> crate::daemon_pool::DaemonExit {
4131    let mut fiber = op_builder.create_fiber_builder();
4132    fiber.attach_dispenser_kernels(&dispensers);
4133    let dispenser = dispensers[template_idx].clone();
4134    let fields = crate::adapter::ResolvedFields::new(Vec::new(), Vec::new());
4135    // Resolve the wrapper-side pull plan against this daemon fiber's
4136    // kernel — same as the cycle-pool path. Daemon ops carry wrappers
4137    // too (notably `if:`, whose IF_COND wrapper registers a pull for
4138    // its predicate); an empty `ResolvedPulls` would panic when that
4139    // handle resolves. Captures the daemon reads (e.g. a `shared`
4140    // cell written by an earlier stanza op gating `if: sstables > 1`)
4141    // are visible here because the daemon dispatches at its op-walk
4142    // position, after the writer op completed.
4143    let pulls = fiber.resolve_pulls_for_idx(template_idx, &pull_plans[template_idx]);
4144    let cycle_wires = fiber.cycle_wires(template_idx);
4145    let ctx = crate::fixture::ExecCtx::with_wires(&fields, &pulls, &cycle_wires);
4146
4147    activity.metrics.ops_started.fetch_add(1, Ordering::Relaxed);
4148    let started = std::time::Instant::now();
4149    let activity_stop = activity.stop_flag.clone();
4150    let exit = tokio::select! {
4151        result = dispenser.execute(0, &ctx) => match result {
4152            Ok(_) => crate::daemon_pool::DaemonExit::Completed,
4153            Err(e) => crate::daemon_pool::DaemonExit::Errored(e),
4154        },
4155        _ = poll_daemon_stop(&stop, &activity_stop) => {
4156            crate::daemon_pool::DaemonExit::Cancelled
4157        }
4158    };
4159    let service_nanos = started.elapsed().as_nanos() as u64;
4160    activity.metrics.cycles_total.inc();
4161    activity
4162        .metrics
4163        .ops_finished
4164        .fetch_add(1, Ordering::Relaxed);
4165    activity.metrics.service_time.record(service_nanos);
4166    activity.metrics.response_time.record(service_nanos);
4167    // SRD-91 op-outcome taxonomy for daemon dispatch. The `attempt_*`
4168    // counters are owned by the innermost `TriesDispenser` in the op's
4169    // wrapper stack (which this daemon op runs through, same as a foreground
4170    // op), so only the RESULT-level tallies are recorded here — no
4171    // double-count. Cancelled / TimedOut are shutdown outcomes tracked via
4172    // daemon_cancelled_total / daemon_errors_total, not op results.
4173    match &exit {
4174        crate::daemon_pool::DaemonExit::Completed => {
4175            activity.metrics.result_total.inc();
4176            activity.metrics.result_success.observe(service_nanos);
4177        }
4178        crate::daemon_pool::DaemonExit::Errored(_) => {
4179            // `errors_total` / per-type tallies + policy effects already
4180            // ran in the OUTERMOST `ErrorHandlerDispenser` of the daemon
4181            // op's own stack (SRD-82 Part 3b) — only the result-level
4182            // outcome is recorded here.
4183            activity.metrics.result_total.inc();
4184            activity.metrics.result_failure.observe(service_nanos);
4185        }
4186        _ => {}
4187    }
4188    crate::diag!(
4189        crate::observer::LogLevel::Debug,
4190        "daemon op '{op_name}' exit={} elapsed_ms={:.0}",
4191        exit.label(),
4192        service_nanos as f64 / 1_000_000.0
4193    );
4194    exit
4195}
4196
4197/// Polls both the per-daemon stop flag and the activity-global
4198/// stop flag at 50ms granularity. Returns as soon as either is
4199/// set. The 50ms cadence is a compromise: fast enough that
4200/// daemon cancellation lands well under the typical 5-second
4201/// grace window, slow enough that an idle daemon doesn't burn
4202/// CPU. Replacing this with a `tokio::sync::Notify`-backed
4203/// flag would drop the latency to zero but requires touching
4204/// the StopFlag surface and isn't load-bearing for the
4205/// trigger-and-observe pattern.
4206async fn poll_daemon_stop(
4207    daemon_stop: &crate::daemon_pool::DaemonStopFlag,
4208    activity_stop: &Arc<std::sync::atomic::AtomicBool>,
4209) {
4210    loop {
4211        if daemon_stop.load(Ordering::Acquire) || activity_stop.load(Ordering::Acquire) {
4212            return;
4213        }
4214        tokio::time::sleep(Duration::from_millis(50)).await;
4215    }
4216}
4217
4218// reason: cohesive per-fiber executor driver; each argument is a distinct
4219// runtime channel/handle the loop needs — splitting into a struct would only
4220// relocate the same fields with no clarity gain.
4221#[allow(clippy::too_many_arguments)]
4222async fn executor_task(
4223    activity: Arc<Activity>,
4224    dispensers: Arc<Vec<Arc<dyn OpDispenser>>>,
4225    pull_plans: Arc<Vec<crate::fixture::PullPlan>>,
4226    op_builder: Arc<crate::synthesis::OpBuilder>,
4227    // Optional activity-level rate limiter. `acquire` fires
4228    // once per cycle before adapter dispatch. There is no
4229    // separate stanza-rate limiter.
4230    rate_limiter: Option<Arc<RateLimiter>>,
4231    // Per-fiber cooperative-exit flag owned by the activity's
4232    // [`crate::fiber_pool::FiberPool`]. Set to `true` by
4233    // `ConcurrencyApplier` when the pool scales down.
4234    fiber_stop: crate::fiber_pool::StopFlag,
4235    // Daemon-op pool — shared across cycle-pool fibers. Each
4236    // stanza walk that reaches a daemon op dispatches a fresh
4237    // fiber onto this pool via `try_spawn` and continues
4238    // without awaiting; the daemon body runs to completion
4239    // (or until phase-exit drain signals stop) on its own
4240    // tokio task.
4241    daemon_pool: Arc<crate::daemon_pool::DaemonPool>,
4242    // Phase name — used to wrap the daemon body in the same
4243    // runtime-context guard cycle-pool fibers use, so daemon
4244    // ops can read `phase()` / `cycle()` runtime-context
4245    // wires.
4246    phase_name_arc: Arc<str>,
4247) {
4248    let stanza_positions = activity.op_sequence.stanza_length();
4249    // SRD-22 batching cover-once: the phase-cursor stride is the SUM of
4250    // each stanza op's `rows_per_op` (its uniform per-invocation cursor
4251    // consumption), NOT the raw stanza length. A normal op contributes 1
4252    // (identical to the pre-batching model); a batch op contributes its
4253    // fixed stride `N`. Reserving `Σ rows_per_op` per stanza and handing
4254    // each op a contiguous sub-run of its own `rows_per_op` makes
4255    // consecutive stanzas cover DISJOINT ordinal runs — every ordinal is
4256    // inserted exactly once. Precomputed once (rows_per_op is fixed per
4257    // dispenser at map_op) so the hot loop pays no per-stanza virtual
4258    // calls and `Σ per_pos_rows == stanza_stride` by construction.
4259    let per_pos_rows: Vec<usize> = (0..stanza_positions)
4260        .map(|pos| {
4261            let (idx, _) = activity.op_sequence.get_with_index(pos as u64);
4262            dispensers[idx].rows_per_op().max(1)
4263        })
4264        .collect();
4265    let stanza_stride: usize = per_pos_rows.iter().sum::<usize>().max(1);
4266    // Per-fiber `FiberBuilder` carries scope values (per-iteration
4267    // extern inputs) populated by the OpBuilder, so iter-var
4268    // references like `{table}` in op templates resolve to the
4269    // current iteration's value.
4270    let mut fiber = op_builder.create_fiber_builder();
4271
4272    // Shutdown-ladder subscription (session_signals module doc): the op
4273    // dispatch below races the adapter call against the CANCEL rung
4274    // (level 2) so a hung request — one that will only ever end by
4275    // client timeout — can be dropped mid-flight, letting the drain and
4276    // the process-level cleanup (WAL consolidation, summaries) proceed.
4277    // One receiver per fiber; the race is a `select!` per dispatch.
4278    let mut shutdown_rx = crate::session_signals::subscribe_shutdown();
4279
4280    // SRD-68 Push 3 — materialise per-fiber subscope kernels from
4281    // each dispenser's canonical kernel. The fiber holds them as
4282    // `Vec<Option<PolydatKernel>>` indexed parallel to the dispenser
4283    // registry; cycle dispatch reads `fiber.per_op_kernel(template_idx)`
4284    // to populate `ExecCtx::wires` for the firing dispenser.
4285    // Dispensers that return `None` from `canonical_kernel()` get
4286    // a `None` slot and the cycle falls back to `NullWireSource`.
4287    fiber.attach_dispenser_kernels(&dispensers);
4288
4289    // Create per-fiber source reader (used for all phases).
4290    // Source-declared phases will eventually use the advancer model,
4291    // but for now all phases go through the source reader.
4292    // SRD-92 Step 5e — the per-cycle stream flows through the unified
4293    // `ChildSource` contract: a `CursorSource` wraps the reader; `poll_next` IS
4294    // `reserve(stanza_stride)` (per-stanza, not per-cycle → zero per-cycle
4295    // overhead), yielding an ordinal `Range`; `render` is the per-ordinal fetch.
4296    // The level selects `CursorReserve` — this very FiberPool loop.
4297    use crate::child_source::{Child, ChildSource, CursorSource, Drive, select_drive};
4298    let mut source = CursorSource::new(activity.source_factory.create_reader(), stanza_stride);
4299    debug_assert_eq!(select_drive(source.realizability()), Drive::CursorReserve);
4300
4301    loop {
4302        if activity.stopped() {
4303            break;
4304        } // SRD-92 Step 0: one stop view
4305        if fiber_stop.load(std::sync::atomic::Ordering::Acquire) {
4306            break;
4307        } // per-fiber scale-down (distinct)
4308
4309        // Phase 1: RESERVE — CAS on shared cursor, instantaneous.
4310        // Acquires one stanza's worth of ordinals. This is the only
4311        // shared-state interaction per stanza.
4312        let range = match source.poll_next() {
4313            Some(Child::Ordinals(r)) => r,
4314            // CursorSource yields only Ordinals; anything else (None) means the
4315            // source is exhausted → the phase-poll rewind / standard break.
4316            _ => {
4317                // SRD-75 phase-poll: source exhausted ends a poll
4318                // iteration. Check the predicate; if false and
4319                // the deadline hasn't elapsed, sleep, rewind the
4320                // factory's shared cursor, and re-create the
4321                // reader for another iteration. Phase-poll
4322                // mandates concurrency=1 (workload-load
4323                // validation) so this is the only fiber and the
4324                // rewind isn't racing siblings.
4325                if let Some(pp) = activity.phase_poll.clone() {
4326                    // Check predicate first — handles the case
4327                    // where the very first iteration's captures
4328                    // already satisfy the condition.
4329                    //
4330                    // Polydat comparison operators (`==`, `!=`, `<`,
4331                    // …) return u64 (0/1) per SRD-10 §"BinOpKind"
4332                    // — there's no Bool result type for these.
4333                    // Accept either Value::Bool(true) (in case
4334                    // a future Polydat release adds a Bool result
4335                    // path) OR a non-zero numeric value as
4336                    // "satisfied". This mirrors the workload
4337                    // author's expectation that `(a == 1) & (b == 0)`
4338                    // evaluates to "true" when both clauses hold.
4339                    //
4340                    // `__poll_until` is a DYNAMIC binding
4341                    // (SRD-11 §"Two Evaluation Lifecycles") —
4342                    // its value depends on per-iteration capture
4343                    // writes through the phase scope's
4344                    // SharedCells, so a buffer read via
4345                    // `lookup()` returns the LAST-EVALUATED
4346                    // value (None on first iteration, never
4347                    // updated). We MUST trigger re-evaluation
4348                    // via `pull()`. The phase scope kernel is
4349                    // held as `Arc<PolydatKernel>` (immutable
4350                    // handle), so we evaluate via the per-fiber
4351                    // `main_kernel` instead — main_kernel is
4352                    // built from the phase scope program (so
4353                    // it has `__poll_until` as an output) and
4354                    // is wired to the SAME SharedCells the
4355                    // captures wrote to (so its pull returns
4356                    // the live value).
4357                    // SRD-75 (C5) — strict-gate `require:` selectors.
4358                    // While any selector is unresolved the gate HOLDS:
4359                    // the predicate is not trusted, because an
4360                    // unregistered family reads 0.0 silently and a
4361                    // `>=`-shaped predicate could pass spuriously (or
4362                    // a `<`-shaped one hang to timeout). Past the
4363                    // grace window (one poll interval) an unresolved
4364                    // selector is a hard `poll_require` failure —
4365                    // loud and immediate, never a mystery hang.
4366                    let unresolved: Vec<&String> = pp
4367                        .require
4368                        .iter()
4369                        .filter(|s| !nmbrs_metrics::polydat_nodes::metric_selector_resolves(s))
4370                        .collect();
4371                    if !unresolved.is_empty() && std::time::Instant::now() >= pp.require_grace {
4372                        let names = unresolved
4373                            .iter()
4374                            .map(|s| format!("'{s}'"))
4375                            .collect::<Vec<_>>()
4376                            .join(", ");
4377                        let formatted_reason = format!(
4378                            "[poll_require] poll `require:` selector(s) {names} \
4379                             resolved to no registered instrument within the \
4380                             grace window — the gate's `until:` would read 0.0 \
4381                             for them. Check the family name and labels (e.g. \
4382                             phase=<name>), and that the producing phase is \
4383                             running. SRD-75 (C5)."
4384                        );
4385                        crate::diag!(
4386                            crate::observer::LogLevel::Error,
4387                            "activity '{}': {formatted_reason}",
4388                            activity.config.name
4389                        );
4390                        if let Ok(mut slot) = activity.stop_reason.lock()
4391                            && slot.is_none()
4392                        {
4393                            *slot = Some(formatted_reason.clone());
4394                        }
4395                        if let Ok(mut errs) = activity.phase_errors.lock() {
4396                            errs.push(crate::phase_outcome::PhaseErrorDetail {
4397                                class: "poll_require".into(),
4398                                message: formatted_reason,
4399                                op_name: None,
4400                                cycle: None,
4401                                op_template: None,
4402                                op_resolved: None,
4403                                at_nanos: std::time::SystemTime::now()
4404                                    .duration_since(std::time::UNIX_EPOCH)
4405                                    .map(|d| d.as_nanos() as u64)
4406                                    .unwrap_or(0),
4407                                retryable: false,
4408                            });
4409                        }
4410                        activity
4411                            .stop_flag
4412                            .store(true, std::sync::atomic::Ordering::Relaxed);
4413                        break;
4414                    }
4415                    let requires_ok = unresolved.is_empty();
4416                    // SAME call the op-level poll makes. An execution node is
4417                    // an execution node: the predicate is resolved through one
4418                    // interface (`CycleWires`, which PULLS and so re-evaluates
4419                    // a dynamic binding) and judged by one truthiness rule.
4420                    //
4421                    // This was a third, divergent implementation — an inline
4422                    // match whose `_ => false` arm made a non-empty string
4423                    // falsy here and truthy under `if:` / `while:` / op-poll,
4424                    // for the same expression. (The `require:` gate above
4425                    // additionally withholds trust in the predicate until
4426                    // every declared metric selector resolves.)
4427                    let satisfied = requires_ok && {
4428                        let wires = fiber.main_wires();
4429                        // An unresolved predicate (`None`) is a wiring
4430                        // fault, not a false predicate. Keep waiting rather
4431                        // than silently declaring the phase done; the
4432                        // timeout below reports it with the predicate named.
4433                        crate::wrappers::condition::holds(
4434                            &wires,
4435                            crate::wrappers::condition::UNTIL_BINDING,
4436                        )
4437                        .unwrap_or(false)
4438                    };
4439                    if satisfied {
4440                        // SRD-75 metric_name emission is wired
4441                        // when the per-fiber mutable kernel handle
4442                        // Elapsed time goes to the metric (when one
4443                        // is configured); operators read it there.
4444                        // Logging it at INFO every loop is just
4445                        // narrating the happy path.
4446                        if let Some(name) = &pp.metric_name {
4447                            let elapsed = pp.started_at.elapsed().as_secs_f64();
4448                            crate::diag!(
4449                                crate::observer::LogLevel::Debug,
4450                                "phase-poll: predicate satisfied; {name}={elapsed:.3}s",
4451                            );
4452                        }
4453                        break;
4454                    }
4455                    if std::time::Instant::now() >= pp.deadline {
4456                        let elapsed = pp.started_at.elapsed().as_secs_f64();
4457                        // Compose the diagnostic once; the `abort`
4458                        // path appends a workload-invalidation
4459                        // note so the operator immediately knows
4460                        // that the whole run is terminating, not
4461                        // just this phase.
4462                        let invalidation_note = match pp.on_timeout {
4463                            PhasePollTimeoutPolicy::Abort => {
4464                                " — `on_timeout: abort` declared by the workload; \
4465                                 requesting session stop (the whole run terminates)"
4466                            }
4467                            PhasePollTimeoutPolicy::Error => "",
4468                        };
4469                        let formatted_reason = format!(
4470                            "[poll_timeout] phase-poll deadline reached after {elapsed:.1}s \
4471                             with predicate '__poll_until' still not Bool(true) \
4472                             (SRD-75 §\"Workload-load validation\" — adjust `timeout_ms` \
4473                             or the `until:` predicate){invalidation_note}"
4474                        );
4475                        if let Ok(mut slot) = activity.stop_reason.lock()
4476                            && slot.is_none()
4477                        {
4478                            *slot = Some(formatted_reason.clone());
4479                        }
4480                        // SRD-76 — push a structured
4481                        // `PhaseErrorDetail` into the
4482                        // activity's phase_errors buffer so
4483                        // the executor's phase-end build of
4484                        // `PhaseOutcome` captures the
4485                        // poll_timeout with its class and
4486                        // message. No op_template /
4487                        // op_resolved because the failure is
4488                        // at the phase level (no specific op
4489                        // dispenser fired the error).
4490                        if let Ok(mut errs) = activity.phase_errors.lock() {
4491                            errs.push(crate::phase_outcome::PhaseErrorDetail {
4492                                class: "poll_timeout".into(),
4493                                message: formatted_reason,
4494                                op_name: None,
4495                                cycle: None,
4496                                op_template: None,
4497                                op_resolved: None,
4498                                at_nanos: std::time::SystemTime::now()
4499                                    .duration_since(std::time::UNIX_EPOCH)
4500                                    .map(|d| d.as_nanos() as u64)
4501                                    .unwrap_or(0),
4502                                retryable: false,
4503                            });
4504                        }
4505                        activity
4506                            .stop_flag
4507                            .store(true, std::sync::atomic::Ordering::Relaxed);
4508                        // SRD-75 `on_timeout: abort` —
4509                        // workload-author declares that an
4510                        // unsatisfied predicate makes the whole
4511                        // run meaningless. Set the session-wide
4512                        // stop signal; the scenario walker
4513                        // observes it on its next iteration check
4514                        // (`session_signals::stop_requested()`)
4515                        // and unwinds without entering the next
4516                        // sweep cell. The phase itself still
4517                        // returns Err for the normal stop-flag
4518                        // path; the session signal is the
4519                        // CROSS-PHASE escalation.
4520                        if matches!(pp.on_timeout, PhasePollTimeoutPolicy::Abort) {
4521                            crate::diag!(
4522                                crate::observer::LogLevel::Error,
4523                                "phase-poll: `on_timeout: abort` triggered after \
4524                                 {elapsed:.1}s; requesting session-wide stop \
4525                                 (SRD-75 §\"on_timeout\")",
4526                            );
4527                            crate::session_signals::request_stop();
4528                        }
4529                        break;
4530                    }
4531                    // Wait, rewind, re-create the reader.
4532                    tokio::time::sleep(pp.interval).await;
4533                    if !activity.source_factory.rewind_for_poll() {
4534                        if let Ok(mut slot) = activity.stop_reason.lock()
4535                            && slot.is_none()
4536                        {
4537                            *slot = Some(
4538                                "[phase_poll] source factory doesn't support \
4539                                 rewind_for_poll(); phase-poll requires a \
4540                                 rewindable source (RangeSourceFactory or \
4541                                 ExtendingRangeSourceFactory). SRD-75."
4542                                    .to_string(),
4543                            );
4544                        }
4545                        activity
4546                            .stop_flag
4547                            .store(true, std::sync::atomic::Ordering::Relaxed);
4548                        break;
4549                    }
4550                    source =
4551                        CursorSource::new(activity.source_factory.create_reader(), stanza_stride);
4552                    continue;
4553                }
4554                break; // source exhausted (standard path)
4555            }
4556        };
4557
4558        activity.metrics.stanzas_total.inc();
4559        // Stanza-boundary `reset_captures()` was historically called
4560        // here to defend against capture leakage between cycles. That
4561        // defence is redundant under the post-closure-binding-economy
4562        // architecture: every reachable wire is either a per-cycle
4563        // kernel output (recomputed each cycle from inputs and the
4564        // current `cycle`), a closed-loop capture (the same op that
4565        // reads the wire is the op that writes it; a failed write
4566        // short-circuits the consumer via OpResult error), a magic
4567        // extern (`body` / `count` / `ok`, rewritten pre-eval by
4568        // ResultDispenser), or a scope-invariant iter-var / workload
4569        // param (constant across the phase activation). None of those
4570        // can hold a stale value that a successful cycle would read.
4571        // The per-cycle reset + re-apply round-trip was 40% of single-
4572        // fiber CPU; removing it leaves end-state semantics identical.
4573
4574        // Phase 2: RENDER + EXECUTE — distribute the reserved run across
4575        // the stanza's ops via `StanzaRuns`. Each op covers a contiguous
4576        // ordinal sub-run `[cycle, cycle + run_len)` of its own
4577        // `rows_per_op` (1 for ordinary ops, N for a batch op); `Σ ==
4578        // stanza_stride`, so consecutive stanzas cover DISJOINT ordinal
4579        // runs (SRD-22 cover-once). The LUT POSITION (not the ordinal)
4580        // selects the op, so a batch op that advances the cursor by N
4581        // still maps to the right stanza slot. At the cursor tail
4582        // `reserve` returned a short range, so the last op's `run_len`
4583        // is the truncated remainder — the partial final batch is still
4584        // inserted, never over-read, never dropped. Sequential in
4585        // declaration order.
4586        for (pos, cycle, run_len) in
4587            crate::child_source::StanzaRuns::new(range.clone(), &per_pos_rows)
4588        {
4589            if activity.stopped() {
4590                break;
4591            } // SRD-92 Step 0: one stop view
4592
4593            // Mark op as active from render through result join.
4594            // "Active" means this fiber is working on an op — resolving
4595            // fields, waiting for the adapter, or recording results.
4596            activity.metrics.ops_started.fetch_add(1, Ordering::Relaxed);
4597
4598            // Render the source item at the sub-run base (fiber-local, no
4599            // shared state). The op reads `[cycle, cycle + run_len)`.
4600            let item = source.render(cycle);
4601            // Publish the cycle to the enclosing fiber-context
4602            // scope so any Polydat node reading `cycle()` or implicitly
4603            // `cycle` inside the DAG sees the same ordinal as
4604            // adapter execution. No-op outside a fiber scope.
4605            crate::polydat_nodes::runtime_context::set_task_cycle(cycle);
4606
4607            let wait_start = Instant::now();
4608            if let Some(ref rl) = rate_limiter {
4609                rl.acquire().await;
4610            }
4611            let wait_nanos = wait_start.elapsed().as_nanos() as u64;
4612
4613            // The stanza POSITION (not the ordinal) selects the op —
4614            // `get_with_index(pos)` returns `lut[pos]`, stable regardless
4615            // of how many ordinals prior batch ops consumed.
4616            let (template_idx, template) = activity.op_sequence.get_with_index(pos as u64);
4617
4618            // Daemon-op dispatch. If the template declares
4619            // `daemon: ...` (non-disabled), spawn a fresh
4620            // fiber onto the daemon pool instead of running
4621            // the op inline. The pool enforces a per-op-name
4622            // fiber cap; an overflow is a workload-design
4623            // error that fails the phase. Cycle-pool moves
4624            // on to the next stanza op as soon as the spawn
4625            // returns (Ok or Err).
4626            if !template.daemon.is_disabled() {
4627                let cap = template
4628                    .daemon
4629                    .max_fibers()
4630                    .expect("non-disabled daemon has cap");
4631                let cancel_grace = template
4632                    .daemon_cancel_grace_ms
4633                    .map(std::time::Duration::from_millis);
4634                let activity_d = activity.clone();
4635                let dispensers_d = dispensers.clone();
4636                let pull_plans_d = pull_plans.clone();
4637                let op_builder_d = op_builder.clone();
4638                let phase_arc_d = phase_name_arc.clone();
4639                let op_name_d = template.name.clone();
4640                let spawn_result =
4641                    daemon_pool.try_spawn(op_name_d.clone(), cap, cancel_grace, move |stop| {
4642                        let activity = activity_d;
4643                        let dispensers = dispensers_d;
4644                        let pull_plans = pull_plans_d;
4645                        let op_builder = op_builder_d;
4646                        let phase_arc = phase_arc_d;
4647                        let op_name = op_name_d;
4648                        async move {
4649                            use futures::FutureExt as _;
4650                            let phase_controls = activity
4651                                .component
4652                                .as_ref()
4653                                .map(crate::polydat_nodes::runtime_context::snapshot_controls)
4654                                .unwrap_or_else(
4655                                    crate::polydat_nodes::runtime_context::empty_controls,
4656                                );
4657                            let body = crate::polydat_nodes::runtime_context::with_fiber_context(
4658                                phase_arc,
4659                                phase_controls,
4660                                daemon_dispatch(
4661                                    activity.clone(),
4662                                    dispensers,
4663                                    pull_plans,
4664                                    op_builder,
4665                                    template_idx,
4666                                    op_name.clone(),
4667                                    stop,
4668                                ),
4669                            );
4670                            match std::panic::AssertUnwindSafe(body).catch_unwind().await {
4671                                Ok(exit) => exit,
4672                                Err(payload) => {
4673                                    let msg = payload
4674                                        .downcast_ref::<&'static str>()
4675                                        .map(|s| (*s).to_string())
4676                                        .or_else(|| payload.downcast_ref::<String>().cloned())
4677                                        .unwrap_or_else(|| "<non-string panic payload>".into());
4678                                    crate::diag!(
4679                                        crate::observer::LogLevel::Error,
4680                                        "daemon op '{op_name}' panicked: {msg}"
4681                                    );
4682                                    activity
4683                                        .stop_flag
4684                                        .store(true, std::sync::atomic::Ordering::Relaxed);
4685                                    crate::daemon_pool::DaemonExit::Panicked(msg)
4686                                }
4687                            }
4688                        }
4689                    });
4690                match spawn_result {
4691                    Ok(()) => {
4692                        // Dispatch succeeded — the daemon fiber
4693                        // (`daemon_dispatch`) owns this op's accounting
4694                        // end to end: it records `ops_started` when it
4695                        // runs and `cycles_total` / `ops_finished` + the
4696                        // SRD-91 result outcome when it completes. Counting
4697                        // the stanza-position here too DOUBLE-counted the
4698                        // op — one extra `cycles_total`/`ops_finished`
4699                        // with no matching result — which dragged ok%
4700                        // below 100% and pushed phase progress above it,
4701                        // and broke the `cycles_total == result_total +
4702                        // skips_total` invariant. `StanzaRuns` already
4703                        // advanced past this op's sub-run (daemon ops have
4704                        // rows_per_op == 1); just skip the inline execute
4705                        // path and let the daemon fiber count.
4706                        continue;
4707                    }
4708                    Err(msg) => {
4709                        crate::diag!(
4710                            crate::observer::LogLevel::Error,
4711                            "daemon op '{}' spawn failed: {msg}",
4712                            template.name
4713                        );
4714                        activity.stop_flag.store(true, Ordering::Release);
4715                        if let Ok(mut slot) = activity.stop_reason.lock()
4716                            && slot.is_none()
4717                        {
4718                            *slot = Some(format!("daemon op '{}' spawn: {msg}", template.name));
4719                        }
4720                        return;
4721                    }
4722                }
4723            }
4724
4725            fiber.set_source_item(&item);
4726            // SRD-68 Push 5: `ctx.fields` is no longer the
4727            // resolution surface for adapters or wrappers — they
4728            // read everything through `ctx.wires` (the bound GK
4729            // context). The empty `ResolvedFields` satisfies the
4730            // `ExecCtx` struct-shape contract until the field is
4731            // removed from the trait surface entirely.
4732            let fields = crate::adapter::ResolvedFields::new(Vec::new(), Vec::new());
4733
4734            // Resolve the wrapper-side pull plan against this
4735            // fiber's GkState (one indexed pull per registered
4736            // name, no name hashing). The resulting `pulls` is
4737            // disjoint from `fields`: adapters see only `fields`,
4738            // wrappers see only `pulls`.
4739            //
4740            // SRD-13d Phase 9 — when this op template materialised
4741            // its own kernel, the plan was sealed against the
4742            // op-template program; resolve_pulls_for_op picks
4743            // that kernel's state. Flattened op-templates fall
4744            // through to the main kernel (the workload program)
4745            // — same call site, the lookup is idempotent.
4746            let pulls = fiber.resolve_pulls_for_idx(template_idx, &pull_plans[template_idx]);
4747            let dispenser = &dispensers[template_idx];
4748            // SRD-68 invariant I-2: cycle-time reads against the
4749            // firing dispenser's per-fiber kernel slot, exposed
4750            // through the narrow `WireSource` trait. `CycleWires`
4751            // wraps the per-fiber kernel handle for the cycle's
4752            // duration so `WireSource::get` can drive output pulls
4753            // (`pull(&mut state, …)` through interior mutability)
4754            // alongside input/constant lookups. Dispensers with
4755            // no canonical kernel (legacy adapters, wrapper
4756            // delegates) fall through to the `NullWireSource`
4757            // baseline `ExecCtx::new` provides.
4758            // SRD-13f / SRD-68: cycle-time wire reads go through a
4759            // single kernel handle — the dispenser's per-fiber
4760            // op-template kernel. Every visible cross-scope wire
4761            // was wired into that kernel at construction (cells
4762            // for shared, folded constants for workload params,
4763            // construction-time slot setup + per-cycle refresh in
4764            // `set_inputs` for other parent outputs). The local
4765            // read API resolves every name; the wires layer never
4766            // composes chains externally.
4767            let cycle_wires = fiber.cycle_wires(template_idx);
4768            let mut exec_ctx = crate::fixture::ExecCtx::with_wires(&fields, &pulls, &cycle_wires);
4769            // Hand the op the ACTUAL reserved sub-run length so a batch op
4770            // inserts exactly `[base, base + run_len)` — the full run, or
4771            // the short tail at cursor exhaustion. Ordinary ops ignore it.
4772            exec_ctx.run_len = run_len;
4773            let service_start = Instant::now();
4774            // The op runs through the wrapper stack ONCE. The innermost
4775            // `TriesDispenser` (when the op has a `tries` budget) owns the
4776            // attempt loop, `attempt_*` counters,
4777            // and the per-attempt panic catch; the OUTERMOST
4778            // `ErrorHandlerDispenser` (SRD-82 Part 3b) owns the whole-stack
4779            // panic backstop and the terminal-error handling — policy
4780            // routing, `errors_total` / per-type tallies, phase-error
4781            // capture, and the stop/fail effects. This loop sees exactly ONE
4782            // terminal outcome per cycle and keeps only the result-level
4783            // accounting. The residual `catch_unwind` guards a panic in the
4784            // error wrapper's OWN routing code (a runtime bug, not an op
4785            // failure): keep the fiber alive, mark the phase stopped.
4786            let outcome: Result<crate::adapter::OpResult, crate::adapter::ExecutionError> = {
4787                use futures::FutureExt as _;
4788                let op_fut = std::panic::AssertUnwindSafe(dispenser.execute(cycle, &exec_ctx))
4789                    .catch_unwind();
4790                // Race the whole op stack against the shutdown ladder's
4791                // CANCEL rung. `biased` polls the op first, so the cancel
4792                // branch costs one extra poll per dispatch on the happy
4793                // path. On cancellation the stack's future is DROPPED —
4794                // that is the cancel — and a synthesised non-retryable
4795                // error stands in as the terminal outcome (the errors
4796                // wrapper was inside the dropped future, so result-level
4797                // accounting below is all that records it).
4798                let raced = tokio::select! {
4799                    biased;
4800                    r = op_fut => Some(r),
4801                    _ = crate::session_signals::ops_cancelled(&mut shutdown_rx) => None,
4802                };
4803                match raced {
4804                    None => Err(crate::adapter::ExecutionError::Op(
4805                        crate::adapter::AdapterError {
4806                            error_name: "cancelled".into(),
4807                            message: "in-flight op cancelled by shutdown \
4808                                      escalation (Ctrl-C)"
4809                                .into(),
4810                            retryable: false,
4811                        },
4812                    )),
4813                    Some(Ok(r)) => r,
4814                    Some(Err(payload)) => {
4815                        let msg = payload
4816                            .downcast_ref::<&'static str>()
4817                            .map(|s| (*s).to_string())
4818                            .or_else(|| payload.downcast_ref::<String>().cloned())
4819                            .unwrap_or_else(|| "<non-string panic payload>".into());
4820                        activity.metrics.errors_total.inc();
4821                        activity.metrics.count_error_type("panic");
4822                        activity.stop_flag.store(true, Ordering::Relaxed);
4823                        if let Ok(mut slot) = activity.stop_reason.lock()
4824                            && slot.is_none()
4825                        {
4826                            // Headline = first line; the full
4827                            // enriched text travels in the
4828                            // AdapterError message and renders
4829                            // once in the phase error list
4830                            // (SRD-82 §one full render).
4831                            let first = msg.lines().next().unwrap_or(&msg);
4832                            *slot = Some(format!(
4833                                "[panic] op '{}' at cycle {}: {first}",
4834                                template.name, cycle,
4835                            ));
4836                        }
4837                        Err(crate::adapter::ExecutionError::Op(
4838                            crate::adapter::AdapterError {
4839                                error_name: "panic".into(),
4840                                message: msg,
4841                                retryable: false,
4842                            },
4843                        ))
4844                    }
4845                }
4846            };
4847            let service_nanos = service_start.elapsed().as_nanos() as u64;
4848            let (success, skipped) = match outcome {
4849                Ok(result) => (true, result.skipped),
4850                Err(_) => (false, false),
4851            };
4852
4853            // Per-OP totals (SRD-91): `cycles_total` counts every op
4854            // dispatched; executed ops go to `result_total`
4855            // (= result_success + result_failure). Skipped ops increment
4856            // `skips_total` in the `if:` wrapper (wrappers/if.rs), so
4857            // `cycles_total == result_total + skips_total` holds without a
4858            // tally here. The per-op error rate reads `result_failure`
4859            // (in [0,1]); the per-attempt `errors_total` was already
4860            // tallied in the loop.
4861            activity.metrics.cycles_total.inc();
4862            if !skipped {
4863                activity.metrics.result_total.inc();
4864                activity.metrics.service_time.record(service_nanos);
4865                activity.metrics.wait_time.record(wait_nanos);
4866                activity
4867                    .metrics
4868                    .response_time
4869                    .record(service_nanos + wait_nanos);
4870                // `tries_histogram` is recorded by the TriesDispenser (it owns
4871                // the attempt count).
4872                if success {
4873                    activity.metrics.result_success.observe(service_nanos);
4874                    // Captures landed on the per-op-template kernel
4875                    // directly via ctx.wires.write inside the
4876                    // dispenser stack — no post-execute pump.
4877                    //
4878                    // Two kernel-side steps remain:
4879                    //
4880                    // 1. Rule 2 write-through commit on the
4881                    //    op-template kernel — pulls every
4882                    //    `__write_<X>` and stores its value through
4883                    //    the cell-bound input slot for `<X>`,
4884                    //    propagating result-binding LHS values up
4885                    //    to parent `shared` cells. No-op when the
4886                    //    kernel carries no write-throughs. A
4887                    //    type-stability violation (scope_model.md
4888                    //    §"Type stability") is a DETERMINISTIC
4889                    //    workload bug — every cycle would repeat it —
4890                    //    so it stops the phase with the write-site
4891                    //    diagnostic (same treatment as the panic arm).
4892                    if let Err(e) = fiber.commit_op_template_write_throughs_for_idx(template_idx) {
4893                        activity.metrics.errors_total.inc();
4894                        activity.metrics.count_error_type("type_mismatch");
4895                        activity.stop_flag.store(true, Ordering::Relaxed);
4896                        if let Ok(mut slot) = activity.stop_reason.lock()
4897                            && slot.is_none()
4898                        {
4899                            *slot = Some(format!(
4900                                "[type_mismatch] op '{}' at cycle {}: {e}",
4901                                template.name, cycle,
4902                            ));
4903                        }
4904                    }
4905                    // 2. Pull every output of the op-template
4906                    //    kernel so side-effecting nodes (log_info,
4907                    //    log_debug) inside result-binding compute
4908                    //    chains actually evaluate. Without this, a
4909                    //    result-binding whose LHS isn't a
4910                    //    write-through stays dormant.
4911                    fiber.pull_all_op_template_outputs_for_idx(template_idx);
4912                } else {
4913                    activity.metrics.result_failure.observe(service_nanos);
4914                }
4915            }
4916
4917            // Op fully processed — render, execute, and metrics all done.
4918            activity
4919                .metrics
4920                .ops_finished
4921                .fetch_add(1, Ordering::Relaxed);
4922        }
4923    }
4924}
4925
4926/// Best-effort terminal column count read off stderr (fd 2) via
4927/// the `TIOCGWINSZ` ioctl. Returns `None` when stderr isn't a
4928/// TTY or the call fails. The status renderer (now hosted by
4929/// `nmbrs-tui::log_only_sink`) uses this to clamp the rendered
4930/// status to a single visual row, since a wrap would leave
4931/// previous-tick text on screen below the cursor — the in-place
4932/// rewrite only erases from the cursor through end of the
4933/// current visual line.
4934#[cfg(unix)]
4935pub fn terminal_cols() -> Option<usize> {
4936    use std::os::raw::c_int;
4937    #[repr(C)]
4938    struct WinSize {
4939        ws_row: u16,
4940        ws_col: u16,
4941        ws_xpixel: u16,
4942        ws_ypixel: u16,
4943    }
4944    let mut ws = WinSize {
4945        ws_row: 0,
4946        ws_col: 0,
4947        ws_xpixel: 0,
4948        ws_ypixel: 0,
4949    };
4950    // SAFETY: `libc::ioctl` is FFI; `TIOCGWINSZ` writes into the
4951    // out-parameter which we own (pinned on the stack for the
4952    // duration of the call). Failure is signalled by negative
4953    // return — we ignore the actual errno.
4954    let rc: c_int = unsafe { libc::ioctl(2, libc::TIOCGWINSZ, &mut ws as *mut _) };
4955    if rc < 0 || ws.ws_col == 0 {
4956        return None;
4957    }
4958    Some(ws.ws_col as usize)
4959}
4960
4961/// Windows variant: `GetConsoleScreenBufferInfo` on the stderr
4962/// handle. The console API is declared by hand rather than via a
4963/// `windows-sys` dependency — two kernel32 imports don't justify
4964/// one. Width is the visible window (srWindow), not the scrollback
4965/// buffer width, matching what the status line can occupy.
4966#[cfg(windows)]
4967pub fn terminal_cols() -> Option<usize> {
4968    use std::ffi::c_void;
4969    #[repr(C)]
4970    struct Coord {
4971        x: i16,
4972        y: i16,
4973    }
4974    #[repr(C)]
4975    struct SmallRect {
4976        left: i16,
4977        top: i16,
4978        right: i16,
4979        bottom: i16,
4980    }
4981    #[repr(C)]
4982    struct ConsoleScreenBufferInfo {
4983        size: Coord,
4984        cursor_position: Coord,
4985        attributes: u16,
4986        window: SmallRect,
4987        maximum_window_size: Coord,
4988    }
4989    #[link(name = "kernel32")]
4990    unsafe extern "system" {
4991        fn GetStdHandle(std_handle: u32) -> *mut c_void;
4992        fn GetConsoleScreenBufferInfo(
4993            console: *mut c_void,
4994            info: *mut ConsoleScreenBufferInfo,
4995        ) -> i32;
4996    }
4997    const STD_ERROR_HANDLE: u32 = -12i32 as u32;
4998    const INVALID_HANDLE_VALUE: *mut c_void = -1isize as *mut c_void;
4999    // SAFETY: both calls only write into the out-parameter we own;
5000    // failure is signalled by null/INVALID handle or zero return.
5001    unsafe {
5002        let handle = GetStdHandle(STD_ERROR_HANDLE);
5003        if handle.is_null() || handle == INVALID_HANDLE_VALUE {
5004            return None;
5005        }
5006        let mut info = std::mem::zeroed::<ConsoleScreenBufferInfo>();
5007        if GetConsoleScreenBufferInfo(handle, &mut info) == 0 {
5008            return None;
5009        }
5010        let cols = i32::from(info.window.right) - i32::from(info.window.left) + 1;
5011        if cols <= 0 { None } else { Some(cols as usize) }
5012    }
5013}
5014
5015/// Glob-style match: `*` matches zero or more characters, `?`
5016/// matches exactly one character, every other byte must match
5017/// literally. Recursive — adequate for the short patterns
5018/// `status_metrics:` accepts (`recall*`, `latency_p99`, etc.).
5019/// Trades worst-case quadratic time for simplicity; the
5020/// candidate set is also tiny (low single-digit count of metric
5021/// Evaluate a gutter template ONCE at phase end (the `final:` form,
5022/// or the during-form's guaranteed last update). Placeholders resolve
5023/// through the wires of a throwaway subscope of the activity's source
5024/// kernel (shared cells and captures visible), then any names still
5025/// unresolved fall back to the phase's STATUS-METRIC aggregates
5026/// (`{recall}`, `{latency_p50}`, …) formatted exactly like the status
5027/// chips. Numeric kinds (`bar`/`spark`) additionally require the fully
5028/// resolved string to parse as f64; failures degrade to None (no
5029/// final cell) — the display must never fail a completed phase.
5030fn evaluate_final_gutter(
5031    activity: &Activity,
5032    source_kernel: &Arc<crate::scope_kernel::ScopeKernel>,
5033    declared: &crate::wrappers::gutter::GutterTemplate,
5034) -> Option<crate::wrappers::gutter::GutterSpec> {
5035    use crate::wrappers::gutter::{GutterKind, GutterSpec};
5036    let (kind, template) = (declared.kind, declared.template.as_str());
5037    // Wires pass: a fork of the phase scope (its cells shared) gives
5038    // template names their live end-of-phase values.
5039    let rendered = {
5040        let mut k = source_kernel.fork();
5041        let wires = crate::wires::CycleWires::new(&mut k);
5042        crate::wires::substitute_via_wires(template, &wires).ok()
5043    };
5044    let mut text = rendered.unwrap_or_else(|| template.to_string());
5045
5046    // Status-metric fallback for placeholders the wires didn't know:
5047    // relevancy aggregates and the latency family, formatted like the
5048    // status chips so `{recall}` in a final template reads identically
5049    // to the `recall:` chip beside it.
5050    if text.contains('{') {
5051        let mut candidates: Vec<(String, String)> = Vec::new();
5052        for live in activity.metrics.collect_relevancy_live() {
5053            if live.total_count > 0 {
5054                candidates.push((live.name, format!("{:.2}%", live.total_mean * 100.0)));
5055            }
5056        }
5057        let snap = activity.metrics.service_time.peek_snapshot();
5058        let h = &snap.histogram;
5059        if !h.is_empty() {
5060            let fmt = nmbrs_metrics::reporters::summary::format_duration;
5061            candidates.push(("latency_p50".into(), fmt(h.value_at_quantile(0.50) as f64)));
5062            candidates.push(("latency_p99".into(), fmt(h.value_at_quantile(0.99) as f64)));
5063            candidates.push(("latency_max".into(), fmt(h.max() as f64)));
5064            candidates.push(("latency_mean".into(), fmt(h.mean())));
5065        }
5066        for (name, val) in &candidates {
5067            text = text.replace(&format!("{{{name}}}"), val);
5068        }
5069    }
5070
5071    // A template still carrying unresolved placeholders means the value
5072    // it names was never measured (a gated-off recall phase has no
5073    // relevancy aggregate) — no measurement, no cell. The completion
5074    // detail line keeps its standard stamp instead of showing the
5075    // literal `recall {recall}`.
5076    if text.contains('{') && text.contains('}') {
5077        return None;
5078    }
5079    match kind {
5080        GutterKind::Labeled => {
5081            let (name, value) = text.split_once('\u{1f}').unwrap_or(("", text.as_str()));
5082            Some(GutterSpec::Labeled {
5083                name: name.to_string(),
5084                value: value.to_string(),
5085            })
5086        }
5087        GutterKind::Text => Some(GutterSpec::Text(text)),
5088        GutterKind::Bar => text
5089            .trim()
5090            .parse::<f64>()
5091            .ok()
5092            .map(|v| GutterSpec::Bar(v.clamp(0.0, 1.0))),
5093        GutterKind::Spark => text.trim().parse::<f64>().ok().map(GutterSpec::Spark),
5094    }
5095}
5096
5097/// names per phase).
5098fn glob_match(pattern: &str, candidate: &str) -> bool {
5099    glob_match_bytes(pattern.as_bytes(), candidate.as_bytes())
5100}
5101
5102fn glob_match_bytes(pat: &[u8], s: &[u8]) -> bool {
5103    match (pat.first(), s.first()) {
5104        (None, None) => true,
5105        (Some(b'*'), _) => {
5106            // zero-or-more: try consuming nothing OR consume one
5107            // char of input and re-attempt.
5108            glob_match_bytes(&pat[1..], s) || (!s.is_empty() && glob_match_bytes(pat, &s[1..]))
5109        }
5110        (Some(b'?'), Some(_)) => glob_match_bytes(&pat[1..], &s[1..]),
5111        (Some(p), Some(c)) if p == c => glob_match_bytes(&pat[1..], &s[1..]),
5112        _ => false,
5113    }
5114}
5115
5116// `spinner_frame`, `braille_bar`, `format_eta` moved to
5117// `crate::readouts::format` in Push 2 — the readouts that
5118// consume them now own the helpers. `truncate_to_width`
5119// stays here (it's a surface-level width-clamp concern,
5120// not a readout concern).
5121
5122/// Truncate `s` to at most `max_cols` *visible* columns,
5123/// appending an ellipsis when truncation actually elides
5124/// content. Skips ANSI SGR escape sequences (`\x1b[...m`) when
5125/// counting visible width — they consume characters in the
5126/// string but no terminal columns. The truncation point is
5127/// always at a character boundary that's NOT inside an escape
5128/// sequence, so we never emit a half-broken `\x1b[3` to the
5129/// terminal.
5130pub fn truncate_to_width(s: &str, max_cols: usize) -> String {
5131    if max_cols == 0 {
5132        return String::new();
5133    }
5134    let bytes = s.as_bytes();
5135    let mut visible = 0usize;
5136    let mut byte_pos = 0usize; // last clean truncation point
5137    let mut chars = s.char_indices();
5138    while let Some((i, c)) = chars.next() {
5139        if c == '\x1b' && bytes.get(i + 1) == Some(&b'[') {
5140            // SGR escape: walk until the final byte (`m`,
5141            // `K`, `J`, etc.) so we don't truncate mid-escape.
5142            for (_, ch) in chars.by_ref() {
5143                if ch.is_ascii_alphabetic() {
5144                    break;
5145                }
5146            }
5147            // byte_pos doesn't advance — escape costs no
5148            // visible columns, and the next plain char's
5149            // position is what we'd truncate to.
5150            continue;
5151        }
5152        if visible + 1 > max_cols.saturating_sub(1) {
5153            return format!("{}…", &s[..byte_pos]);
5154        }
5155        visible += 1;
5156        byte_pos = i + c.len_utf8();
5157    }
5158    s.to_string()
5159}
5160
5161#[cfg(test)]
5162mod tests {
5163    use super::*;
5164    use crate::adapter::{AdapterError, ExecutionError, OpResult};
5165    use std::collections::HashMap;
5166    use std::sync::atomic::{AtomicU64, Ordering};
5167
5168    /// SRD-92 R4 — `collect_status_primary` feeds the key-metric
5169    /// gutter cell's trend: first `status_metrics:` pattern's first
5170    /// candidate, as a raw numeric (latency family in milliseconds).
5171    /// The relevancy-first candidate ordering is exercised end-to-end
5172    /// by `crates/nmbrs/tests/srd92_display.rs` (a live relevancy aggregate
5173    /// needs the full validation pipeline).
5174    #[test]
5175    fn status_primary_selects_first_matching_numeric() {
5176        let m = ActivityMetrics::new(&nmbrs_metrics::labels::Labels::empty());
5177        // No patterns → no primary, regardless of measurements.
5178        assert_eq!(m.collect_status_primary(&[]), None);
5179        // Patterns but nothing measured yet → None (no fabricated 0).
5180        assert_eq!(m.collect_status_primary(&["latency_*".into()]), None);
5181
5182        // 5 ms samples land in the service-time histogram.
5183        for _ in 0..10 {
5184            m.service_time.record(5_000_000);
5185        }
5186        let (name, val) = m
5187            .collect_status_primary(&["latency_p50".into()])
5188            .expect("p50 measurable");
5189        assert_eq!(name, "latency_p50");
5190        assert!((val - 5.0).abs() < 0.5, "p50 ≈ 5 ms, got {val}");
5191
5192        // Glob: first pattern's FIRST candidate wins (p50 precedes
5193        // p99 in candidate order).
5194        let (name, _) = m
5195            .collect_status_primary(&["latency_*".into()])
5196            .expect("glob matches");
5197        assert_eq!(name, "latency_p50");
5198
5199        // Non-matching pattern → None.
5200        assert_eq!(m.collect_status_primary(&["recall*".into()]), None);
5201    }
5202
5203    /// A counting DriverAdapter + OpDispenser for testing.
5204    struct CountingDriverAdapter {
5205        count: Arc<AtomicU64>,
5206    }
5207
5208    impl CountingDriverAdapter {
5209        fn new() -> (Self, Arc<AtomicU64>) {
5210            let count = Arc::new(AtomicU64::new(0));
5211            (
5212                Self {
5213                    count: count.clone(),
5214                },
5215                count,
5216            )
5217        }
5218    }
5219
5220    impl DriverAdapter for CountingDriverAdapter {
5221        fn name(&self) -> &str {
5222            "counting"
5223        }
5224        fn map_op<'a>(
5225            &'a self,
5226            _template: &'a nmbrs_workload::model::ParsedOp,
5227            _parent: std::sync::Arc<dyn polydat::Kernel>,
5228        ) -> std::pin::Pin<
5229            Box<dyn std::future::Future<Output = Result<Box<dyn OpDispenser>, String>> + Send + 'a>,
5230        > {
5231            Box::pin(async move {
5232                Ok(Box::new(CountingDispenser {
5233                    count: self.count.clone(),
5234                }) as Box<dyn OpDispenser>)
5235            })
5236        }
5237    }
5238
5239    struct CountingDispenser {
5240        count: Arc<AtomicU64>,
5241    }
5242
5243    impl OpDispenser for CountingDispenser {
5244        fn execute<'a>(
5245            &'a self,
5246            _cycle: u64,
5247            _ctx: &'a crate::fixture::ExecCtx<'a>,
5248        ) -> std::pin::Pin<
5249            Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
5250        > {
5251            self.count.fetch_add(1, Ordering::Relaxed);
5252            Box::pin(async {
5253                Ok(OpResult {
5254                    body: None,
5255                    skipped: false,
5256                })
5257            })
5258        }
5259    }
5260
5261    /// A fail-then-succeed DriverAdapter for retry testing.
5262    struct FailThenSucceedDriverAdapter {
5263        fails_remaining: Arc<AtomicU64>,
5264        total_calls: Arc<AtomicU64>,
5265    }
5266
5267    impl FailThenSucceedDriverAdapter {
5268        fn new(fail_count: u64) -> (Self, Arc<AtomicU64>) {
5269            let total = Arc::new(AtomicU64::new(0));
5270            (
5271                Self {
5272                    fails_remaining: Arc::new(AtomicU64::new(fail_count)),
5273                    total_calls: total.clone(),
5274                },
5275                total,
5276            )
5277        }
5278    }
5279
5280    impl DriverAdapter for FailThenSucceedDriverAdapter {
5281        fn name(&self) -> &str {
5282            "fail-then-succeed"
5283        }
5284        fn map_op<'a>(
5285            &'a self,
5286            _template: &'a nmbrs_workload::model::ParsedOp,
5287            _parent: std::sync::Arc<dyn polydat::Kernel>,
5288        ) -> std::pin::Pin<
5289            Box<dyn std::future::Future<Output = Result<Box<dyn OpDispenser>, String>> + Send + 'a>,
5290        > {
5291            Box::pin(async move {
5292                Ok(Box::new(FailThenSucceedDispenser {
5293                    fails_remaining: self.fails_remaining.clone(),
5294                    total_calls: self.total_calls.clone(),
5295                }) as Box<dyn OpDispenser>)
5296            })
5297        }
5298    }
5299
5300    struct FailThenSucceedDispenser {
5301        fails_remaining: Arc<AtomicU64>,
5302        total_calls: Arc<AtomicU64>,
5303    }
5304
5305    impl OpDispenser for FailThenSucceedDispenser {
5306        fn execute<'a>(
5307            &'a self,
5308            _cycle: u64,
5309            _ctx: &'a crate::fixture::ExecCtx<'a>,
5310        ) -> std::pin::Pin<
5311            Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
5312        > {
5313            self.total_calls.fetch_add(1, Ordering::Relaxed);
5314            let remaining = self.fails_remaining.fetch_sub(1, Ordering::Relaxed);
5315            Box::pin(async move {
5316                if remaining > 0 {
5317                    Err(ExecutionError::Op(AdapterError {
5318                        error_name: "TransientError".into(),
5319                        message: "temporary failure".into(),
5320                        retryable: true,
5321                    }))
5322                } else {
5323                    Ok(OpResult {
5324                        body: None,
5325                        skipped: false,
5326                    })
5327                }
5328            })
5329        }
5330    }
5331
5332    /// Build a minimal Polydat root kernel (single identity node) for tests.
5333    fn test_kernel() -> crate::scope_kernel::ScopeKernel {
5334        use polydat::compile::assembly::{PolydatAssembler, WireRef};
5335        use polydat::library::identity::Identity;
5336        let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
5337        asm.add_node(
5338            "id",
5339            Box::new(Identity::new(polydat::ast::PortType::U64)),
5340            vec![WireRef::input("cycle")],
5341        );
5342        asm.add_output("id", WireRef::node("id"));
5343        asm.compile().unwrap().into()
5344    }
5345
5346    #[tokio::test]
5347    async fn activity_runs_all_cycles() {
5348        let config = ActivityConfig {
5349            name: "test".into(),
5350            cycles: 100,
5351            concurrency: 4,
5352            ..Default::default()
5353        };
5354        let ops = vec![nmbrs_workload::model::ParsedOp::simple("op1", "test")];
5355        let seq = OpSequence::uniform(ops);
5356        let activity = Activity::new(config, &Labels::of("session", "test"), seq);
5357
5358        let (adapter, count) = CountingDriverAdapter::new();
5359        activity
5360            .run_with_driver(
5361                Arc::new(adapter),
5362                Arc::new(crate::synthesis::OpBuilder::new(test_kernel())),
5363            )
5364            .await;
5365
5366        assert_eq!(count.load(Ordering::Relaxed), 100);
5367    }
5368
5369    #[tokio::test]
5370    async fn activity_retries_on_error() {
5371        // Retry backoff keeps this test's op IN FLIGHT for a few
5372        // hundred ms — long enough to overlap the session_signals
5373        // tests, whose bodies legitimately hold the process-global
5374        // cancel rung in force (the raced in-flight cancel would
5375        // kill attempt 3). Serialize with them, same discipline as
5376        // every global-flag test.
5377        let _signals = crate::session_signals::STOP_GLOBAL_TEST_LOCK.lock().await;
5378        let config = ActivityConfig {
5379            name: "retrytest".into(),
5380            cycles: 1,
5381            concurrency: 1,
5382            error_spec: "TransientError:retry,warn;.*:stop".into(),
5383            // Total-attempts budget (the `tries` sigil): 6 total ≈ the old
5384            // `retries: 5` additional-attempts budget.
5385            tries: Some(6),
5386            ..Default::default()
5387        };
5388        let ops = vec![nmbrs_workload::model::ParsedOp::simple("op1", "test")];
5389        let seq = OpSequence::uniform(ops);
5390        let activity = Activity::new(config, &Labels::of("session", "s1"), seq);
5391
5392        let (adapter, total_calls) = FailThenSucceedDriverAdapter::new(2);
5393        activity
5394            .run_with_driver(
5395                Arc::new(adapter),
5396                Arc::new(crate::synthesis::OpBuilder::new(test_kernel())),
5397            )
5398            .await;
5399
5400        assert_eq!(total_calls.load(Ordering::Relaxed), 3);
5401    }
5402
5403    #[tokio::test]
5404    async fn daemon_op_dispatches_at_cycle_pool_position() {
5405        // SRD-79 (in-flight): daemon-flagged op spawns onto the
5406        // daemon pool when the cycle-pool fiber's stanza walk
5407        // reaches it. The daemon fiber runs the same dispenser
5408        // as a non-daemon op would, but on its own tokio task,
5409        // and the cycle-pool fiber doesn't await it.
5410        let config = ActivityConfig {
5411            name: "daemon-disp-test".into(),
5412            cycles: 1,
5413            concurrency: 1,
5414            ..Default::default()
5415        };
5416        let mut op = nmbrs_workload::model::ParsedOp::simple("dmn", "test");
5417        op.daemon = nmbrs_workload::model::DaemonSpec::MaxFibers(1);
5418        let seq = OpSequence::uniform(vec![op]);
5419        let activity = Activity::new(config, &Labels::of("session", "s1"), seq);
5420
5421        let (adapter, count) = CountingDriverAdapter::new();
5422        activity
5423            .run_with_driver(
5424                Arc::new(adapter),
5425                Arc::new(crate::synthesis::OpBuilder::new(test_kernel())),
5426            )
5427            .await;
5428
5429        // Daemon dispatched + ran exactly once (cycles=1).
5430        assert_eq!(
5431            count.load(Ordering::Relaxed),
5432            1,
5433            "daemon op should have run via dispatch-time spawn"
5434        );
5435    }
5436
5437    #[tokio::test]
5438    async fn daemon_op_cap_exceeded_fails_phase() {
5439        // Cap=1 with cycles=2: first dispatch succeeds and the
5440        // daemon fiber blocks (the CountingDispenser returns
5441        // instantly, so the daemon should drain before the
5442        // second cycle — but the daemon-pool counter only
5443        // decrements when the body returns, and the second
5444        // cycle may race with the decrement). This test
5445        // primarily checks the no-panic / clean-failure path:
5446        // even if the cap fires, the activity exits cleanly.
5447        let config = ActivityConfig {
5448            name: "daemon-cap-test".into(),
5449            cycles: 50,
5450            concurrency: 1,
5451            ..Default::default()
5452        };
5453        let mut op = nmbrs_workload::model::ParsedOp::simple("dmn", "test");
5454        op.daemon = nmbrs_workload::model::DaemonSpec::MaxFibers(1);
5455        let seq = OpSequence::uniform(vec![op]);
5456        let activity = Activity::new(config, &Labels::of("session", "s2"), seq);
5457
5458        let (adapter, _count) = CountingDriverAdapter::new();
5459        activity
5460            .run_with_driver(
5461                Arc::new(adapter),
5462                Arc::new(crate::synthesis::OpBuilder::new(test_kernel())),
5463            )
5464            .await;
5465        // No assertion on count — the load-bearing behaviour is
5466        // that the activity terminates cleanly even when caps
5467        // bite. Without the cap, this test would hang or panic.
5468    }
5469
5470    #[tokio::test]
5471    async fn shared_metrics_accessible() {
5472        let config = ActivityConfig {
5473            name: "metricstest".into(),
5474            cycles: 50,
5475            concurrency: 2,
5476            ..Default::default()
5477        };
5478        let ops = vec![nmbrs_workload::model::ParsedOp::simple("op1", "test")];
5479        let seq = OpSequence::uniform(ops);
5480        let activity = Activity::new(config, &Labels::of("session", "s1"), seq);
5481
5482        let shared_metrics = activity.shared_metrics();
5483
5484        let (adapter, _count) = CountingDriverAdapter::new();
5485        activity
5486            .run_with_driver(
5487                Arc::new(adapter),
5488                Arc::new(crate::synthesis::OpBuilder::new(test_kernel())),
5489            )
5490            .await;
5491
5492        assert_eq!(shared_metrics.cycles_total.get(), 50);
5493        let frame = shared_metrics.capture(std::time::Duration::from_secs(1));
5494        assert!(!frame.is_empty());
5495    }
5496
5497    #[tokio::test]
5498    async fn per_error_type_counters_emit_deltas_through_dynamic_capture() {
5499        // SRD-40 / cascade coalesce: `MetricSet::combine_into` for
5500        // Counter sums `total` across intervals — so per-cycle
5501        // emissions must be DELTAS, not absolutes. Per-error-type
5502        // counters live on `ActivityMetricsDynamic` (outside the
5503        // static registry), so they need their own delta tracking.
5504        // This test exercises that path directly.
5505        use nmbrs_metrics::component::Component;
5506        use nmbrs_metrics::snapshot::MetricValue;
5507
5508        let metrics = Arc::new(ActivityMetrics::new(&Labels::of("session", "s1")));
5509        let component = Arc::new(std::sync::RwLock::new(Component::new(
5510            Labels::of("activity", "t"),
5511            HashMap::new(),
5512        )));
5513        {
5514            let mut g = component.write().unwrap();
5515            g.set_state(nmbrs_metrics::component::ComponentState::Running);
5516            metrics.register_on(&mut g).unwrap();
5517        }
5518
5519        // Seed two error-type counters with different totals.
5520        for _ in 0..3 {
5521            metrics.count_error_type("net");
5522        }
5523        for _ in 0..7 {
5524            metrics.count_error_type("timeout");
5525        }
5526
5527        // First capture_delta — totals=3 and 7 are the deltas.
5528        let snap1 = component
5529            .read()
5530            .unwrap()
5531            .capture_delta(std::time::Duration::from_secs(1));
5532        let net1 = read_counter(&snap1, "errors.net");
5533        let to1 = read_counter(&snap1, "errors.timeout");
5534        assert_eq!(net1, 3, "first delta for net should be 3, got {net1}");
5535        assert_eq!(to1, 7, "first delta for timeout should be 7, got {to1}");
5536
5537        // Drive the per-error-type counters further.
5538        for _ in 0..2 {
5539            metrics.count_error_type("net");
5540        }
5541        for _ in 0..1 {
5542            metrics.count_error_type("timeout");
5543        }
5544
5545        // Second capture_delta — should report only the new deltas
5546        // (2 and 1), NOT the absolute totals (5 and 8).
5547        let snap2 = component
5548            .read()
5549            .unwrap()
5550            .capture_delta(std::time::Duration::from_secs(1));
5551        let net2 = read_counter(&snap2, "errors.net");
5552        let to2 = read_counter(&snap2, "errors.timeout");
5553        assert_eq!(
5554            net2, 2,
5555            "second delta for net should be 2 (new only), got {net2}"
5556        );
5557        assert_eq!(
5558            to2, 1,
5559            "second delta for timeout should be 1 (new only), got {to2}"
5560        );
5561
5562        // capture_current (drain=false) should still report absolutes.
5563        let cur = component.read().unwrap().capture_current();
5564        let net_abs = read_counter(&cur, "errors.net");
5565        let to_abs = read_counter(&cur, "errors.timeout");
5566        assert_eq!(
5567            net_abs, 5,
5568            "current should be absolute total 5, got {net_abs}"
5569        );
5570        assert_eq!(
5571            to_abs, 8,
5572            "current should be absolute total 8, got {to_abs}"
5573        );
5574
5575        fn read_counter(snap: &nmbrs_metrics::snapshot::MetricSet, family: &str) -> u64 {
5576            let f = snap
5577                .family(family)
5578                .unwrap_or_else(|| panic!("family {family:?} missing from snapshot"));
5579            let m = f.metrics().next().expect("at least one metric");
5580            match m.point().unwrap().value() {
5581                MetricValue::Counter(c) => c.cumulative,
5582                v => panic!("not a counter: {v:?}"),
5583            }
5584        }
5585    }
5586
5587    #[tokio::test]
5588    async fn activity_with_rate() {
5589        let config = ActivityConfig {
5590            name: "ratetest".into(),
5591            cycles: 10,
5592            concurrency: 2,
5593            rate: Some(10000.0),
5594            ..Default::default()
5595        };
5596        let ops = vec![nmbrs_workload::model::ParsedOp::simple("op1", "test")];
5597        let seq = OpSequence::uniform(ops);
5598        let activity = Activity::new(config, &Labels::of("session", "s1"), seq);
5599
5600        let (adapter, count) = CountingDriverAdapter::new();
5601        activity
5602            .run_with_driver(
5603                Arc::new(adapter),
5604                Arc::new(crate::synthesis::OpBuilder::new(test_kernel())),
5605            )
5606            .await;
5607
5608        assert_eq!(count.load(Ordering::Relaxed), 10);
5609    }
5610
5611    #[tokio::test]
5612    async fn activity_with_weighted_ops() {
5613        let config = ActivityConfig {
5614            name: "weighted".into(),
5615            cycles: 12,
5616            concurrency: 1,
5617            ..Default::default()
5618        };
5619        let ops = vec![
5620            nmbrs_workload::model::ParsedOp::simple("read", "SELECT"),
5621            nmbrs_workload::model::ParsedOp::simple("write", "INSERT"),
5622        ];
5623        let seq = OpSequence::build(ops, &[4, 2], SequencerType::Bucket);
5624        let activity = Activity::new(config, &Labels::of("session", "s1"), seq);
5625
5626        let (adapter, count) = CountingDriverAdapter::new();
5627        activity
5628            .run_with_driver(
5629                Arc::new(adapter),
5630                Arc::new(crate::synthesis::OpBuilder::new(test_kernel())),
5631            )
5632            .await;
5633
5634        assert_eq!(count.load(Ordering::Relaxed), 12);
5635    }
5636
5637    #[tokio::test]
5638    async fn rate_control_is_declared_when_rate_configured() {
5639        use nmbrs_metrics::component::Component;
5640        use nmbrs_metrics::labels::Labels as L;
5641        use std::sync::RwLock;
5642
5643        let config = ActivityConfig {
5644            name: "rate_decl".into(),
5645            cycles: 5,
5646            concurrency: 1,
5647            rate: Some(2500.0),
5648            ..Default::default()
5649        };
5650        let ops = vec![nmbrs_workload::model::ParsedOp::simple("op1", "test")];
5651        let seq = OpSequence::uniform(ops);
5652        let mut activity = Activity::new(config, &L::of("session", "s_rate"), seq);
5653        let component = Arc::new(RwLock::new(Component::new(
5654            L::of("session", "s_rate"),
5655            std::collections::HashMap::new(),
5656        )));
5657        activity.attach_component(component.clone());
5658
5659        let (adapter, _count) = CountingDriverAdapter::new();
5660        activity
5661            .run_with_driver(
5662                Arc::new(adapter),
5663                Arc::new(crate::synthesis::OpBuilder::new(test_kernel())),
5664            )
5665            .await;
5666
5667        // After the activity runs, the rate control is on the
5668        // component and reports the configured target via its
5669        // reified gauge.
5670        let guard = component.read().unwrap();
5671        let erased = guard
5672            .controls()
5673            .get_erased("rate")
5674            .expect("rate control should be declared when rate is set");
5675        assert!(erased.accepts_f64_writes());
5676        assert_eq!(erased.gauge_f64(), Some(2500.0));
5677    }
5678
5679    #[tokio::test]
5680    async fn rate_control_is_absent_when_no_rate() {
5681        use nmbrs_metrics::component::Component;
5682        use nmbrs_metrics::labels::Labels as L;
5683        use std::sync::RwLock;
5684
5685        let config = ActivityConfig {
5686            name: "no_rate".into(),
5687            cycles: 3,
5688            concurrency: 1,
5689            rate: None,
5690            ..Default::default()
5691        };
5692        let ops = vec![nmbrs_workload::model::ParsedOp::simple("op1", "test")];
5693        let seq = OpSequence::uniform(ops);
5694        let mut activity = Activity::new(config, &L::of("session", "s_nr"), seq);
5695        let component = Arc::new(RwLock::new(Component::new(
5696            L::of("session", "s_nr"),
5697            std::collections::HashMap::new(),
5698        )));
5699        activity.attach_component(component.clone());
5700
5701        let (adapter, _count) = CountingDriverAdapter::new();
5702        activity
5703            .run_with_driver(
5704                Arc::new(adapter),
5705                Arc::new(crate::synthesis::OpBuilder::new(test_kernel())),
5706            )
5707            .await;
5708
5709        let guard = component.read().unwrap();
5710        assert!(
5711            guard.controls().get_erased("rate").is_none(),
5712            "no rate control should exist without rate configured",
5713        );
5714    }
5715
5716    #[tokio::test]
5717    async fn rate_control_write_retargets_the_running_limiter() {
5718        use nmbrs_metrics::component::Component;
5719        use nmbrs_metrics::controls::ControlOrigin;
5720        use nmbrs_metrics::labels::Labels as L;
5721        use std::sync::RwLock;
5722
5723        // 200 cycles with a low rate + a concurrent writer that
5724        // bumps the rate mid-flight. The committed value on the
5725        // control reflects the write; the limiter carries the
5726        // same target after reconfigure.
5727        let config = ActivityConfig {
5728            name: "rate_live".into(),
5729            cycles: 200,
5730            concurrency: 2,
5731            rate: Some(50.0),
5732            ..Default::default()
5733        };
5734        let ops = vec![nmbrs_workload::model::ParsedOp::simple("op1", "test")];
5735        let seq = OpSequence::uniform(ops);
5736        let mut activity = Activity::new(config, &L::of("session", "s_live"), seq);
5737        let component = Arc::new(RwLock::new(Component::new(
5738            L::of("session", "s_live"),
5739            std::collections::HashMap::new(),
5740        )));
5741        activity.attach_component(component.clone());
5742
5743        // Spawn the activity, wait for the applier to be wired,
5744        // issue a typed write, assert the control value advanced.
5745        let component_for_writer = component.clone();
5746        let writer = tokio::spawn(async move {
5747            for _ in 0..50 {
5748                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
5749                let ctl: Option<nmbrs_metrics::controls::Control<nmbrs_rate::RateSpec>> =
5750                    component_for_writer.read().unwrap().controls().get("rate");
5751                if let Some(c) = ctl {
5752                    // Only attempt once the applier is registered.
5753                    if c.applier_count() > 0 {
5754                        c.set(nmbrs_rate::RateSpec::new(10_000.0), ControlOrigin::Test)
5755                            .await
5756                            .ok();
5757                        return;
5758                    }
5759                }
5760            }
5761        });
5762
5763        let (adapter, _count) = CountingDriverAdapter::new();
5764        activity
5765            .run_with_driver(
5766                Arc::new(adapter),
5767                Arc::new(crate::synthesis::OpBuilder::new(test_kernel())),
5768            )
5769            .await;
5770        let _ = writer.await;
5771
5772        let guard = component.read().unwrap();
5773        let ctl: nmbrs_metrics::controls::Control<nmbrs_rate::RateSpec> =
5774            guard.controls().get("rate").unwrap();
5775        assert_eq!(ctl.value().ops_per_sec, 10_000.0);
5776    }
5777
5778    #[tokio::test]
5779    async fn concurrency_control_is_declared_on_attached_component() {
5780        // SRD 23 integration: the activity declares its
5781        // `concurrency` control on the attached component during
5782        // startup; the control's reified gauge reads the
5783        // configured value.
5784        use nmbrs_metrics::component::Component;
5785        use nmbrs_metrics::labels::Labels as L;
5786        use std::sync::RwLock;
5787
5788        let config = ActivityConfig {
5789            name: "ctrl_decl".into(),
5790            cycles: 10,
5791            concurrency: 3,
5792            ..Default::default()
5793        };
5794        let ops = vec![nmbrs_workload::model::ParsedOp::simple("op1", "test")];
5795        let seq = OpSequence::uniform(ops);
5796        let mut activity = Activity::new(config, &L::of("session", "s_decl"), seq);
5797        let component = Arc::new(RwLock::new(Component::new(
5798            L::of("session", "s_decl"),
5799            std::collections::HashMap::new(),
5800        )));
5801        activity.attach_component(component.clone());
5802
5803        let (adapter, _count) = CountingDriverAdapter::new();
5804        activity
5805            .run_with_driver(
5806                Arc::new(adapter),
5807                Arc::new(crate::synthesis::OpBuilder::new(test_kernel())),
5808            )
5809            .await;
5810
5811        // After run completes the control is still on the
5812        // component (structural declaration survives execution).
5813        let guard = component.read().unwrap();
5814        let erased = guard
5815            .controls()
5816            .get_erased("concurrency")
5817            .expect("concurrency control should be declared on attached component");
5818        assert_eq!(erased.value_string(), "3");
5819        assert!(erased.accepts_f64_writes());
5820        // Gauge projection reads as f64.
5821        assert_eq!(erased.gauge_f64(), Some(3.0));
5822    }
5823}