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