Skip to main content

nmbrs_runtime/
activity.rs

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