Skip to main content

nmbrs_runtime/polydat_nodes/
runtime_context.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Runtime context nodes (SRD 12 §"Runtime context nodes").
5//!
6//! These nodes project stable runtime surfaces — the current
7//! phase, the current cycle ordinal, the value of a dynamic
8//! control, the active rate-limiter target, the active fiber
9//! count — into GK-readable wires. They are the read-side of
10//! the reification principle (SRD 10 §"GK as the unified access
11//! surface"): any value a workload might want to read is reached
12//! through a Polydat binding, not a side channel.
13//!
14//! Like the metric nodes (see `metrics.rs`), these are
15//! non-deterministic context projections — their output changes
16//! between cycles by definition, so the constant-folder is not
17//! allowed to collapse them. They read from globals / thread
18//! locals the runtime sets during bootstrap and on every cycle
19//! tick.
20
21use std::future::Future;
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::sync::{Arc, LazyLock, Mutex, RwLock};
24
25// All nodes here are authored via `#[polydat::polydat_node]` (fully-qualified
26// `polydat::…` paths), so no `polydat::ast` imports are needed in module
27// code (the in-module tests import what they need locally).
28
29use nmbrs_metrics::component::Component;
30
31// =========================================================================
32// Global session-root handle + per-fiber task-local context
33// =========================================================================
34
35/// Global handle to the session's component root. Set by the
36/// runner during scenario bootstrap so context nodes can resolve
37/// `control(...)` reads against the live tree.
38static SESSION_ROOT: LazyLock<Mutex<Option<Arc<RwLock<Component>>>>> =
39    LazyLock::new(|| Mutex::new(None));
40
41/// Install the session root for every runtime-context node that
42/// reads tree state. Call once at scenario bootstrap; subsequent
43/// calls overwrite.
44/// Test-only serialization for the process-global session root.
45///
46/// `SESSION_ROOT` is one global; the parallel test runner is many threads.
47/// Every test that INSTALLS a root — directly, or by constructing a
48/// [`crate::session::Session`], whose constructor installs one as a side
49/// effect — must hold this guard, and so must every test that READS controls
50/// through the root. It lives here, beside the global it protects, precisely
51/// because the offender that motivated it was in another module: a
52/// session-construction test stomping the control tests' root through the
53/// constructor side effect, which a module-private test lock could never
54/// exclude.
55#[cfg(test)]
56pub(crate) fn session_root_test_guard() -> std::sync::MutexGuard<'static, ()> {
57    static TEST_LOCK: Mutex<()> = Mutex::new(());
58    TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner())
59}
60
61pub fn set_session_root(root: Arc<RwLock<Component>>) {
62    *SESSION_ROOT.lock().unwrap_or_else(|e| e.into_inner()) = Some(root);
63}
64
65fn session_root() -> Option<Arc<RwLock<Component>>> {
66    SESSION_ROOT
67        .lock()
68        .unwrap_or_else(|e| e.into_inner())
69        .clone()
70}
71
72/// Public accessor for the runner-installed session root.
73///
74/// Used by integration layers that need to walk the component
75/// tree from outside this crate — the TUI's control-edit
76/// handler, the web API's control endpoints, the
77/// `dryrun=controls` renderer, etc. Returns `None` when no
78/// session is running (pre-bootstrap, after teardown, tests
79/// that never called [`set_session_root`]).
80pub fn session_root_handle() -> Option<Arc<RwLock<Component>>> {
81    session_root()
82}
83
84/// Per-fiber execution context carried across the async call
85/// chain via a [`tokio::task_local!`] binding. Thread-locals are
86/// unsafe here because tokio's work-stealing scheduler can
87/// migrate a task between worker threads at any `.await`; a
88/// task-local is bound to the task itself and survives
89/// migration.
90pub struct FiberContext {
91    /// Name of the phase this fiber is running under. Arc'd so
92    /// two fibers under the same phase share one allocation.
93    pub phase: Arc<str>,
94    /// Current cycle ordinal. `AtomicU64` rather than `Cell` so
95    /// the context is `Sync` — tokio requires task-local values
96    /// to be `Send + Sync`.
97    pub cycle: AtomicU64,
98    /// SRD-89 — the **current component's** control resolution, for this
99    /// fiber's execution: control name → live erased handle, walked up **once**
100    /// from the fiber's own phase component
101    /// ([`nmbrs_metrics::component::Component::control_snapshot`], first-match /
102    /// nearest-wins) and read lock-free thereafter. It holds live handles, not
103    /// values, so a servo retarget on the shared control is observed through it.
104    /// Because each execution's fibers carry **their own** phase component's
105    /// snapshot, a same-named control (`concurrency` / `rate`) resolves to that
106    /// execution's instance — uniformly in single-run and concurrent runs, with
107    /// no session-root walk and no cross-talk. Empty for fibers spawned without
108    /// a component (a control read then falls back to the session-root walk).
109    pub controls: ControlMap,
110}
111
112/// A lock-free, shareable snapshot of resolved control handles (see
113/// [`FiberContext::controls`]).
114pub type ControlMap =
115    Arc<std::collections::HashMap<String, Arc<dyn nmbrs_metrics::controls::ErasedControl>>>;
116
117/// Snapshot the controls visible from `component` (its own controls plus any
118/// `Subtree`-scoped ancestor control, nearest-wins) into a lock-free
119/// [`ControlMap`]. Deadlock-safe: [`Component::control_snapshot`] acquires one
120/// tier's lock at a time, never nested — so it is safe on the cadence-contended
121/// component tree. Computed once per phase, shared across the phase's fibers.
122pub fn snapshot_controls(component: &Arc<RwLock<Component>>) -> ControlMap {
123    Arc::new(nmbrs_metrics::component::Component::control_snapshot(
124        component,
125    ))
126}
127
128/// An empty [`ControlMap`] for fibers / call sites that have no component (the
129/// read then falls back to the session-root walk).
130pub fn empty_controls() -> ControlMap {
131    Arc::new(std::collections::HashMap::new())
132}
133
134tokio::task_local! {
135    /// Task-local fiber context. Set once per fiber at spawn
136    /// time via [`with_fiber_context`]; updated per cycle via
137    /// [`set_task_cycle`]. Reads outside a scope (e.g. unit
138    /// tests, non-fiber code paths) silently return defaults.
139    static FIBER_CTX: FiberContext;
140}
141
142/// Wrap a fiber's async body in a `FiberContext` scope. Every
143/// runtime-context node read performed inside the future sees
144/// the phase name and cycle counter set here.
145///
146/// Cycle starts at 0 and is updated via [`set_task_cycle`] on
147/// every iteration of the fiber's loop.
148pub async fn with_fiber_context<F>(phase: Arc<str>, controls: ControlMap, fut: F) -> F::Output
149where
150    F: Future,
151{
152    FIBER_CTX
153        .scope(
154            FiberContext {
155                phase,
156                cycle: AtomicU64::new(0),
157                controls,
158            },
159            fut,
160        )
161        .await
162}
163
164/// Resolve a control from the running fiber's **current component** snapshot
165/// (lock-free). `None` outside a fiber scope, or when the snapshot doesn't carry
166/// `name` — the caller then falls back to the session-root walk.
167fn current_phase_control(name: &str) -> Option<Arc<dyn nmbrs_metrics::controls::ErasedControl>> {
168    FIBER_CTX
169        .try_with(|ctx| ctx.controls.get(name).cloned())
170        .ok()
171        .flatten()
172}
173
174/// Update the cycle counter in the enclosing [`FiberContext`].
175/// Safe to call outside a scope — the update is a no-op if
176/// there is no active fiber context (e.g. when the node is
177/// evaluated from a unit test that didn't install one).
178pub fn set_task_cycle(cycle: u64) {
179    let _ = FIBER_CTX.try_with(|ctx| ctx.cycle.store(cycle, Ordering::Relaxed));
180}
181
182fn task_phase() -> Option<Arc<str>> {
183    FIBER_CTX.try_with(|ctx| ctx.phase.clone()).ok()
184}
185
186fn task_cycle() -> u64 {
187    FIBER_CTX
188        .try_with(|ctx| ctx.cycle.load(Ordering::Relaxed))
189        .unwrap_or(0)
190}
191
192// =========================================================================
193// control_set(name, value) — GK-driven write into a control
194// =========================================================================
195
196/// Capture the enclosing DSL binding name at node construction, for write
197/// attribution (`ControlOrigin::Polydat { binding }` — surfaces in control
198/// logs so operators attribute a change to a specific binding, not just
199/// "from GK"). The build context names the binding the node is built for;
200/// falls back to the control name when it names none (a node built outside
201/// a binding, e.g. a library test).
202fn capture_binding(ctx: &polydat::dsl::factory::BuildContext, name: &str) -> String {
203    ctx.binding()
204        .map(str::to_string)
205        .unwrap_or_else(|| name.to_string())
206}
207
208/// Polydat write node: submit an f64 write against the named control via the
209/// session root's walk-up. Returns `1` if dispatched, `0` if not — either no
210/// session root is installed (outside a running scenario / pure-kernel test)
211/// or the control already reads exactly the requested value (idempotent
212/// writes are elided; see the fixpoint check in the body).
213///
214/// Signature: `control_set(name: const str, value: f64) -> u64`. Authored
215/// via `#[polydat::polydat_node]` (SRD-80b).
216///
217/// Writes are **non-blocking** — the node spawns a tokio task that calls
218/// [`nmbrs_metrics::controls::ErasedControl::set_f64`] and does not await it
219/// (awaiting would deadlock the single-threaded runtime). The control
220/// layer's confirmed-apply still runs in the background; failures log but do
221/// not stall the issuing fiber. SRD 23 §"Mutation entry points →
222/// GK-driven feedback loops".
223///
224/// Purity is `SideChannel(Other)`: the write is an observable side effect on
225/// runtime control state, so the node is never const-folded or deduped — it
226/// dispatches on every evaluation.
227#[polydat::polydat_node(
228    category = Context,
229    purity = SideChannel(Other),
230)]
231fn control_set(
232    name: Const<&str>,
233    #[poly_const(capture_binding, from = (ctx, name))] binding: &String,
234    value: f64,
235) -> u64 {
236    // SRD-89 — a workload's `control_set(...)` must write to ITS OWN phase-tier
237    // control (`concurrency` / `rate`), not a neighbour's. Resolve through the
238    // SAME path as the read nodes ([`resolve_control`]: the running fiber's
239    // current-component snapshot, else the session-root walk-up) so the write
240    // targets exactly the control a subsequent read sees. Resolution happens
241    // HERE, inside the fiber's `FIBER_CTX` scope — the background write task
242    // below does NOT inherit `FIBER_CTX`, so it cannot re-resolve; we capture
243    // the live handle and hand it over. If nothing resolves (pre-bootstrap /
244    // pure-kernel test) report "not dispatched" (the no-root → 0 contract)
245    // without spawning.
246    let Some(erased) = resolve_control(name.0) else {
247        return 0;
248    };
249    // Idempotent-write elision (SRD-93-era servo support): a feedback
250    // binding that re-evaluates per cycle recomputes the SAME target
251    // between changes of its inputs, and re-dispatching that write
252    // buys nothing while costing a spawn + the confirmed-apply
253    // pipeline every cycle. The committed gauge projection is the
254    // fixpoint check: when the control already reads exactly the
255    // requested value, the write is elided and the node reports 0
256    // (not dispatched — same code as the no-root case). Exact
257    // equality on purpose: between input changes the recomputation is
258    // bit-identical, and any real change, however small, must
259    // dispatch. Controls without a reified gauge (`gauge_f64() ==
260    // None`) never match and keep the always-dispatch behavior. An
261    // in-flight uncommitted write can let one duplicate through —
262    // harmless, it commits the same value.
263    if erased.gauge_f64() == Some(value) {
264        return 0;
265    }
266    let name = name.0.to_string();
267    let binding = binding.clone();
268
269    // Dispatch the write on a background task — the fiber cannot await an
270    // async `set` without blocking the runtime. The handle is already resolved,
271    // so the task needs no execution context.
272    tokio::spawn(async move {
273        let origin = nmbrs_metrics::controls::ControlOrigin::Polydat { binding };
274        if let Err(e) = erased.set_f64(value, origin).await {
275            polydat::audit::warn(&format!("control_set({name}, {value}) failed: {e}"));
276        }
277    });
278
279    1
280}
281
282// =========================================================================
283// control(name) — read a dynamic control's gauge-projection
284// =========================================================================
285
286/// Resolve a control's erased handle for a cycle-time read or write (SRD-89).
287///
288/// **The running fiber's phase first, lock-free:** consults the current
289/// component's control snapshot ([`current_phase_control`]) — no component
290/// lock, no tree walk. Under concurrent in-process executions (SRD-88) this is
291/// what makes a same-named control (`concurrency` / `rate`) resolve to THIS
292/// execution's own instance, so a neighbour's servo can't drive this phase
293/// (the SRD-89 §2b cross-talk).
294///
295/// **Fallback — the session-root walk:** with no fiber scope (a control edit
296/// from outside a running phase: the TUI `e` prompt, the web control endpoint,
297/// `dryrun=controls`), or for a session-tier control the snapshot doesn't
298/// carry, resolve by walking up from the installed session root via
299/// [`Component::find_control_erased_up`]. The walk holds a single, non-nested
300/// read guard on the session root (which has no parent), released before the
301/// caller projects the value.
302fn resolve_control(name: &str) -> Option<Arc<dyn nmbrs_metrics::controls::ErasedControl>> {
303    // Resolve from the running fiber's **current component** — its phase-tier
304    // control snapshot (walk-up from its own phase component, first match), read
305    // lock-free. Uniform for single-run and concurrent: each execution's fibers
306    // carry their own snapshot, so a same-named control resolves to that
307    // execution's instance. No session-root start.
308    if let Some(handle) = current_phase_control(name) {
309        return Some(handle);
310    }
311    // Fallback: no fiber scope (a control edit from OUTSIDE a running phase —
312    // the TUI `e` prompt, the web control endpoint, `dryrun=controls`). Walk up
313    // from the session root for session-tier controls.
314    let root = session_root()?;
315    let guard = root.read().ok()?;
316    guard.find_control_erased_up(name)
317}
318
319/// Read a dynamic control's current reified-gauge value as `f64`. `0.0` when
320/// the control can't be resolved (no session / per-exec context, absent) or has
321/// no reified gauge. The single read path for every control-reader node
322/// (`control` / `control_u64` / `control_bool` / `rate` / `concurrency`).
323fn control_gauge_f64(name: &str) -> f64 {
324    resolve_control(name)
325        .and_then(|c| c.gauge_f64())
326        .unwrap_or(0.0)
327}
328
329/// Read a dynamic control's current value as its human-readable string
330/// rendering (the erased-control `value_string()`), or `""` when absent.
331fn control_value_string(name: &str) -> String {
332    resolve_control(name)
333        .map(|c| c.value_string())
334        .unwrap_or_default()
335}
336
337/// Read a dynamic control's current value as `f64`, projected through the
338/// control's reified gauge and resolved as `resolve_control` describes.
339/// `0.0` in every case where no numeric value is available:
340///
341/// - the name doesn't resolve to any declared control;
342/// - the control was built without
343///   [`nmbrs_metrics::controls::ControlBuilder::reify_as_gauge`], so it has
344///   no f64 projection;
345/// - the projection returned `None` for the current value (an enum-valued
346///   control on a variant with no numeric form).
347///
348/// This is deliberately not an error: a workload at cycle time cannot
349/// usefully handle a missing control, and a panic or a `NaN` sentinel
350/// poisons everything downstream. `control_str` and `control_bool` read
351/// non-numeric controls with explicit defaults for the same cases, and
352/// operators verify controls exist with `dryrun=controls` before running.
353///
354/// Signature: `control(name: const str) -> f64`. Intrinsically
355/// `Nondeterministic`: the control value changes over the run (operator
356/// edits, SRD-86 servo retargets, per-coordinate reruns), so the node is
357/// never const-folded, re-evaluated on every pull, and the compiler
358/// propagates that volatility to every downstream wire — `load :=
359/// control("concurrency")` (and anything reading `load`) tracks the live
360/// value without the author flagging `volatile`.
361#[polydat::polydat_node(
362    category = Context,
363    purity = Nondeterministic("reads a live dynamic control value; changes over the run"),
364)]
365fn control(name: Const<&str>) -> f64 {
366    control_gauge_f64(name.0)
367}
368
369// =========================================================================
370// control_u64(name) / control_str(name) — typed read sugar
371// =========================================================================
372
373/// Read a dynamic control's current value and cast to `u64`.
374///
375/// Signature: `control_u64(name: const str) -> u64`. Resolves the control by
376/// walk-up from the session root, reads its reified-gauge f64 projection and
377/// casts to u64 (saturating at 0 for negatives). Missing / gauge-less
378/// controls return 0. For integer-valued controls (`concurrency`,
379/// `max_retries`) read as a cycle-time parameter — no need to pipe
380/// `control("…")` through `f64_to_u64`.
381///
382/// Authored via `#[polydat::polydat_node]` (SRD-80b) — purity is the
383/// hygienic attribute below. `Nondeterministic` because the control value
384/// changes over the run (operator edits, SRD-86 servo retargets,
385/// per-coordinate reruns): the node is never const-folded, re-evaluated on
386/// every pull, and the compiler propagates that volatility to every
387/// downstream wire, so `load := control_u64("concurrency")` tracks the live
388/// value without the author flagging `volatile`.
389#[polydat::polydat_node(
390    category = Context,
391    purity = Nondeterministic("reads a live dynamic control value; changes over the run"),
392)]
393fn control_u64(name: Const<&str>) -> u64 {
394    let v = control_gauge_f64(name.0);
395    if v < 0.0 { 0 } else { v as u64 }
396}
397
398/// Read a dynamic control's current value as a boolean — `true` iff its
399/// reified-gauge value is non-zero. Missing / unreified controls → `false`.
400///
401/// Signature: `control_bool(name: const str) -> bool`. Intrinsically
402/// `Nondeterministic` (live control read) — see `control_u64`.
403#[polydat::polydat_node(
404    category = Context,
405    purity = Nondeterministic("reads a live dynamic control value; changes over the run"),
406)]
407fn control_bool(name: Const<&str>) -> bool {
408    control_gauge_f64(name.0) != 0.0
409}
410
411/// Read a dynamic control's current value as its human-readable string
412/// (the erased-control `value_string()` rendering). Missing controls → `""`.
413///
414/// Signature: `control_str(name: const str) -> str`. Intrinsically
415/// `Nondeterministic` (live control read) — see `control_u64`.
416#[polydat::polydat_node(
417    category = Context,
418    purity = Nondeterministic("reads a live dynamic control value; changes over the run"),
419)]
420fn control_str(name: Const<&str>) -> String {
421    control_value_string(name.0)
422}
423
424// =========================================================================
425// rate() / concurrency() — thin aliases over control(...)
426// =========================================================================
427
428/// Sugar for `control("rate")` — the current rate-limiter target (ops/sec).
429/// Intrinsically `Nondeterministic` (live control read) — see `control`.
430#[polydat::polydat_node(
431    category = Context,
432    purity = Nondeterministic("reads the live rate control; changes over the run"),
433)]
434fn rate() -> f64 {
435    control_gauge_f64("rate")
436}
437
438/// Sugar for `control("concurrency")` — the current fiber count for the
439/// nearest phase. Intrinsically `Nondeterministic` — see `control`.
440#[polydat::polydat_node(
441    category = Context,
442    purity = Nondeterministic("reads the live concurrency control; changes over the run"),
443)]
444fn concurrency() -> f64 {
445    control_gauge_f64("concurrency")
446}
447
448// =========================================================================
449// phase() — current phase name (thread-local)
450// =========================================================================
451
452/// Current phase name. Reads a thread-local set by the phase executor;
453/// `""` when unset (outside a cycle, or in tests that install no phase).
454///
455/// Intrinsically `Nondeterministic`: the per-fiber phase name varies across
456/// fibers and over the run, so the node is never const-folded.
457#[polydat::polydat_node(
458    category = Context,
459    purity = Nondeterministic("reads the per-fiber phase name; varies across fibers and over the run"),
460)]
461fn phase() -> String {
462    task_phase().map(|s| s.to_string()).unwrap_or_default()
463}
464
465// =========================================================================
466// phase_start_millis() / phase_elapsed_millis() — phase-scoped clock
467// =========================================================================
468
469/// Epoch millis at which the CURRENT phase started; `0` outside a phase body.
470///
471/// The phase-scoped counterpart to `session_start_millis()`. Both exist because
472/// they answer different questions and a session origin cannot substitute for a
473/// phase one in a run that sweeps many phases.
474///
475/// The origin is established once per phase by the executor's `run_phase` and
476/// carried across fiber spawns, so every op under the phase reads the same
477/// value — including concurrent sibling phases, which each see their own
478/// (the origin is a task-local, not shared execution state).
479///
480/// Intrinsically `Nondeterministic`: the origin differs per phase and per run,
481/// so the node must never be const-folded into one phase's value.
482#[polydat::polydat_node(
483    category = Context,
484    purity = Nondeterministic("reads the current phase's start time; differs per phase and per run"),
485)]
486fn phase_start_millis() -> u64 {
487    crate::execution_context::current_phase_start_ms().unwrap_or(0)
488}
489
490/// Milliseconds elapsed since the CURRENT phase started; `0` outside a phase.
491///
492/// `current_epoch_millis() - phase_start_millis()` spelled as one node, which
493/// is the form workloads actually want — a phase-relative duration available
494/// while the phase is still running, rather than only at its completion pull.
495///
496/// Intrinsically `Nondeterministic`: it grows monotonically within a phase.
497#[polydat::polydat_node(
498    category = Context,
499    purity = Nondeterministic("monotonic elapsed time within the current phase"),
500)]
501fn phase_elapsed_millis() -> u64 {
502    let Some(start) = crate::execution_context::current_phase_start_ms() else {
503        return 0;
504    };
505    let now = std::time::SystemTime::now()
506        .duration_since(std::time::UNIX_EPOCH)
507        .map(|d| d.as_millis() as u64)
508        .unwrap_or(0);
509    now.saturating_sub(start)
510}
511
512// =========================================================================
513// cycle() — current cycle ordinal (thread-local)
514// =========================================================================
515
516/// Current cycle ordinal. Reads a thread-local set by the phase executor.
517/// For bindings that already declare `cycle` as a named input this is
518/// redundant; it exists so bindings which never named `cycle` explicitly can
519/// still reach it (SRD 10's "cycle is not magic" rule — the node is context,
520/// not a privileged input).
521///
522/// Intrinsically `Nondeterministic`: the cycle ordinal changes every cycle,
523/// so the node is never const-folded.
524#[polydat::polydat_node(
525    category = Context,
526    purity = Nondeterministic("reads the per-fiber cycle ordinal; changes every cycle"),
527)]
528fn cycle() -> u64 {
529    task_cycle()
530}
531
532// =========================================================================
533// Registration
534// =========================================================================
535//
536// Every node in this module is authored via `#[polydat::polydat_node]`
537// (SRD-80b) — the control readers (`control` / `control_u64` /
538// `control_bool` / `control_str` / `rate` / `concurrency`), the fiber-context
539// readers (`phase` / `cycle`), and the `control_set` writer. Each macro
540// emits its own FuncSig + builder + `inventory::submit!`, so there is no
541// hand-written `signatures()` / `build_node()` / `register_nodes!` here.
542
543#[cfg(test)]
544mod tests {
545    // The async tests hold the `serial_test()` guard (a pure `Mutex<()>`)
546    // across `.await` to serialize global session-root installs; the
547    // awaited code never locks it, so there's no deadlock.
548    #![allow(clippy::await_holding_lock)]
549    use super::*;
550    use nmbrs_metrics::controls::{BranchScope, ControlBuilder};
551    use nmbrs_metrics::labels::Labels;
552    use polydat::ast::Value;
553    use std::collections::HashMap;
554    use std::sync::MutexGuard;
555
556    /// Serializes test access to the global `SESSION_ROOT` and the
557    /// thread-locals — the crate-wide guard hoisted next to the global
558    /// itself, so session-construction tests in OTHER modules can hold the
559    /// same lock (see `session_root_test_guard`).
560    fn serial_test() -> MutexGuard<'static, ()> {
561        super::session_root_test_guard()
562    }
563
564    /// Build a session root with a declared control, install it
565    /// as the global, and return the root handle so callers can
566    /// mutate the control further.
567    fn install_session_with_control(name: &str, initial: u32) -> Arc<RwLock<Component>> {
568        let root = Component::root(Labels::empty().with("session", "t"), HashMap::new());
569        root.read().unwrap().controls().declare(
570            ControlBuilder::new(name, initial)
571                .reify_as_gauge(|v| Some(*v as f64))
572                .branch_scope(BranchScope::Subtree)
573                .build(),
574        );
575        set_session_root(root.clone());
576        root
577    }
578
579    #[test]
580    fn control_reads_current_value() {
581        let _g = serial_test();
582        install_session_with_control("rate", 500);
583        let mut k =
584            polydat::dsl::compile_polydat_interpreter("x := control(\"rate\")").expect("compile");
585        assert_eq!(k.pull_ref("x").as_f64(), 500.0);
586    }
587
588    #[test]
589    fn control_missing_name_returns_zero() {
590        let _g = serial_test();
591        install_session_with_control("rate", 500);
592        let mut k = polydat::dsl::compile_polydat_interpreter("x := control(\"not_declared\")")
593            .expect("compile");
594        assert_eq!(k.pull_ref("x").as_f64(), 0.0);
595    }
596
597    // Live re-read after a write is covered end-to-end by
598    // `fiber_writes_control_via_control_set_and_reads_back` (the integration
599    // test, which yields for the async commit then re-pulls `control(...)`);
600    // `control_u64_is_volatile_not_const_folded` covers the const-fold
601    // property here. A unit test that pulls immediately after an async write
602    // would race the background commit, so it lives at the integration tier.
603
604    #[test]
605    fn rate_node_is_alias_of_control_rate() {
606        let _g = serial_test();
607        install_session_with_control("rate", 750);
608        let mut k = polydat::dsl::compile_polydat_interpreter("x := rate()").expect("compile");
609        assert_eq!(k.pull_ref("x").as_f64(), 750.0);
610    }
611
612    #[test]
613    fn concurrency_node_reads_concurrency_control() {
614        let _g = serial_test();
615        install_session_with_control("concurrency", 32);
616        let mut k =
617            polydat::dsl::compile_polydat_interpreter("x := concurrency()").expect("compile");
618        assert_eq!(k.pull_ref("x").as_f64(), 32.0);
619    }
620
621    #[tokio::test]
622    async fn phase_and_cycle_read_from_task_locals() {
623        let phase_arc: Arc<str> = Arc::from("rampup");
624        with_fiber_context(phase_arc.clone(), empty_controls(), async {
625            set_task_cycle(4242);
626            let mut k = polydat::dsl::compile_polydat_interpreter("p := phase()\nc := cycle()")
627                .expect("compile phase/cycle");
628            assert_eq!(k.pull_ref("p").as_str(), "rampup");
629            assert_eq!(k.pull_ref("c").as_u64(), 4242);
630        })
631        .await;
632    }
633
634    #[test]
635    fn phase_is_empty_outside_fiber_scope() {
636        // Reading outside a fiber context — e.g. from a unit test or a
637        // non-fiber call site — silently returns the empty string rather
638        // than panicking (the task_local's `try_with` Err maps to default).
639        let mut k = polydat::dsl::compile_polydat_interpreter("p := phase()").expect("compile");
640        assert_eq!(k.pull_ref("p").as_str(), "");
641    }
642
643    #[test]
644    fn cycle_is_zero_outside_fiber_scope() {
645        let mut k = polydat::dsl::compile_polydat_interpreter("c := cycle()").expect("compile");
646        assert_eq!(k.pull_ref("c").as_u64(), 0);
647    }
648
649    #[tokio::test]
650    async fn set_task_cycle_is_noop_outside_scope() {
651        // A stray call with no active scope must not panic.
652        set_task_cycle(99);
653        let mut k = polydat::dsl::compile_polydat_interpreter("c := cycle()").expect("compile");
654        assert_eq!(k.pull_ref("c").as_u64(), 0);
655    }
656
657    // ---- control_set ------------------------------------------
658
659    #[tokio::test]
660    async fn control_set_writes_through_converter_and_reaches_committed() {
661        let _g = serial_test();
662        // Install a root with a concurrency control that accepts
663        // f64 writes via an explicit from_f64 converter.
664        let root = Component::root(
665            Labels::empty().with("session", "s_cs"),
666            std::collections::HashMap::new(),
667        );
668        let c: nmbrs_metrics::controls::Control<u32> =
669            nmbrs_metrics::controls::ControlBuilder::new("concurrency", 4u32)
670                .reify_as_gauge(|v| Some(*v as f64))
671                .from_f64(|v| {
672                    if v < 0.0 || v > u32::MAX as f64 {
673                        Err(format!("out of range: {v}"))
674                    } else {
675                        Ok(v as u32)
676                    }
677                })
678                .branch_scope(nmbrs_metrics::controls::BranchScope::Subtree)
679                .build();
680        root.read().unwrap().controls().declare(c.clone());
681        set_session_root(root);
682
683        // Issue the write through the macro-authored node, built via the same
684        // factory route the compiler uses (under a binding scope).
685        let ctx = polydat::dsl::factory::BuildContext::with_binding("feedback_loop");
686        let consts = [polydat::dsl::factory::ConstArg::Str("concurrency".into())];
687        let node = polydat::dsl::factory::build_node(&ctx, "control_set", &[], &[], &consts)
688            .expect("control_set should build");
689        let mut out = [Value::None];
690        node.eval(&[Value::F64(64.0)], &mut out);
691        assert_eq!(out[0].as_u64(), 1, "write should report submitted");
692
693        // The write is async; yield a few times for the spawned
694        // task to run through validate → fanout → commit.
695        for _ in 0..10 {
696            tokio::task::yield_now().await;
697            if c.value() == 64u32 {
698                break;
699            }
700        }
701        assert_eq!(c.value(), 64u32);
702        let committed = c.get();
703        assert!(matches!(
704            committed.origin,
705            nmbrs_metrics::controls::ControlOrigin::Polydat { .. }
706        ));
707
708        // Idempotent-write elision: the control now reads 64.0, so a
709        // second write of the SAME value is a fixpoint — elided, 0
710        // (not dispatched), revision unmoved. A different value
711        // dispatches again.
712        let rev_before = c.get().rev;
713        node.eval(&[Value::F64(64.0)], &mut out);
714        assert_eq!(
715            out[0].as_u64(),
716            0,
717            "write of the committed value must be elided"
718        );
719        assert_eq!(
720            c.get().rev,
721            rev_before,
722            "an elided write must not touch the control"
723        );
724        node.eval(&[Value::F64(32.0)], &mut out);
725        assert_eq!(out[0].as_u64(), 1, "a real change dispatches");
726        for _ in 0..10 {
727            tokio::task::yield_now().await;
728            if c.value() == 32u32 {
729                break;
730            }
731        }
732        assert_eq!(c.value(), 32u32);
733    }
734
735    #[test]
736    fn control_u64_casts_gauge_to_integer() {
737        let _g = serial_test();
738        install_session_with_control("concurrency", 64);
739        // `control_u64` is macro-authored — compile + pull it end to end.
740        let mut k = polydat::dsl::compile_polydat_interpreter("x := control_u64(\"concurrency\")")
741            .expect("compile control_u64");
742        assert_eq!(k.pull_ref("x").as_u64(), 64);
743    }
744
745    #[test]
746    fn control_u64_missing_name_returns_zero() {
747        let _g = serial_test();
748        install_session_with_control("concurrency", 5);
749        let mut k = polydat::dsl::compile_polydat_interpreter("x := control_u64(\"not_there\")")
750            .expect("compile control_u64");
751        assert_eq!(k.pull_ref("x").as_u64(), 0);
752    }
753
754    #[test]
755    fn control_u64_is_volatile_not_const_folded() {
756        let _g = serial_test();
757        install_session_with_control("concurrency", 32);
758        // Intrinsic volatility (the bug this fixes): a `Nondeterministic`
759        // node is never const-folded, so the wire stays a live dynamic
760        // output re-read on every pull. A Pure reader would fold `x` to a
761        // compile-time constant — which is exactly how the old hand-written
762        // node (no purity override) cached a stale first value.
763        let k = polydat::dsl::compile_polydat_interpreter("x := control_u64(\"concurrency\")")
764            .expect("compile control_u64");
765        assert!(
766            k.get_constant("x").is_none(),
767            "control_u64 must be volatile — its wire must NOT be const-folded",
768        );
769    }
770
771    #[test]
772    fn control_bool_projects_gauge_to_boolean() {
773        let _g = serial_test();
774        install_session_with_control("enabled", 1);
775        let mut k = polydat::dsl::compile_polydat_interpreter("x := control_bool(\"enabled\")")
776            .expect("compile");
777        assert!(k.pull_ref("x").as_bool());
778    }
779
780    #[test]
781    fn control_bool_zero_is_false() {
782        let _g = serial_test();
783        install_session_with_control("enabled", 0);
784        let mut k = polydat::dsl::compile_polydat_interpreter("x := control_bool(\"enabled\")")
785            .expect("compile");
786        assert!(!k.pull_ref("x").as_bool());
787    }
788
789    #[test]
790    fn control_bool_missing_name_is_false() {
791        let _g = serial_test();
792        install_session_with_control("enabled", 1);
793        let mut k = polydat::dsl::compile_polydat_interpreter("x := control_bool(\"absent\")")
794            .expect("compile");
795        assert!(!k.pull_ref("x").as_bool());
796    }
797
798    #[test]
799    fn control_str_renders_value_string() {
800        let _g = serial_test();
801        install_session_with_control("concurrency", 42);
802        let mut k = polydat::dsl::compile_polydat_interpreter("x := control_str(\"concurrency\")")
803            .expect("compile");
804        // u32's Debug rendering is its decimal representation.
805        assert_eq!(k.pull_ref("x").as_str(), "42");
806    }
807
808    #[test]
809    fn control_str_missing_name_returns_empty() {
810        let _g = serial_test();
811        install_session_with_control("concurrency", 42);
812        let mut k = polydat::dsl::compile_polydat_interpreter("x := control_str(\"log_level\")")
813            .expect("compile");
814        assert_eq!(k.pull_ref("x").as_str(), "");
815    }
816
817    #[tokio::test]
818    async fn control_set_records_compile_time_binding_attribution() {
819        let _g = serial_test();
820        // Build a control that accepts f64 writes and install
821        // the session root.
822        let root = Component::root(
823            Labels::empty().with("session", "attr"),
824            std::collections::HashMap::new(),
825        );
826        let c: nmbrs_metrics::controls::Control<f64> =
827            nmbrs_metrics::controls::ControlBuilder::new("rate", 100.0)
828                .reify_as_gauge(|v| Some(*v))
829                .from_f64(Ok)
830                .branch_scope(nmbrs_metrics::controls::BranchScope::Subtree)
831                .build();
832        root.read().unwrap().controls().declare(c.clone());
833        set_session_root(root.clone());
834
835        // Simulate a compiler constructing a control_set factory
836        // under a binding scope named `rate_adj`. We can't call
837        // `build_node` from inside the same crate's private
838        // factory path directly, so reach into the nodes
839        // registration helper via the same build-by-name route
840        // the compiler uses.
841        let ctx = polydat::dsl::factory::BuildContext::with_binding("rate_adj");
842        let consts = [polydat::dsl::factory::ConstArg::Str("rate".into())];
843        let node = polydat::dsl::factory::build_node(&ctx, "control_set", &[], &[], &consts)
844            .expect("control_set should build");
845        let mut out = [Value::None];
846        node.eval(&[Value::F64(4242.0)], &mut out);
847
848        // Let the spawned write complete.
849        for _ in 0..40 {
850            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
851            if c.value() == 4242.0 {
852                break;
853            }
854        }
855        assert_eq!(c.value(), 4242.0);
856        match c.get().origin {
857            nmbrs_metrics::controls::ControlOrigin::Polydat { ref binding } => {
858                assert_eq!(
859                    binding, "rate_adj",
860                    "attribution should be the DSL binding name, not the control name"
861                );
862            }
863            other => panic!("expected Polydat origin, got {other:?}"),
864        }
865    }
866
867    #[test]
868    fn control_set_returns_zero_without_session_root() {
869        let _g = serial_test();
870        // Explicitly clear the session root so the node can't
871        // resolve anything.
872        *SESSION_ROOT.lock().unwrap_or_else(|e| e.into_inner()) = None;
873
874        let consts = [polydat::dsl::factory::ConstArg::Str("anything".into())];
875        let node = polydat::dsl::factory::build_node(
876            &polydat::dsl::factory::BuildContext::default(),
877            "control_set",
878            &[],
879            &[],
880            &consts,
881        )
882        .expect("control_set should build");
883        let mut out = [Value::None];
884        node.eval(&[Value::F64(1.0)], &mut out);
885        assert_eq!(out[0].as_u64(), 0);
886    }
887
888    // ---- SRD-89: per-execution control isolation -------------------
889
890    /// Build a one-entry control map carrying a `concurrency` control fixed at
891    /// `val`, as `install_controls` expects (name → erased handle).
892    /// A standalone phase-tier component declaring a `concurrency` control at
893    /// `val` — the per-execution phase component a fiber resolves against.
894    fn component_with_concurrency(val: u32) -> Arc<RwLock<Component>> {
895        let comp = Component::root(Labels::empty().with("phase", "p"), HashMap::new());
896        comp.read()
897            .unwrap_or_else(|e| e.into_inner())
898            .controls()
899            .declare(
900                ControlBuilder::new("concurrency", val)
901                    .reify_as_gauge(|v| Some(*v as f64))
902                    .branch_scope(BranchScope::Subtree)
903                    .build(),
904            );
905        comp
906    }
907
908    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
909    async fn per_execution_control_map_isolates_concurrent_reads() {
910        // SRD-89 §2b — two executions sharing one session each declare a
911        // `concurrency` control with a DISTINCT value on their own phase
912        // component. Under the pre-SRD-89 shared-`SESSION_ROOT` model both
913        // resolve to one instance (deterministic cross-talk — a servo
914        // retargeting one drives the other). The per-execution control map
915        // isolates them: each execution reads its OWN setting. This is the unit
916        // encoding of the walker's `control`/`multiservo` failure.
917        let _g = serial_test();
918        // Clear the global root so resolution can ONLY come from each fiber's
919        // own current-component snapshot (a leftover sibling root must not mask
920        // a miss).
921        *SESSION_ROOT.lock().unwrap_or_else(|e| e.into_inner()) = None;
922
923        // Two executions, each with its OWN phase component declaring
924        // `concurrency` at a distinct value.
925        let comp_a = component_with_concurrency(2);
926        let comp_b = component_with_concurrency(32);
927        let phase: Arc<str> = Arc::from("p");
928
929        // Each fiber resolves through its own component snapshot (FIBER_CTX).
930        let a_val = with_fiber_context(phase.clone(), snapshot_controls(&comp_a), async {
931            control_gauge_f64("concurrency")
932        })
933        .await;
934        let b_val = with_fiber_context(phase.clone(), snapshot_controls(&comp_b), async {
935            control_gauge_f64("concurrency")
936        })
937        .await;
938
939        assert_eq!(a_val, 2.0, "execution A must read its OWN concurrency (2)");
940        assert_eq!(
941            b_val, 32.0,
942            "execution B must read its OWN concurrency (32), not A's",
943        );
944    }
945
946    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
947    async fn control_read_falls_back_to_session_root_without_exec_context() {
948        // A1 — outside any scoped execution (single-run / dryrun / TUI), the
949        // read path is byte-identical to before SRD-89: it resolves via the
950        // global SESSION_ROOT walk. No per-exec map exists, so the fallback is
951        // the only path.
952        let _g = serial_test();
953        install_session_with_control("concurrency", 7);
954        // No execution_context::scope here — current_control() returns None.
955        assert_eq!(control_gauge_f64("concurrency"), 7.0);
956    }
957}