Skip to main content

nmbrs_runtime/
throttle.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Phase `throttle:` — the adaptive backpressure governor (SRD-83
5//! Part 9).
6//!
7//! A saturated target converts client overload into retry churn: the
8//! tries wrapper absorbs server rejections, `ok:%` stays green, and
9//! the only truthful signal is the ATTEMPT plane — the windowed
10//! attempt-failure fraction (`attempt_failure / resolved attempts`,
11//! the see-through-retries view).
12//!
13//! The governor assumes the MOST FRAGILE target by default and scales
14//! to robust ones, TCP-style:
15//!
16//! - **Slow-start.** The offered value begins at `start` (default:
17//!   `floor`) — the authored `concurrency:`/`rate:` is the CEILING,
18//!   not the opening offer. While no congestion has been seen, each
19//!   clean window DOUBLES the offer toward the ceiling: a robust
20//!   target climbs to full load in a handful of windows with zero
21//!   failures; a fragile one is never assaulted at all. A target
22//!   known to be robust at phase entry declares `start:` explicitly.
23//! - **Severity-proportional back-off.** Above `high`, the offer is
24//!   multiplied by `clamp(1 − frac, 0.25, 0.9)`: a marginal breach
25//!   trims gently (×0.9), total failure collapses fast (×0.25),
26//!   never below `floor`.
27//! - **Congestion memory.** Each back-off records the offer at which
28//!   failure was observed (`last_bad`). Recovery climbs ×1.5 through
29//!   the proven-safe zone (up to 75% of `last_bad`), then probes
30//!   ADDITIVELY (+max(1, 2% of `last_bad`) per clean window) — no
31//!   more marching multiplicatively back into the same wall.
32//!   [`MEMORY_CLEAR_STREAK`] CONSECUTIVE clean windows at-or-above
33//!   `last_bad` clear the memory (the target got healthier — warmed
34//!   caches, finished compactions), restoring the multiplicative
35//!   climb. One clean window is not evidence: the additive probes
36//!   keep stepping through the streak, so each window in it sits a
37//!   notch higher than the last, and a single quiet window at a
38//!   marginal congestion point can never re-arm the doubling climb
39//!   straight back into the wall.
40//!
41//! Windows are computed from counter DELTAS on the drain-loop tick —
42//! a true trailing window, never a lifetime average. Writes ride the
43//! push-on-set control path (`ControlOrigin::Governor`,
44//! confirmed-apply, spawned off the loop); every movement logs one
45//! line naming the signal — visible, never silent.
46//!
47//! Measurement honesty: the throttled steady state IS the
48//! measurement — the target's capacity at the declared failure
49//! bound. A load figure taken at high attempt-failure is a
50//! saturation artifact.
51
52use std::sync::Arc;
53use std::time::{Duration, Instant};
54
55use nmbrs_metrics::controls::{ControlOrigin, ErasedControl};
56
57/// All governor lines carry the `Throttle` category (in-flight —
58/// governance happens mid-body, attached to no boundary), so sinks
59/// and counters can dispatch on the axis instead of matching the
60/// rendered `throttle:` prefix.
61macro_rules! gov_log {
62    ($level:expr, $($arg:tt)*) => {
63        crate::observer::log_tagged(
64            $level,
65            crate::observer::EventTag::in_flight(
66                crate::observer::EventCategory::Throttle),
67            &format!($($arg)*),
68        )
69    };
70}
71
72/// What one window decided — pure, unit-testable.
73#[derive(Debug, Clone, Copy, PartialEq)]
74pub enum Decision {
75    /// Signal above `high`: back off to the contained value.
76    Down(f64),
77    /// Clean window with headroom: raise to the contained value.
78    Up(f64),
79    /// Hold (dead band, no traffic, or at a bound).
80    Hold,
81}
82
83/// Consecutive clean windows at-or-above the remembered congestion
84/// point required before the memory clears and the multiplicative
85/// climb resumes. Additive probing continues through the streak, so
86/// clearing means the target stayed clean across a rising run of
87/// offers, not one lucky window.
88pub const MEMORY_CLEAR_STREAK: u32 = 3;
89
90/// Pure congestion-memory step: fold one window's evidence (`clean
91/// at-or-above last_bad`) into the running streak. Returns the new
92/// streak and whether the memory clears on this window. Any window
93/// without that evidence — a breach, a dead-band hold, or a clean
94/// window still below the congestion point — resets the streak.
95pub fn memory_clear_step(streak: u32, evidence: bool) -> (u32, bool) {
96    if !evidence {
97        return (0, false);
98    }
99    let streak = streak + 1;
100    if streak >= MEMORY_CLEAR_STREAK {
101        (0, true)
102    } else {
103        (streak, false)
104    }
105}
106
107/// Pure governor step. `frac` is the windowed attempt-failure
108/// fraction, `current` the committed offer, `last_bad` the offer at
109/// which congestion was last observed (`None` = unexplored — slow
110/// start).
111pub fn decide(
112    frac: f64,
113    current: f64,
114    high: f64,
115    low: f64,
116    floor: f64,
117    ceiling: f64,
118    last_bad: Option<f64>,
119) -> Decision {
120    if frac > high {
121        // Severity-proportional multiplicative decrease: marginal
122        // breach trims ×0.9; total failure collapses ×0.25.
123        let target = (current * (1.0 - frac).clamp(0.25, 0.9)).max(floor);
124        if target < current {
125            return Decision::Down(target);
126        }
127        return Decision::Hold;
128    }
129    if frac < low && current < ceiling {
130        let target = match last_bad {
131            // Unexplored territory: slow-start doubling.
132            None => (current * 2.0).max(current + 1.0),
133            Some(bad) => {
134                // Fast reclimb through the proven-safe zone, then
135                // cautious additive probing toward the old wall.
136                let safe = (bad * 0.75).max(floor);
137                // A reclimb target less than one whole step above the
138                // committed value is no move at all on an integral
139                // control (fiber counts round it straight back), so it
140                // falls through to the additive probe: every clean
141                // window advances the offer by at least one.
142                let fast = (current * 1.5).min(safe);
143                if fast >= current + 1.0 {
144                    fast
145                } else {
146                    current + (bad * 0.02).max(1.0)
147                }
148            }
149        }
150        .min(ceiling);
151        if target > current {
152            return Decision::Up(target);
153        }
154    }
155    Decision::Hold
156}
157
158/// The per-phase governor: window bookkeeping over the activity's
159/// cumulative attempt counters plus the resolved control handle.
160pub struct ThrottleGovernor {
161    control: Arc<dyn ErasedControl>,
162    control_name: String,
163    phase_name: String,
164    high: f64,
165    low: f64,
166    floor: f64,
167    ceiling: f64,
168    start: f64,
169    window: Duration,
170    window_start: Instant,
171    base_success: u64,
172    base_failure: u64,
173    /// The offer at which congestion was last observed. `None` =
174    /// unexplored (slow-start regime).
175    last_bad: Option<f64>,
176    /// Consecutive clean windows observed at-or-above `last_bad`;
177    /// the memory clears at [`MEMORY_CLEAR_STREAK`].
178    clean_streak: u32,
179}
180
181impl ThrottleGovernor {
182    /// Resolve the governor from the phase's declared spec against the
183    /// attached component (where `Activity::attach_component` declared
184    /// the controls). Returns `None` — with a logged warning, never
185    /// silently — when the named control is not declared (e.g.
186    /// `control: rate` on a phase without `rate:`).
187    ///
188    /// Construction immediately publishes the slow-start offer to the
189    /// control (push-on-set), so the phase OPENS at `start`, not at
190    /// the authored ceiling; the caller also reads
191    /// [`Self::initial_concurrency`] to spawn the fiber pool at the
192    /// same offer.
193    pub fn from_spec(
194        spec: &nmbrs_workload::model::ThrottleSpec,
195        component: Option<&Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>>,
196        phase_name: &str,
197        authored_concurrency: usize,
198        authored_rate: Option<f64>,
199    ) -> Option<Self> {
200        let Some(component) = component else {
201            gov_log!(
202                crate::observer::LogLevel::Warn,
203                "phase '{phase_name}': throttle: no component attached — \
204                 governor disabled"
205            );
206            return None;
207        };
208        let control = component
209            .read()
210            .unwrap_or_else(|e| e.into_inner())
211            .find_control_erased_up(&spec.control);
212        let Some(control) = control else {
213            gov_log!(
214                crate::observer::LogLevel::Warn,
215                "phase '{phase_name}': throttle: control '{}' is not \
216                 declared on this phase — governor disabled \
217                 (`control: rate` needs a `rate:` on the phase)",
218                spec.control
219            );
220            return None;
221        };
222        let ceiling = match spec.control.as_str() {
223            "rate" => authored_rate.unwrap_or(f64::INFINITY),
224            _ => authored_concurrency as f64,
225        };
226        let start = spec.start.unwrap_or(spec.floor).clamp(
227            spec.floor,
228            if ceiling.is_finite() {
229                ceiling
230            } else {
231                f64::MAX
232            },
233        );
234        let window = nmbrs_workload::magnitude::parse_magnitude(&spec.window)
235            .map(Duration::from_secs_f64)
236            .or_else(|| {
237                crate::timeval::parse_time_ms(&spec.window)
238                    .ok()
239                    .map(Duration::from_millis)
240            })
241            .unwrap_or(Duration::from_secs(2));
242        let low = spec.low.unwrap_or(spec.high / 5.0);
243        gov_log!(
244            crate::observer::LogLevel::Info,
245            "phase '{phase_name}': throttle: governing '{}' — slow-start \
246             at {} toward ceiling {} (floor {}); back off above {:.1}% \
247             windowed attempt failure ({}), recover below {:.1}%",
248            spec.control,
249            fmt_val(start),
250            fmt_val(ceiling),
251            fmt_val(spec.floor),
252            spec.high * 100.0,
253            spec.window,
254            low * 100.0
255        );
256        let governor = Self {
257            control,
258            control_name: spec.control.clone(),
259            phase_name: phase_name.to_string(),
260            high: spec.high,
261            low,
262            floor: spec.floor,
263            ceiling,
264            start,
265            window,
266            window_start: Instant::now(),
267            base_success: 0,
268            base_failure: 0,
269            last_bad: None,
270            clean_streak: 0,
271        };
272        // Publish the opening offer so the control's committed value
273        // reflects the slow-start from the first cycle. (For a
274        // concurrency governor the caller ALSO spawns the pool at
275        // `initial_concurrency`, so the offer and the pool agree.)
276        if start < ceiling {
277            governor.write(start);
278        }
279        Some(governor)
280    }
281
282    /// The fiber count the activity should OPEN with when this
283    /// governor walks `concurrency` — the slow-start offer, not the
284    /// authored ceiling. `None` when the governor walks `rate` (the
285    /// pool spawns at the authored concurrency; the rate limiter
286    /// carries the slow-start instead).
287    pub fn initial_concurrency(&self) -> Option<usize> {
288        (self.control_name == "concurrency").then_some((self.start.max(1.0)) as usize)
289    }
290
291    /// Called every activity-loop pass with the CUMULATIVE attempt
292    /// counters; acts at most once per window. The control write is
293    /// push-on-set (spawned, confirmed-apply) — the loop never blocks.
294    pub fn tick(&mut self, attempt_success: u64, attempt_failure: u64) {
295        if self.window_start.elapsed() < self.window {
296            return;
297        }
298        let d_success = attempt_success.saturating_sub(self.base_success);
299        let d_failure = attempt_failure.saturating_sub(self.base_failure);
300        self.window_start = Instant::now();
301        self.base_success = attempt_success;
302        self.base_failure = attempt_failure;
303
304        let d_total = d_success + d_failure;
305        if d_total == 0 {
306            return;
307        }
308        let frac = d_failure as f64 / d_total as f64;
309        // The committed value is the truth to step from — external
310        // writers (TUI, web, control_set) are honored, not fought.
311        let Some(current) = self.control.gauge_f64() else {
312            return;
313        };
314
315        // A SUSTAINED run of clean windows at-or-above the remembered
316        // congestion point means the target got healthier (caches
317        // warm, compactions done): clear the memory and resume the
318        // multiplicative climb. One clean window at a marginal
319        // congestion point is noise, not evidence — the additive
320        // probes keep stepping through the streak, so clearing means
321        // the target stayed clean across a rising run of offers.
322        if let Some(bad) = self.last_bad {
323            let evidence = frac < self.low && current >= bad;
324            let (streak, clears) = memory_clear_step(self.clean_streak, evidence);
325            self.clean_streak = streak;
326            if clears {
327                gov_log!(
328                    crate::observer::LogLevel::Info,
329                    "throttle: phase '{}': {} consecutive clean windows at or \
330                     above prior congestion point {} (now at {}) — memory \
331                     cleared, resuming climb",
332                    self.phase_name,
333                    MEMORY_CLEAR_STREAK,
334                    fmt_val(bad),
335                    fmt_val(current)
336                );
337                self.last_bad = None;
338            } else if evidence {
339                gov_log!(
340                    crate::observer::LogLevel::Debug,
341                    "throttle: phase '{}': clean window at {} ≥ prior \
342                     congestion point {} ({streak}/{} toward clearing memory)",
343                    self.phase_name,
344                    fmt_val(current),
345                    fmt_val(bad),
346                    MEMORY_CLEAR_STREAK
347                );
348            }
349        }
350
351        match decide(
352            frac,
353            current,
354            self.high,
355            self.low,
356            self.floor,
357            self.ceiling,
358            self.last_bad,
359        ) {
360            Decision::Down(target) => {
361                gov_log!(
362                    crate::observer::LogLevel::Warn,
363                    "throttle: phase '{}': windowed attempt failure {:.1}% \
364                     ({d_failure}/{d_total} over {:.1}s) > {:.1}% — {} {} → {}",
365                    self.phase_name,
366                    frac * 100.0,
367                    self.window.as_secs_f64(),
368                    self.high * 100.0,
369                    self.control_name,
370                    fmt_val(current),
371                    fmt_val(target)
372                );
373                self.last_bad = Some(current);
374                self.write(target);
375            }
376            Decision::Up(target) => {
377                let mode = match self.last_bad {
378                    None => "climbing",
379                    Some(bad) if target < bad * 0.75 => "reclimbing",
380                    Some(_) => "probing",
381                };
382                gov_log!(
383                    crate::observer::LogLevel::Info,
384                    "throttle: phase '{}': windowed attempt failure {:.1}% \
385                     < {:.1}% — {mode} {} {} → {} (ceiling {})",
386                    self.phase_name,
387                    frac * 100.0,
388                    self.low * 100.0,
389                    self.control_name,
390                    fmt_val(current),
391                    fmt_val(target),
392                    fmt_val(self.ceiling)
393                );
394                self.write(target);
395            }
396            Decision::Hold => {}
397        }
398    }
399
400    fn write(&self, target: f64) {
401        let control = self.control.clone();
402        let origin = ControlOrigin::Governor {
403            source: format!("throttle:{}", self.phase_name),
404        };
405        let name = self.control_name.clone();
406        let phase = self.phase_name.clone();
407        tokio::spawn(async move {
408            if let Err(e) = control.set_f64(target, origin).await {
409                gov_log!(
410                    crate::observer::LogLevel::Warn,
411                    "throttle: phase '{phase}': write {name}={target} \
412                     failed: {e}"
413                );
414            }
415        });
416    }
417}
418
419fn fmt_val(v: f64) -> String {
420    if v.is_infinite() {
421        "∞".to_string()
422    } else if (v.fract()).abs() < 1e-9 {
423        format!("{}", v as i64)
424    } else {
425        format!("{v:.1}")
426    }
427}
428
429#[cfg(test)]
430mod tests {
431    use super::*;
432
433    /// Severity-proportional back-off: total failure collapses fast,
434    /// a marginal breach trims gently, the floor contains the walk.
435    #[test]
436    fn backoff_scales_with_severity() {
437        // 100% failure → ×0.25.
438        assert_eq!(
439            decide(1.0, 100.0, 0.05, 0.01, 1.0, 100.0, None),
440            Decision::Down(25.0)
441        );
442        // Marginal breach (7%) → ×0.9 trim.
443        assert_eq!(
444            decide(0.07, 100.0, 0.05, 0.01, 1.0, 100.0, None),
445            Decision::Down(90.0)
446        );
447        // Mid-severity (50%) → ×0.5.
448        assert_eq!(
449            decide(0.5, 40.0, 0.05, 0.01, 1.0, 100.0, None),
450            Decision::Down(20.0)
451        );
452        // The floor contains the collapse; at the floor, hold.
453        assert_eq!(
454            decide(1.0, 5.0, 0.05, 0.01, 4.0, 100.0, None),
455            Decision::Down(4.0)
456        );
457        assert_eq!(
458            decide(1.0, 4.0, 0.05, 0.01, 4.0, 100.0, None),
459            Decision::Hold
460        );
461    }
462
463    /// Unexplored territory (slow-start): clean windows DOUBLE the
464    /// offer toward the ceiling — a robust target reaches full load
465    /// in log2(ceiling/start) windows with zero failures.
466    #[test]
467    fn slow_start_doubles_while_clean() {
468        assert_eq!(
469            decide(0.0, 1.0, 0.05, 0.01, 1.0, 100.0, None),
470            Decision::Up(2.0)
471        );
472        assert_eq!(
473            decide(0.0, 8.0, 0.05, 0.01, 1.0, 100.0, None),
474            Decision::Up(16.0)
475        );
476        // Ceiling contains the climb; at the ceiling, hold.
477        assert_eq!(
478            decide(0.0, 64.0, 0.05, 0.01, 1.0, 100.0, None),
479            Decision::Up(100.0)
480        );
481        assert_eq!(
482            decide(0.0, 100.0, 0.05, 0.01, 1.0, 100.0, None),
483            Decision::Hold
484        );
485    }
486
487    /// After congestion at `last_bad`, recovery climbs ×1.5 only
488    /// through the proven-safe zone (75% of last_bad), then probes
489    /// additively — never a multiplicative march back into the wall.
490    #[test]
491    fn congestion_memory_gates_the_reclimb() {
492        // Fast reclimb below the safe zone, capped at it.
493        assert_eq!(
494            decide(0.0, 10.0, 0.05, 0.01, 1.0, 100.0, Some(40.0)),
495            Decision::Up(15.0)
496        );
497        assert_eq!(
498            decide(0.0, 24.0, 0.05, 0.01, 1.0, 100.0, Some(40.0)),
499            Decision::Up(30.0)
500        ); // capped at 40*0.75
501        // At/above the safe zone: additive probing only.
502        assert_eq!(
503            decide(0.0, 30.0, 0.05, 0.01, 1.0, 100.0, Some(40.0)),
504            Decision::Up(31.0)
505        ); // + max(1, 40*0.02)
506        // Large-scale controls probe proportionally (+2% of bad).
507        assert_eq!(
508            decide(0.0, 40_000.0, 0.05, 0.01, 1.0, 100_000.0, Some(50_000.0)),
509            Decision::Up(41_000.0)
510        );
511    }
512
513    /// Congestion memory clears only on a sustained streak of clean
514    /// windows at-or-above the congestion point; any window without
515    /// that evidence resets the streak.
516    #[test]
517    fn memory_clears_on_a_sustained_clean_streak() {
518        assert_eq!(memory_clear_step(0, true), (1, false));
519        assert_eq!(memory_clear_step(1, true), (2, false));
520        assert_eq!(memory_clear_step(2, true), (0, true));
521        // A breach, a dead-band hold, or a clean window still below
522        // the congestion point resets the streak.
523        assert_eq!(memory_clear_step(2, false), (0, false));
524        assert_eq!(memory_clear_step(0, false), (0, false));
525    }
526
527    /// A reclimb capped less than one step above the committed value
528    /// (safe zone 8.2 over a committed 8) is no move on an integral
529    /// control; the additive probe takes over so the offer never
530    /// wedges (observed live: `8 → 8.2` every window, forever).
531    #[test]
532    fn reclimb_never_wedges_below_one_step() {
533        assert_eq!(
534            decide(0.0, 8.0, 0.05, 0.01, 1.0, 100.0, Some(10.93)),
535            Decision::Up(9.0)
536        );
537    }
538
539    /// The dead band between `low` and `high` holds — no hunting
540    /// around the operating point.
541    #[test]
542    fn dead_band_holds() {
543        assert_eq!(
544            decide(0.03, 50.0, 0.05, 0.01, 4.0, 100.0, None),
545            Decision::Hold
546        );
547        assert_eq!(
548            decide(0.03, 50.0, 0.05, 0.01, 4.0, 100.0, Some(60.0)),
549            Decision::Hold
550        );
551    }
552}