nmbrs_runtime/optimize/settle.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! SRD-86 §"Settling via the cadence pulse" — the per-pulse settle
5//! interpreter and its [`PulseEvaluator`] adapter.
6//!
7//! For a *volatile* optimizer objective (one defined over a windowed
8//! run-produced metric such as `metric_window("...","errors")` or a
9//! `metricsql_*` reader), the objective value chases the live cadence
10//! window and at phase completion the trailing window is empty. The
11//! objective therefore cannot be read by a one-shot post-execution
12//! pull; it must be *settled* across the run and held in a register the
13//! executor reads at completion.
14//!
15//! [`SettleInterpreter`] is the settle-signal engine. It owns one
16//! persistent settle-kernel — typically the phase's objective bindings
17//! plus `(stable_value, stable) := is_stable(<objective>, …)` — and is
18//! driven once per cadence pulse:
19//!
20//! 1. `set_input` on the kernel's poke input advances the generation,
21//! which dirties **every** non-deterministic node (engine rule, see
22//! `kernel::engines::set_input`): the embedded volatile objective
23//! reader re-reads the latest published window and
24//! [`is_stable`](polydat::library::stability) re-evaluates — exactly
25//! one new sample on its ring.
26//! 2. Pull `stable` then `stable_value`; both land on that single
27//! evaluation (generation cache), so the multi-output node
28//! contributes one sample per pulse, not two.
29//! 3. Publish `stable_value` into the shared register (an [`ArcSwap`],
30//! lock-free for the executor's completion read).
31//!
32//! The interpreter does **not** decide phase stop — that is the
33//! [`SettleEvaluator`]'s job (settled ⇒ `interrupted`; timed out ⇒
34//! `failed`), driven through the general
35//! [`super::phase_pulse::PhaseStopEvaluator`] callback registered on the
36//! metrics cadence feed.
37
38use std::sync::Arc;
39use std::sync::atomic::AtomicBool;
40use std::time::{Duration, Instant};
41
42use crate::scope_kernel::ScopeKernel;
43use arc_swap::ArcSwap;
44use nmbrs_metrics::cadence_reporter::{CadenceReporter, SubscriberId};
45use nmbrs_metrics::snapshot::MetricSet;
46use polydat::Kernel;
47use polydat::ast::Value;
48use polydat::kernel::PolydatProgram;
49
50use super::phase_pulse::{PhaseStopEvaluator, PulseEvaluator, StopOutcomeCell};
51use crate::phase_outcome::Outcome;
52
53/// Convert a pulled objective wire to f64 with the same numeric
54/// coercion as `read_objective_at_completion` (F64 as-is, U64 widened,
55/// Bool 0/1); a non-numeric objective reads as 0.0 (the
56/// volatile-objective gate upstream only admits numeric readers).
57fn objective_to_f64(v: &Value) -> f64 {
58 match v {
59 Value::F64(f) => *f,
60 Value::U64(u) => *u as f64,
61 Value::Bool(b) if *b => 1.0,
62 _ => 0.0,
63 }
64}
65
66/// The latest reading a [`SettleInterpreter`] publishes.
67#[derive(Clone, Copy, Debug)]
68pub struct SettleReading {
69 /// The stabilized objective value — `is_stable`'s `stable_value`
70 /// output (the median of the recent window). This is what the
71 /// phase executor reads as the objective at completion.
72 pub value: f64,
73 /// Whether the signal reached steady state on the latest pulse.
74 pub stable: bool,
75 /// Count of pulses delivered so far (viability / diagnostics).
76 pub pulses: u64,
77}
78
79impl Default for SettleReading {
80 fn default() -> Self {
81 Self {
82 value: 0.0,
83 stable: false,
84 pulses: 0,
85 }
86 }
87}
88
89/// Per-pulse interpreter of objective settling. See the module docs.
90pub struct SettleInterpreter {
91 /// A standalone kernel on whatever engine the compile chose — it
92 /// takes no part in the scope tree, so it is driven through the
93 /// engine-neutral [`Kernel`] trait.
94 kernel: Box<dyn Kernel>,
95 /// Index of the kernel's `samples: vec_f64` input, the window
96 /// `is_stable` judges.
97 samples_input: usize,
98 /// The most recent samples, oldest first, at most `horizon` of them.
99 /// `is_stable` is a pure function of its window, so the interpreter
100 /// owns the history.
101 window: std::collections::VecDeque<f64>,
102 horizon: usize,
103 value_wire: String,
104 stable_wire: String,
105 register: Arc<ArcSwap<SettleReading>>,
106 pulses: u64,
107}
108
109impl SettleInterpreter {
110 /// Build an interpreter over a compiled settle kernel. `samples` is
111 /// its `vec_f64` window input; `value_wire` / `stable_wire` are the
112 /// `is_stable` multi-output wire names; `horizon` is how many recent
113 /// samples the window holds.
114 ///
115 /// # Panics
116 /// When the kernel has no `samples` input: a malformed settle kernel.
117 pub fn new(
118 kernel: Box<dyn Kernel>,
119 samples: &str,
120 value_wire: &str,
121 stable_wire: &str,
122 horizon: usize,
123 ) -> Self {
124 let samples_input = kernel
125 .input_index(samples)
126 .unwrap_or_else(|| panic!("settle kernel has no `{samples}` input"));
127 Self {
128 kernel,
129 samples_input,
130 window: std::collections::VecDeque::with_capacity(horizon),
131 horizon,
132 value_wire: value_wire.to_string(),
133 stable_wire: stable_wire.to_string(),
134 register: Arc::new(ArcSwap::from_pointee(SettleReading::default())),
135 pulses: 0,
136 }
137 }
138
139 /// The shared register handle. The executor reads the settled
140 /// objective from this at phase completion; the interpreter
141 /// publishes into it on every pulse.
142 pub fn register(&self) -> Arc<ArcSwap<SettleReading>> {
143 self.register.clone()
144 }
145
146 /// Deliver one cadence pulse: append `sample` to the window (dropping
147 /// the oldest past `horizon`), write the window to the kernel, read
148 /// `is_stable`'s verdict on it, publish the stabilized value, and
149 /// return the reading.
150 pub fn pulse(&mut self, sample: f64) -> SettleReading {
151 self.pulses += 1;
152 if self.window.len() == self.horizon {
153 self.window.pop_front();
154 }
155 self.window.push_back(sample);
156 let window: Vec<f64> = self.window.iter().copied().collect();
157 // `samples` is a `vec_f64` extern, so a `VecF64` write cannot be
158 // refused; a refusal is a malformed settle kernel.
159 self.kernel
160 .set_input_at(
161 self.samples_input,
162 Value::VecF64(polydat::ast::SliceArc::from_vec(window)),
163 )
164 .expect("settle kernel refused its vec_f64 `samples` extern");
165 let stable = self.kernel.pull(&self.stable_wire).as_u64() != 0;
166 let value = self.kernel.pull(&self.value_wire).as_f64();
167
168 let reading = SettleReading {
169 value,
170 stable,
171 pulses: self.pulses,
172 };
173 self.register.store(Arc::new(reading));
174 reading
175 }
176}
177
178/// The settle detector as a [`PulseEvaluator`]. It holds the phase's
179/// **objective kernel** (a clone of node X's kernel — already bound to
180/// this evaluation's coordinate, the same kernel
181/// `read_objective_at_completion` pulls) and a fixed `is_stable`
182/// engine. Each cadence pulse:
183///
184/// 1. positions the objective kernel at the pulse's ordinal on its
185/// coordinate input (typically `cycle`); a volatile objective reader
186/// re-reads the latest published window on every pull regardless;
187/// 2. pulls the objective wire — the fresh windowed objective value;
188/// 3. feeds it to [`SettleInterpreter`] (`is_stable`).
189///
190/// It yields a terminal [`Outcome`] when the objective settles
191/// (`interrupted` — stopped early, register trustworthy) or when the
192/// settle `timeout` elapses without settling (`failed` — SRD-86 §6
193/// step 5). `None` while the loop should hold.
194pub struct SettleEvaluator {
195 objective: ScopeKernel,
196 objective_wire: String,
197 poke: Option<usize>,
198 interp: SettleInterpreter,
199 timeout: Duration,
200 /// SRD-86 viability gate — minimum WALL-CLOCK a coordinate must run before a
201 /// stable verdict is trusted, so the windowed objective's rollup has cleared
202 /// the prior coordinate (and the leading transient). Wall-clock, not pulse
203 /// count: under concurrent scheduling cadence pulses are delivered in
204 /// bursts (many per cadence interval), so a pulse gate collapses to far less
205 /// than the window — the gate must measure real time.
206 min_viable: Duration,
207 started: Option<Instant>,
208 pulses: u64,
209}
210
211impl SettleEvaluator {
212 /// `objective` is the phase's objective kernel (node X clone);
213 /// `objective_wire` the objective output; `poke_input` the coordinate
214 /// input positioned at each pulse's ordinal (typically `cycle`);
215 /// `interp` the `is_stable` engine fed the objective value.
216 pub fn new(
217 objective: ScopeKernel,
218 objective_wire: &str,
219 poke_input: &str,
220 interp: SettleInterpreter,
221 timeout: Duration,
222 min_viable: Duration,
223 ) -> Self {
224 let poke = objective.program().find_input(poke_input);
225 Self {
226 objective,
227 objective_wire: objective_wire.to_string(),
228 poke,
229 interp,
230 timeout,
231 min_viable,
232 started: None,
233 pulses: 0,
234 }
235 }
236
237 /// The settled-value register (grab it before boxing the evaluator).
238 pub fn register(&self) -> Arc<ArcSwap<SettleReading>> {
239 self.interp.register()
240 }
241}
242
243impl PulseEvaluator for SettleEvaluator {
244 fn evaluate(&mut self, _window: &MetricSet) -> Option<Outcome> {
245 let start = *self.started.get_or_insert_with(Instant::now);
246 self.pulses += 1;
247 // Position the objective kernel at this pulse, then read it; a
248 // volatile reader in its cone re-reads the latest published
249 // window on every pull.
250 if let Some(idx) = self.poke {
251 let k = &mut self.objective;
252 let coords = k.coord_count();
253 if idx < coords {
254 // A coordinate is positioned with `set_inputs`; the pulse
255 // then invalidates every output so a volatile reader
256 // re-reads (native_scope_trees.md §3, the settle pulse).
257 let mut position: Vec<u64> = (0..coords)
258 .map(|i| k.input_value_at(i).map_or(0, |v| v.as_u64()))
259 .collect();
260 position[idx] = self.pulses;
261 k.set_inputs(&position);
262 k.invalidate_all();
263 } else if let Err(e) = k.set_input_at(idx, Value::U64(self.pulses)) {
264 crate::diag!(
265 crate::observer::LogLevel::Warn,
266 "settle: the objective's poke input refused pulse {}: {e}",
267 self.pulses
268 );
269 }
270 }
271 let obj = objective_to_f64(&self.objective.pull(&self.objective_wire));
272 // SRD-89 — a NaN objective is a windowed metric reading **no data** (an
273 // empty `rate(...[W])` lookback — see `nodes::no_data_value`), distinct
274 // from a real 0. HOLD on it: do not feed the stability detector (a
275 // fabricated 0 would let `is_stable` settle on the empty leading reads,
276 // mis-converging the optimizer under concurrency where early windows are
277 // routinely empty) and do not advance the register. The timeout still
278 // bounds the wait, so a window that never produces data fails rather
279 // than hanging.
280 if obj.is_nan() {
281 if start.elapsed() >= self.timeout {
282 return Some(Outcome::failed());
283 }
284 return None;
285 }
286 let reading = self.interp.pulse(obj);
287 // SRD-86 viability gate — do NOT trust a stable verdict until the
288 // coordinate has run for `min_viable` of WALL-CLOCK, so the windowed
289 // objective's rollup has cleared the prior coordinate (and its own
290 // leading transient). At a coordinate's START the windowed objective is
291 // a stable run of stale data — `rate(errors_total[W])` reads ~0 before
292 // the first error registers at warmup, and at a transition it reads the
293 // PRIOR coordinate's value drifting out of the window. `is_stable`
294 // (which fires on `SETTLE_MIN_SAMPLES`, and whose relative margin admits
295 // a slow drift as "stable") would latch that stale value, mis-converging
296 // the optimizer (it keeps a saturating `concurrency` because it "saw no
297 // errors", or accepts a half-cleared transition value). The gate is
298 // wall-clock, not pulse count: under concurrent scheduling cadence
299 // pulses arrive in bursts, so a pulse gate collapses to far less than
300 // the window — only real elapsed time guarantees the window has cleared.
301 if reading.stable && start.elapsed() >= self.min_viable {
302 return Some(Outcome::interrupted());
303 }
304 if start.elapsed() >= self.timeout {
305 return Some(Outcome::failed());
306 }
307 None
308 }
309}
310
311/// Metrics-reader node names whose presence makes a phase's objective
312/// potentially volatile (read from the live cadence feed). The
313/// `metric` / `metric_window` stat-readers and the four `metricsql_*`
314/// readers. (First-push heuristic: program-wide presence, not
315/// objective-cone-precise — a non-reader objective in a phase that also
316/// reads metrics elsewhere would settle trivially on its constant.)
317const READER_NODES: &[&str] = &[
318 "metric",
319 "metric_window",
320 "metricsql",
321 "metricsql_scalar",
322 "metricsql_vector",
323 "metricsql_window",
324];
325
326/// True if `program` contains a metrics-reader node — the signal that
327/// the phase's objective may be a volatile windowed metric that the
328/// one-shot post-completion read cannot capture.
329pub fn program_reads_live_metrics(program: &PolydatProgram) -> bool {
330 (0..program.node_count()).any(|i| READER_NODES.contains(&program.node_meta(i).name.as_str()))
331}
332
333/// Node name of the session-cumulative reader (`metric(...)`), which
334/// reads `MetricsQuery::session_lifetime` — a running total over ALL
335/// coordinates. Unlike the windowed readers it has no bounded lookback,
336/// so the viability gate cannot scope it to one coordinate.
337const SESSION_CUMULATIVE_READER: &str = "metric";
338
339/// True if `program` reads the session-cumulative `metric(...)` reader —
340/// an objective aggregated across every coordinate, which the per-eval
341/// warmup gate cannot isolate (no window to clear). The settle warns
342/// rather than silently treating it as per-coordinate.
343fn program_reads_session_cumulative_metrics(program: &PolydatProgram) -> bool {
344 (0..program.node_count()).any(|i| program.node_meta(i).name == SESSION_CUMULATIVE_READER)
345}
346
347/// Warn at most once per distinct objective string that it reads a
348/// session-cumulative metric. Returns `true` the first time a given
349/// objective is seen (so the caller emits the diagnostic once, not once
350/// per coordinate across a search).
351fn warn_once_session_cumulative(objective: &str) -> bool {
352 static WARNED: std::sync::LazyLock<std::sync::Mutex<std::collections::HashSet<String>>> =
353 std::sync::LazyLock::new(Default::default);
354 WARNED
355 .lock()
356 .unwrap_or_else(|e| e.into_inner())
357 .insert(objective.to_string())
358}
359
360// First-push settle parameters (the SRD-86 §6 `settle:` YAML surface +
361// finer-cadence reconfiguration are deferred). Sized for the default
362// 1 s cadence and short phases: `is_stable`'s windowed median is
363// published every pulse regardless of the `stable` flag, so the
364// register holds a smoothed objective even before a full settle; the
365// 8-deep horizon / 4-sample warmup let a steady objective settle (and
366// stop the phase early) within a handful of pulses. The generous
367// timeout means a phase that completes first simply uses its smoothed
368// value — only a genuinely non-settling long phase trips `failed`.
369//
370// The settle is gated by a viability horizon (see `SettleEvaluator::evaluate`):
371// a stable verdict is only honored once `SETTLE_HORIZON` pulses have been
372// delivered, so the verdict is always taken over a full horizon of
373// in-coordinate samples (≈ `SETTLE_HORIZON × cadence` of wall-clock, the rollup
374// window by the usual `window = horizon × cadence` sizing). Without it, a
375// windowed objective's leading transient — `rate(...[W])` reading ~0 before the
376// coordinate's first data lands — is itself momentarily "stable", and
377// `is_stable` (firing on `SETTLE_MIN_SAMPLES`) latches that phantom value; under
378// concurrent scheduling a sub-window eval did exactly that.
379const SETTLE_MARGIN: f64 = 0.05;
380const SETTLE_MIN_SAMPLES: u64 = 4;
381const SETTLE_HORIZON: u64 = 8;
382const SETTLE_TIMEOUT: Duration = Duration::from_secs(60);
383
384/// What the executor holds while a settle detector runs: the cadence
385/// subscription to tear down, the settled-value register, and the
386/// terminal-disposition cell.
387pub struct SettleHandle {
388 pub subscriber: SubscriberId,
389 pub register: Arc<ArcSwap<SettleReading>>,
390 pub outcome: StopOutcomeCell,
391}
392
393/// Why [`start_settle`] started no detector.
394#[derive(Debug)]
395pub enum SettleSkip {
396 /// The objective reads no live metric: its one-shot read at phase
397 /// completion is the value, and there is nothing to settle.
398 NotWindowed,
399 /// The metrics cadence is disabled, so no pulse would ever arrive.
400 CadenceDisabled,
401 /// The detector could not be built.
402 Failed(String),
403}
404
405impl std::fmt::Display for SettleSkip {
406 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407 match self {
408 SettleSkip::NotWindowed => write!(f, "it reads no live windowed metric"),
409 SettleSkip::CadenceDisabled => write!(f, "the metrics cadence is disabled"),
410 SettleSkip::Failed(reason) => {
411 write!(f, "the settle detector failed to start: {reason}")
412 }
413 }
414 }
415}
416
417/// Start a cadence-fed settle detector for `objective` on the running
418/// phase **iff** the objective reads live metrics. Builds the objective
419/// kernel as node X's program rebound to `parent` (carrying the
420/// coordinate — mirrors `read_objective_at_completion`), wraps it in a
421/// [`PhaseStopEvaluator`], and subscribes it to the smallest cadence.
422/// Starts nothing for a non-volatile objective (the one-shot read path
423/// is correct there) or when the metrics cadence is disabled, and says
424/// which; a detector that cannot be built is [`SettleSkip::Failed`].
425pub fn start_settle(
426 parent: &Arc<ScopeKernel>,
427 phase_kernel: &Arc<ScopeKernel>,
428 objective: &str,
429 reporter: &Arc<CadenceReporter>,
430 stop_flag: Arc<AtomicBool>,
431) -> Result<SettleHandle, SettleSkip> {
432 let program = phase_kernel.program();
433 if !program_reads_live_metrics(program) {
434 return Err(SettleSkip::NotWindowed);
435 }
436 // A session-cumulative `metric(...)` objective has no bounded window
437 // for the gate to scope, so it cannot isolate per-coordinate — warn
438 // once and servo the author to a windowed reader.
439 if program_reads_session_cumulative_metrics(program) && warn_once_session_cumulative(objective)
440 {
441 crate::diag!(
442 crate::observer::LogLevel::Warn,
443 "optimizer objective '{objective}' reads a session-cumulative metric \
444 (`metric(...)` → session_lifetime): it aggregates across coordinates and \
445 will not isolate per-coordinate. Use `metric_window(...)` or \
446 `metricsql_scalar(rate(...[W]))` for a per-coordinate objective."
447 );
448 }
449 let cadence = reporter.declared_cadences().smallest();
450 if cadence.is_zero() {
451 return Err(SettleSkip::CadenceDisabled);
452 }
453
454 let failed = |what: &str, e: &dyn std::fmt::Display| SettleSkip::Failed(format!("{what}: {e}"));
455 let obj_kernel = phase_kernel
456 .bind_under(parent.kernel(), &[])
457 .map_err(|e| failed("objective kernel", &e))?;
458
459 let is_stable_kernel = polydat::dsl::compile::compile_polydat(&format!(
460 "extern samples: vec_f64\n(stable_value, stable) := is_stable(samples, {SETTLE_MARGIN}, \
461 {SETTLE_MIN_SAMPLES})"
462 ))
463 .map_err(|e| failed("is_stable kernel", &e))?;
464 let interp = SettleInterpreter::new(
465 is_stable_kernel,
466 "samples",
467 "stable_value",
468 "stable",
469 SETTLE_HORIZON as usize,
470 );
471 // Viability gate = the stability horizon's worth of cadence intervals, in
472 // WALL-CLOCK. With the usual `window = SETTLE_HORIZON × cadence` sizing this
473 // is the rollup window — long enough for the objective's window to clear the
474 // prior coordinate before a stable verdict is honored.
475 let min_viable = cadence.saturating_mul(SETTLE_HORIZON as u32);
476 let eval = SettleEvaluator::new(
477 obj_kernel,
478 objective,
479 "cycle",
480 interp,
481 SETTLE_TIMEOUT,
482 min_viable,
483 );
484 let register = eval.register();
485
486 let pse = PhaseStopEvaluator::new(Box::new(eval), stop_flag);
487 let outcome = pse.outcome_cell();
488 // SRD-88 — bind this subscription to THIS execution's context so its
489 // delivery fiber pulls the objective as the owning execution (the
490 // metric read scopes to its own `exec_id`). Captured in the
491 // execution's scope here; `None` in single-run (A1).
492 let mut opts = nmbrs_metrics::cadence_reporter::SubscriptionOpts::default();
493 if let Some(ctx) = crate::execution_context::try_current() {
494 opts.context_wrap = Some(std::sync::Arc::new(move |fut| {
495 Box::pin(crate::execution_context::scope(ctx.clone(), fut))
496 as std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>
497 }));
498 }
499 let subscriber = reporter
500 .subscribe(cadence, Box::new(pse), opts)
501 .map_err(|e| failed("cadence subscription", &e))?;
502 Ok(SettleHandle {
503 subscriber,
504 register,
505 outcome,
506 })
507}
508
509#[cfg(test)]
510mod tests {
511 use super::*;
512 use crate::phase_outcome::{Disposition, Validity};
513 use polydat::dsl::compile::{compile_polydat, compile_polydat_interpreter};
514
515 /// The fixed `is_stable` engine fed the per-pulse objective value.
516 fn settle_interp() -> SettleInterpreter {
517 let kernel = compile_polydat(
518 "extern samples: vec_f64\n(stable_value, stable) := is_stable(samples, 0.05, 4)",
519 )
520 .expect("is_stable kernel compiles");
521 SettleInterpreter::new(kernel, "samples", "stable_value", "stable", 8)
522 }
523
524 fn obj_kernel(src: &str) -> ScopeKernel {
525 crate::bindings::compile_scope_kernel(src, &Default::default())
526 .expect("objective kernel compiles")
527 }
528
529 // A constant objective: settles regardless of the poke.
530 const STEADY_OBJ: &str = "input cycle: u64\nobj := 5.0";
531 // A ramping objective = the poke value (cycle): never settles.
532 const RAMP_OBJ: &str = "input cycle: u64\nobj := cycle";
533
534 fn window() -> MetricSet {
535 MetricSet::new(Duration::from_secs(1))
536 }
537
538 #[test]
539 fn interpreter_publishes_settled_value_into_the_register() {
540 let mut i = settle_interp();
541 let mut last = SettleReading::default();
542 for _ in 0..8 {
543 last = i.pulse(5.0);
544 }
545 assert!(last.stable, "a steady value settles");
546 assert!(
547 (i.register().load().value - 5.0).abs() < 1e-9,
548 "register holds the steady level"
549 );
550 }
551
552 #[test]
553 fn evaluator_yields_interrupted_when_settled() {
554 let mut ev = SettleEvaluator::new(
555 obj_kernel(STEADY_OBJ),
556 "obj",
557 "cycle",
558 settle_interp(),
559 Duration::from_secs(60),
560 Duration::ZERO,
561 );
562 let reg = ev.register();
563 let mut verdict = None;
564 for _ in 0..16 {
565 if let Some(o) = ev.evaluate(&window()) {
566 verdict = Some(o);
567 break;
568 }
569 }
570 let o = verdict.expect("a steady objective settles within the budget");
571 assert_eq!(o.disposition, Disposition::Interrupted);
572 assert_eq!(o.validity, Validity::Succeeded);
573 assert!(
574 (reg.load().value - 5.0).abs() < 1e-9,
575 "settled register reads 5.0"
576 );
577 }
578
579 #[test]
580 fn evaluator_yields_failed_on_settle_timeout() {
581 let mut ev = SettleEvaluator::new(
582 obj_kernel(RAMP_OBJ),
583 "obj",
584 "cycle",
585 settle_interp(),
586 Duration::from_millis(40),
587 Duration::ZERO,
588 );
589 // First pulse starts the clock; the ramp never settles.
590 assert!(
591 ev.evaluate(&window()).is_none(),
592 "no verdict before timeout"
593 );
594 std::thread::sleep(Duration::from_millis(55));
595 let o = ev.evaluate(&window()).expect("timeout fires a verdict");
596 assert_eq!(o.disposition, Disposition::Interrupted);
597 assert_eq!(
598 o.validity,
599 Validity::Failed,
600 "a settle timeout is the untrustworthy quadrant"
601 );
602 }
603
604 #[test]
605 fn viability_gate_withholds_settle_until_min_viable_elapses() {
606 // A steady objective is "stable" almost immediately, but the gate
607 // withholds the settle until `min_viable` of WALL-CLOCK has elapsed —
608 // so a windowed objective's rollup has cleared the prior coordinate /
609 // warmup transient before its value is trusted (the bug that let a
610 // sub-window concurrent eval latch a phantom score).
611 let mut ev = SettleEvaluator::new(
612 obj_kernel(STEADY_OBJ),
613 "obj",
614 "cycle",
615 settle_interp(),
616 Duration::from_secs(60),
617 Duration::from_millis(60),
618 );
619 // Many pulses arrive in a burst (as under concurrent scheduling): the
620 // objective is stable, but the gate holds because no real time passed.
621 for _ in 0..32 {
622 assert!(
623 ev.evaluate(&window()).is_none(),
624 "stable-but-gated: a burst of pulses must not settle before min_viable wall-clock"
625 );
626 }
627 std::thread::sleep(Duration::from_millis(70));
628 let o = ev
629 .evaluate(&window())
630 .expect("settles once min_viable has elapsed");
631 assert_eq!(o.disposition, Disposition::Interrupted);
632 assert_eq!(o.validity, Validity::Succeeded);
633 }
634
635 #[test]
636 fn detects_session_cumulative_reader_only() {
637 // `metric(...)` reads session_lifetime (cumulative across all
638 // coordinates) → flagged as un-gateable. `metric_window(...)` is
639 // a bounded windowed reader, and a plain objective reads nothing
640 // → neither is flagged.
641 let cum = compile_polydat_interpreter(r#"obj := metric("cycles_total, phase=p", "rate")"#)
642 .expect("metric node compiles");
643 assert!(program_reads_session_cumulative_metrics(cum.program()));
644
645 let win =
646 compile_polydat_interpreter(r#"obj := metric_window("cycles_total, phase=p", "rate")"#)
647 .expect("metric_window node compiles");
648 assert!(
649 !program_reads_session_cumulative_metrics(win.program()),
650 "metric_window is windowed, not session-cumulative"
651 );
652
653 let plain = compile_polydat_interpreter("obj := 5.0").expect("plain objective compiles");
654 assert!(!program_reads_session_cumulative_metrics(plain.program()));
655 }
656}