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