Skip to main content

ftui_render/
budget.rs

1#![forbid(unsafe_code)]
2
3//! Render budget enforcement with graceful degradation.
4//!
5//! This module provides time-based budget tracking for frame rendering,
6//! enabling the system to gracefully degrade visual fidelity when
7//! performance budgets are exceeded.
8//!
9//! # Overview
10//!
11//! Agent UIs receive unpredictable content (burst log output, large tool responses).
12//! A frozen UI during burst input makes the agent feel broken. Users tolerate
13//! reduced visual fidelity; they do NOT tolerate hangs.
14//!
15//! # Usage
16//!
17//! ```
18//! use ftui_render::budget::{RenderBudget, DegradationLevel, FrameBudgetConfig};
19//! use std::time::Duration;
20//!
21//! // Create a budget with 16ms total (60fps target)
22//! let mut budget = RenderBudget::new(Duration::from_millis(16));
23//!
24//! // Check remaining time
25//! let remaining = budget.remaining();
26//!
27//! // Check if we should degrade for an expensive operation
28//! if budget.should_degrade(Duration::from_millis(5)) {
29//!     budget.degrade();
30//! }
31//!
32//! // Render at current degradation level
33//! match budget.degradation() {
34//!     DegradationLevel::Full => { /* full rendering */ }
35//!     DegradationLevel::SimpleBorders => { /* ASCII borders */ }
36//!     _ => { /* further degradation */ }
37//! }
38//! ```
39
40use web_time::{Duration, Instant};
41
42#[cfg(feature = "tracing")]
43use tracing::{trace, warn};
44
45// ---------------------------------------------------------------------------
46// Budget Controller: PID + E-Process-Style Gate (Heuristic Plug-In)
47// ---------------------------------------------------------------------------
48
49/// PID controller gains for frame time regulation.
50///
51/// # Mathematical Model
52///
53/// Let `e_t = (frame_time_t − target) / target` be the normalized error signal
54/// at frame `t` (positive when over budget).
55///
56/// The PID control output is:
57///
58/// ```text
59/// u_t = Kp * e_t  +  Ki * Σ_{j=0..t} e_j  +  Kd * (e_t − e_{t−1})
60/// ```
61///
62/// The output `u_t` maps to degradation level adjustments:
63/// - `u_t > degrade_threshold` → degrade one level (if e-process permits)
64/// - `u_t < -upgrade_threshold` → upgrade one level
65/// - otherwise → hold current level
66///
67/// # Gain Selection Rationale
68///
69/// For a 16ms target (60fps):
70/// - `Kp = 0.5`: Proportional response. Moderate gain avoids oscillation
71///   while still reacting to single-frame overruns.
72/// - `Ki = 0.05`: Integral term. Low gain eliminates steady-state error
73///   over ~20 frames without integral windup issues.
74/// - `Kd = 0.2`: Derivative term. Provides anticipatory damping to reduce
75///   overshoot when frame times are trending upward.
76///
77/// # Stability Analysis
78///
79/// For a first-order plant model G(s) = 1/(τs + 1) with τ ≈ 1 frame:
80/// - Phase margin > 45° with these gains
81/// - Gain margin > 6dB
82/// - Settling time ≈ 8-12 frames for a step disturbance
83///
84/// Anti-windup: integral term is clamped to `[-integral_max, +integral_max]`
85/// to prevent runaway accumulation during sustained overload.
86#[derive(Debug, Clone, PartialEq)]
87pub struct PidGains {
88    /// Proportional gain. Reacts to current error magnitude.
89    pub kp: f64,
90    /// Integral gain. Eliminates steady-state error over time.
91    pub ki: f64,
92    /// Derivative gain. Dampens oscillations by reacting to error rate.
93    pub kd: f64,
94    /// Maximum absolute value of the integral accumulator (anti-windup).
95    pub integral_max: f64,
96}
97
98impl Default for PidGains {
99    fn default() -> Self {
100        Self {
101            kp: 0.5,
102            ki: 0.05,
103            kd: 0.2,
104            integral_max: 5.0,
105        }
106    }
107}
108
109/// Internal PID controller state.
110///
111/// Tracks the error integral and previous error for derivative computation.
112#[derive(Debug, Clone)]
113struct PidState {
114    /// Accumulated integral of error (clamped by `integral_max`).
115    integral: f64,
116    /// Previous frame's error value (for derivative).
117    prev_error: f64,
118    /// Last proportional term (for telemetry).
119    last_p: f64,
120    /// Last integral term (for telemetry).
121    last_i: f64,
122    /// Last derivative term (for telemetry).
123    last_d: f64,
124}
125
126impl Default for PidState {
127    fn default() -> Self {
128        Self {
129            integral: 0.0,
130            prev_error: 0.0,
131            last_p: 0.0,
132            last_i: 0.0,
133            last_d: 0.0,
134        }
135    }
136}
137
138impl PidState {
139    /// Compute PID output for the current error and update internal state.
140    ///
141    /// Returns the control signal `u_t`.
142    fn update(&mut self, error: f64, gains: &PidGains) -> f64 {
143        if error.is_nan() {
144            return 0.0;
145        }
146        // Integral with anti-windup clamping
147        self.integral = (self.integral + error).clamp(-gains.integral_max, gains.integral_max);
148
149        // Derivative (first-frame uses zero derivative)
150        let derivative = error - self.prev_error;
151        self.prev_error = error;
152
153        // Record individual PID terms for telemetry
154        self.last_p = gains.kp * error;
155        self.last_i = gains.ki * self.integral;
156        self.last_d = gains.kd * derivative;
157
158        // PID output
159        self.last_p + self.last_i + self.last_d
160    }
161
162    /// Reset controller state (e.g., after a mode change).
163    fn reset(&mut self) {
164        *self = Self::default();
165    }
166}
167
168/// E-process-style evidence accumulator for gating degradation decisions.
169///
170/// # Mathematical Model
171///
172/// Inspired by anytime-valid e-processes; the accumulator is
173///
174/// ```text
175/// E_t = Π_{j=1..t} exp(λ * r_j − λ² / 2)
176/// ```
177///
178/// where:
179/// - `r_j` is the standardized residual at frame j: `(frame_time − target) / σ̂`
180/// - `σ̂` is an EMA of *absolute* deviation (≈ 0.8σ for Gaussian noise),
181///   measured against the already-updated EMA mean of frame times
182/// - `λ` is a tuning parameter controlling sensitivity (default: 0.5)
183///
184/// # Decision Rule
185///
186/// - **Degrade** only when `E_t > 1/α` (evidence exceeds threshold).
187///   Default α = 0.05, so we need `E_t > 20`.
188/// - **Upgrade** only when `E_t < β` (evidence that overload has passed).
189///   Default β = 0.5.
190///
191/// # Properties
192///
193/// 1. **Check-every-frame**: The gate can be evaluated after every frame;
194///    thresholds are tuned empirically rather than by fixed-sample theory.
195/// 2. **Heuristic threshold, not a formal α-bound**: because σ̂ is a
196///    mean-absolute-deviation EMA (biased low vs. true σ), residuals are
197///    inflated and `E_t` drifts upward slightly even under healthy jitter,
198///    so Ville's inequality `P(E_t > 1/α | H₀) ≤ α` does NOT formally hold.
199///    In practice this makes the gate a little more eager to degrade than
200///    the α suggests, which errs on the fail-safe side. Treat `alpha` as a
201///    tuning knob, not a guaranteed false-positive rate.
202/// 3. **Self-correcting**: After a burst passes, E_t decays back toward 1.0,
203///    naturally enabling recovery.
204///
205/// # Failure Modes
206///
207/// - **Sustained overload**: E_t grows exponentially → rapid degradation.
208/// - **Transient spike**: E_t grows briefly → may not cross threshold →
209///   PID handles short-term. Only persistent overload triggers e-process gate.
210/// - **σ estimation drift**: We use an exponential moving average for σ with
211///   a warmup period of 10 frames to avoid unstable early estimates.
212#[derive(Debug, Clone, PartialEq)]
213pub struct EProcessConfig {
214    /// Initial/baseline sensitivity parameter λ. Higher values detect overload faster
215    /// but increase false positive risk near the boundary.
216    /// Default: 0.5.
217    pub lambda: f64,
218    /// Whether to adapt λ online via the Gaussian-form GRAPA update
219    /// `λ_{t+1} = clamp(λ_t + η (r_t − λ_t), λ_min, λ_max)`.
220    /// Default: true.
221    pub adaptive_lambda: bool,
222    /// Step size η for Gaussian-form GRAPA adaptation of λ.
223    /// Default: 0.1.
224    pub grapa_eta: f64,
225    /// Lower bound on the betting fraction λ.
226    /// Default: 0.05.
227    pub lambda_min: f64,
228    /// Upper bound on the betting fraction λ.
229    /// Default: 2.0.
230    pub lambda_max: f64,
231    /// Significance level α. Degrade when E_t > 1/α.
232    /// Default: 0.05 (need E_t > 20 to degrade).
233    pub alpha: f64,
234    /// Recovery threshold β. Upgrade allowed when E_t < β.
235    /// Default: 0.5.
236    pub beta: f64,
237    /// EMA decay for σ estimation. Closer to 1.0 = slower adaptation.
238    /// Default: 0.9 (adapts over ~10 frames).
239    pub sigma_ema_decay: f64,
240    /// Minimum σ floor to prevent division by zero.
241    /// Default: 1.0 ms.
242    pub sigma_floor_ms: f64,
243    /// Warmup frame threshold before e-process degradation activates.
244    ///
245    /// Because `frames_observed` is incremented before the gate check,
246    /// `should_degrade` returns `false` while `frames_observed < warmup_frames`
247    /// (the first `warmup_frames - 1` observations) so cold-start jitter cannot
248    /// trigger degradation before `sigma_ema` calibrates, and activates on the
249    /// `warmup_frames`-th observation. `should_upgrade` returns `true` during
250    /// warmup so PID-driven recovery remains permitted.
251    /// Default: 10.
252    pub warmup_frames: u32,
253}
254
255impl Default for EProcessConfig {
256    fn default() -> Self {
257        Self {
258            lambda: 0.5,
259            adaptive_lambda: true,
260            grapa_eta: 0.1,
261            lambda_min: 0.05,
262            lambda_max: 2.0,
263            alpha: 0.05,
264            beta: 0.5,
265            sigma_ema_decay: 0.9,
266            sigma_floor_ms: 1.0,
267            warmup_frames: 10,
268        }
269    }
270}
271
272/// Internal e-process state.
273#[derive(Debug, Clone)]
274struct EProcessState {
275    /// Current e-process value E_t (starts at 1.0).
276    e_value: f64,
277    /// Current predictable betting fraction λ_t (initialized from `config.lambda`).
278    ///
279    /// Invariant: at frame `t`, `update()` uses the `lambda` stored at the end of
280    /// frame `t - 1` (measurable before observing `r_t`) to update `e_value`, and
281    /// only then adapts `lambda` for frame `t + 1`.
282    lambda: f64,
283    /// EMA estimate of frame time standard deviation (ms).
284    sigma_ema: f64,
285    /// EMA estimate of mean frame time (ms) for residual computation.
286    mean_ema: f64,
287    /// Frames observed so far.
288    frames_observed: u32,
289}
290
291impl Default for EProcessState {
292    fn default() -> Self {
293        Self {
294            e_value: 1.0,
295            lambda: EProcessConfig::default().lambda,
296            sigma_ema: 0.0,
297            mean_ema: 0.0,
298            frames_observed: 0,
299        }
300    }
301}
302
303impl EProcessState {
304    fn new(config: &EProcessConfig) -> Self {
305        Self {
306            lambda: config.lambda,
307            ..Self::default()
308        }
309    }
310
311    /// Update the e-process with a new frame time observation.
312    ///
313    /// Uses the current predictable betting fraction `self.lambda` ($\lambda_{t-1}$)
314    /// to update $E_t = E_{t-1} \exp(\lambda_{t-1} r_t - \lambda_{t-1}^2 / 2)$, and
315    /// then (when `config.adaptive_lambda` is enabled and warmup has completed)
316    /// applies the Gaussian-form GRAPA gradient step:
317    ///
318    /// $$\frac{\partial}{\partial \lambda}\left(\lambda r_t - \frac{\lambda^2}{2}\right) = r_t - \lambda_t
319    ///   \implies \lambda_t = \mathrm{clamp}(\lambda_{t-1} + \eta (r_t - \lambda_{t-1}), \lambda_{\min}, \lambda_{\max})$$
320    ///
321    /// generalizing the Bernoulli GRAPA update in `ftui_runtime::eprocess_throttle`
322    /// (`grad = (x_t - μ_0) / (1 + λ(x_t - μ_0))`) to standardized sub-Gaussian residuals.
323    ///
324    /// Returns the updated E_t value.
325    fn update(&mut self, frame_time_ms: f64, target_ms: f64, config: &EProcessConfig) -> f64 {
326        self.frames_observed = self.frames_observed.saturating_add(1);
327
328        // Update mean EMA
329        if self.frames_observed == 1 {
330            self.mean_ema = frame_time_ms;
331            self.sigma_ema = config.sigma_floor_ms;
332            self.lambda = config.lambda;
333        } else {
334            let decay = config.sigma_ema_decay;
335            self.mean_ema = decay * self.mean_ema + (1.0 - decay) * frame_time_ms;
336            // Update sigma EMA using absolute deviation as proxy
337            let deviation = (frame_time_ms - self.mean_ema).abs();
338            self.sigma_ema = decay * self.sigma_ema + (1.0 - decay) * deviation;
339        }
340
341        if !config.adaptive_lambda {
342            self.lambda = config.lambda;
343        }
344
345        // Floor sigma to prevent instability
346        let sigma = self.sigma_ema.max(config.sigma_floor_ms);
347
348        // Compute standardized residual
349        let residual = (frame_time_ms - target_ms) / sigma;
350
351        // E-process multiplicative update (predictable betting: uses λ_{t-1}
352        // measurable at time t-1 before observing r_t):
353        // E_t = E_{t-1} * exp(λ_{t-1} * r_t − λ_{t-1}² * σ² / 2)
354        // Since r_t is already standardized, σ in the exponent is 1.0.
355        let lambda = self.lambda;
356        let log_factor = lambda * residual - lambda * lambda / 2.0;
357        if !log_factor.is_nan() {
358            self.e_value *= log_factor.exp();
359            // Clamp to avoid numerical issues (but preserve the supermartingale property
360            // by allowing it to grow large or shrink small).
361            self.e_value = self.e_value.clamp(1e-10, 1e10);
362        }
363
364        // Adapt λ for step t+1 after computing E_t (no adaptation during warmup frames).
365        // While accumulated overload evidence E_t > 1.0 is draining, keep λ >= config.lambda
366        // so negative residuals during recovery drain E_t back below β promptly.
367        if config.adaptive_lambda
368            && self.frames_observed >= config.warmup_frames
369            && !residual.is_nan()
370        {
371            let lo = config.lambda_min.min(config.lambda_max);
372            let hi = config.lambda_max.max(config.lambda_min);
373            let effective_min = if self.e_value > 1.0 && residual < 0.0 {
374                config.lambda.clamp(lo, hi)
375            } else {
376                lo
377            };
378            self.lambda = (self.lambda + config.grapa_eta * (residual - self.lambda))
379                .clamp(effective_min, hi);
380        }
381
382        #[cfg(feature = "tracing")]
383        trace!(
384            target: ftui_core::TARGET_EPROCESS,
385            lambda = self.lambda,
386            e_value = self.e_value,
387            residual,
388            "e-process update"
389        );
390
391        self.e_value
392    }
393
394    /// Check if evidence supports degradation.
395    fn should_degrade(&self, config: &EProcessConfig) -> bool {
396        if self.frames_observed < config.warmup_frames {
397            return false; // Suppress degradation while sigma_ema calibrates during warmup
398        }
399        self.e_value > 1.0 / config.alpha
400    }
401
402    /// Check if evidence supports upgrade (overload has passed).
403    fn should_upgrade(&self, config: &EProcessConfig) -> bool {
404        if self.frames_observed < config.warmup_frames {
405            return true; // Allow PID-driven upgrades during warmup
406        }
407        self.e_value < config.beta
408    }
409
410    /// Reset state.
411    fn reset(&mut self, config: &EProcessConfig) {
412        *self = Self::new(config);
413    }
414}
415
416/// Configuration for the adaptive budget controller.
417#[derive(Debug, Clone, PartialEq)]
418pub struct BudgetControllerConfig {
419    /// PID controller gains.
420    pub pid: PidGains,
421    /// E-process configuration.
422    pub eprocess: EProcessConfig,
423    /// Target frame time.
424    pub target: Duration,
425    /// Hysteresis: PID output must exceed this to trigger degradation.
426    ///
427    /// This prevents oscillation at the boundary. The value is in
428    /// normalized units (error / target). Default: 0.3 (30% of target).
429    ///
430    /// # Justification
431    ///
432    /// A threshold of 0.3 means the controller needs ~5ms sustained error
433    /// at 16ms target before degrading. This filters out single-frame jitter
434    /// while remaining responsive to genuine overload (2-3 consecutive
435    /// slow frames will cross the threshold via integral accumulation).
436    pub degrade_threshold: f64,
437    /// Hysteresis: PID output must be below negative of this to trigger upgrade.
438    /// Default: 0.2 (20% of target).
439    pub upgrade_threshold: f64,
440    /// Cooldown frames between level changes.
441    ///
442    /// A value of `N` keeps transitions at least `N` frames apart. Since
443    /// decisions are made once per frame, `0` and `1` are equivalent (no
444    /// extra spacing beyond the per-frame cadence).
445    pub cooldown_frames: u32,
446    /// Minimum quality floor: the controller will never degrade past this level.
447    ///
448    /// Default: `DegradationLevel::SimpleBorders` — preserves readable text
449    /// content while still allowing border simplification.
450    ///
451    /// Setting this to `DegradationLevel::Full` disables all degradation.
452    /// Setting this to `DegradationLevel::SkipFrame` effectively removes the floor.
453    pub degradation_floor: DegradationLevel,
454}
455
456impl Default for BudgetControllerConfig {
457    fn default() -> Self {
458        Self {
459            pid: PidGains::default(),
460            eprocess: EProcessConfig::default(),
461            target: Duration::from_millis(16),
462            degrade_threshold: 0.3,
463            upgrade_threshold: 0.2,
464            cooldown_frames: 3,
465            degradation_floor: DegradationLevel::SimpleBorders,
466        }
467    }
468}
469
470/// Adaptive budget controller combining PID regulation with e-process gating.
471///
472/// # Architecture
473///
474/// ```text
475/// frame_time ─┬─► PID Controller ─► control signal u_t
476///             │                              │
477///             └─► E-Process ──────► gate ────┤
478///                                            ▼
479///                                    Decision Logic
480///                                    ┌───────────────┐
481///                                    │ u_t > thresh   │──► DEGRADE (if e-process permits)
482///                                    │ u_t < -thresh  │──► UPGRADE (if e-process permits)
483///                                    │ otherwise      │──► HOLD
484///                                    └───────────────┘
485/// ```
486///
487/// The PID controller provides smooth, reactive adaptation. The e-process
488/// gates decisions to ensure statistical validity — we only degrade when
489/// there is strong evidence of sustained overload, not just transient spikes.
490///
491/// # Usage
492///
493/// ```rust
494/// use ftui_render::budget::{BudgetController, BudgetControllerConfig, DegradationLevel};
495/// use std::time::Duration;
496///
497/// let mut controller = BudgetController::new(BudgetControllerConfig::default());
498///
499/// // After each frame, feed the observed frame time:
500/// let decision = controller.update(Duration::from_millis(20)); // slow frame
501/// // decision tells you what to do: Hold, Degrade, or Upgrade
502/// ```
503#[derive(Debug, Clone)]
504pub struct BudgetController {
505    config: BudgetControllerConfig,
506    pid: PidState,
507    eprocess: EProcessState,
508    current_level: DegradationLevel,
509    frames_since_change: u32,
510    last_pid_output: f64,
511    last_decision: BudgetDecision,
512    last_decision_reason: BudgetDecisionReason,
513    last_frame_ms: f64,
514    transition_seq: u64,
515    last_transition_correlation_id: u64,
516    last_pid_gate_threshold: f64,
517    last_pid_gate_margin: f64,
518    last_evidence_threshold: f64,
519    last_evidence_margin: f64,
520    recovery_streak: u32,
521    total_degrades: u64,
522    total_recoveries: u64,
523}
524
525/// Decision output from the budget controller.
526#[derive(Debug, Clone, Copy, PartialEq, Eq)]
527pub enum BudgetDecision {
528    /// Maintain current degradation level.
529    Hold,
530    /// Degrade one level (reduce visual fidelity).
531    Degrade,
532    /// Upgrade one level (restore visual fidelity).
533    Upgrade,
534}
535
536impl BudgetDecision {
537    /// JSONL-compatible string representation.
538    #[inline]
539    pub fn as_str(self) -> &'static str {
540        match self {
541            Self::Hold => "stay",
542            Self::Degrade => "degrade",
543            Self::Upgrade => "upgrade",
544        }
545    }
546}
547
548/// Version tag for budget telemetry schema emitted by [`BudgetTelemetry`].
549pub const BUDGET_TELEMETRY_SCHEMA_VERSION: u16 = 1;
550
551/// Controller rationale for a per-frame decision.
552#[derive(Debug, Clone, Copy, PartialEq, Eq)]
553pub enum BudgetDecisionReason {
554    /// No decision change while cooldown is active.
555    CooldownActive,
556    /// Overload + evidence gate passed, so degrade one level.
557    OverloadEvidencePassed,
558    /// Underload + evidence gate passed, so upgrade one level.
559    UnderloadEvidencePassed,
560    /// Already at maximum degradation; cannot degrade further.
561    AtMaxDegradation,
562    /// Already at the configured degradation floor; policy forbids degrading further.
563    AtDegradationFloor,
564    /// Already at full quality; cannot upgrade further.
565    AtFullQuality,
566    /// Overload signal present but e-process degrade gate not satisfied.
567    OverloadEvidenceInsufficient,
568    /// Underload signal present but e-process upgrade gate not satisfied.
569    UnderloadEvidenceInsufficient,
570    /// PID output remained in the hold band.
571    WithinThresholdBand,
572}
573
574impl BudgetDecisionReason {
575    /// Stable string code for JSONL logs and CI parsing.
576    #[inline]
577    pub fn as_str(self) -> &'static str {
578        match self {
579            Self::CooldownActive => "cooldown_active",
580            Self::OverloadEvidencePassed => "overload_evidence_passed",
581            Self::UnderloadEvidencePassed => "underload_evidence_passed",
582            Self::AtMaxDegradation => "at_max_degradation",
583            Self::AtDegradationFloor => "at_degradation_floor",
584            Self::AtFullQuality => "at_full_quality",
585            Self::OverloadEvidenceInsufficient => "overload_evidence_insufficient",
586            Self::UnderloadEvidenceInsufficient => "underload_evidence_insufficient",
587            Self::WithinThresholdBand => "within_threshold_band",
588        }
589    }
590}
591
592impl BudgetController {
593    /// Create a new budget controller with the given configuration.
594    pub fn new(config: BudgetControllerConfig) -> Self {
595        let eprocess = EProcessState::new(&config.eprocess);
596        Self {
597            config,
598            pid: PidState::default(),
599            eprocess,
600            current_level: DegradationLevel::Full,
601            frames_since_change: 0,
602            last_pid_output: 0.0,
603            last_decision: BudgetDecision::Hold,
604            last_decision_reason: BudgetDecisionReason::WithinThresholdBand,
605            last_frame_ms: 0.0,
606            transition_seq: 0,
607            last_transition_correlation_id: 0,
608            last_pid_gate_threshold: 0.0,
609            last_pid_gate_margin: 0.0,
610            last_evidence_threshold: 0.0,
611            last_evidence_margin: 0.0,
612            recovery_streak: 0,
613            total_degrades: 0,
614            total_recoveries: 0,
615        }
616    }
617
618    /// Feed a frame time observation and get a decision.
619    ///
620    /// Call this once per frame with the measured frame duration.
621    pub fn update(&mut self, frame_time: Duration) -> BudgetDecision {
622        let target_ms = self.config.target.as_secs_f64() * 1000.0;
623        let frame_ms = frame_time.as_secs_f64() * 1000.0;
624
625        // Compute normalized error (positive = over budget)
626        let error = (frame_ms - target_ms) / target_ms;
627
628        // Update PID
629        let u = self.pid.update(error, &self.config.pid);
630        self.last_pid_output = u;
631        self.last_frame_ms = frame_ms;
632
633        // Update e-process
634        self.eprocess
635            .update(frame_ms, target_ms, &self.config.eprocess);
636
637        // Track recovery streak: consecutive upgrade-eligible frames
638        if u < -self.config.upgrade_threshold {
639            self.recovery_streak = self.recovery_streak.saturating_add(1);
640        } else {
641            self.recovery_streak = 0;
642        }
643
644        // Increment cooldown counter
645        self.frames_since_change = self.frames_since_change.saturating_add(1);
646
647        let mut decision = BudgetDecision::Hold;
648        let mut reason = BudgetDecisionReason::WithinThresholdBand;
649        let mut pid_gate_threshold = 0.0;
650        let mut pid_gate_margin = 0.0;
651        let mut evidence_threshold = 0.0;
652        let mut evidence_margin = 0.0;
653
654        // Decision logic with hysteresis + e-process gating + explainable reason/evidence.
655        if self.frames_since_change < self.config.cooldown_frames {
656            reason = BudgetDecisionReason::CooldownActive;
657        } else if u > self.config.degrade_threshold {
658            pid_gate_threshold = self.config.degrade_threshold;
659            pid_gate_margin = u - pid_gate_threshold;
660            evidence_threshold = 1.0 / self.config.eprocess.alpha;
661            evidence_margin = self.eprocess.e_value - evidence_threshold;
662
663            if self.current_level.is_max() {
664                reason = BudgetDecisionReason::AtMaxDegradation;
665            } else if self.current_level >= self.config.degradation_floor {
666                reason = BudgetDecisionReason::AtDegradationFloor;
667            } else if self.eprocess.should_degrade(&self.config.eprocess) {
668                decision = BudgetDecision::Degrade;
669                reason = BudgetDecisionReason::OverloadEvidencePassed;
670            } else {
671                reason = BudgetDecisionReason::OverloadEvidenceInsufficient;
672            }
673        } else if u < -self.config.upgrade_threshold {
674            pid_gate_threshold = -self.config.upgrade_threshold;
675            pid_gate_margin = (-u) - self.config.upgrade_threshold;
676            evidence_threshold = self.config.eprocess.beta;
677            evidence_margin = evidence_threshold - self.eprocess.e_value;
678
679            if self.current_level.is_full() {
680                reason = BudgetDecisionReason::AtFullQuality;
681            } else if self.eprocess.should_upgrade(&self.config.eprocess) {
682                decision = BudgetDecision::Upgrade;
683                reason = BudgetDecisionReason::UnderloadEvidencePassed;
684            } else {
685                reason = BudgetDecisionReason::UnderloadEvidenceInsufficient;
686            }
687        }
688
689        // Record decision for telemetry
690        self.last_decision = decision;
691        self.last_decision_reason = reason;
692        self.last_pid_gate_threshold = pid_gate_threshold;
693        self.last_pid_gate_margin = pid_gate_margin;
694        self.last_evidence_threshold = evidence_threshold;
695        self.last_evidence_margin = evidence_margin;
696
697        // Apply decision
698        match decision {
699            BudgetDecision::Degrade => {
700                self.transition_seq = self.transition_seq.saturating_add(1);
701                self.last_transition_correlation_id =
702                    (self.transition_seq << 32) ^ u64::from(self.eprocess.frames_observed);
703                let next = self.current_level.next();
704                // Clamp to degradation floor: never degrade past the configured minimum quality.
705                self.current_level = if next > self.config.degradation_floor {
706                    self.config.degradation_floor
707                } else {
708                    next
709                };
710                self.frames_since_change = 0;
711                self.recovery_streak = 0;
712                self.total_degrades = self.total_degrades.saturating_add(1);
713
714                #[cfg(feature = "tracing")]
715                warn!(
716                    level = self.current_level.as_str(),
717                    pid_output = u,
718                    e_value = self.eprocess.e_value,
719                    "budget controller: degrade"
720                );
721            }
722            BudgetDecision::Upgrade => {
723                self.transition_seq = self.transition_seq.saturating_add(1);
724                self.last_transition_correlation_id =
725                    (self.transition_seq << 32) ^ u64::from(self.eprocess.frames_observed);
726                self.current_level = self.current_level.prev();
727                self.frames_since_change = 0;
728                self.total_recoveries = self.total_recoveries.saturating_add(1);
729
730                #[cfg(feature = "tracing")]
731                trace!(
732                    level = self.current_level.as_str(),
733                    pid_output = u,
734                    e_value = self.eprocess.e_value,
735                    "budget controller: upgrade"
736                );
737            }
738            BudgetDecision::Hold => {}
739        }
740
741        decision
742    }
743
744    /// Get the current degradation level.
745    #[inline]
746    pub fn level(&self) -> DegradationLevel {
747        self.current_level
748    }
749
750    /// Synchronize the controller's level with an externally applied change.
751    ///
752    /// [`RenderBudget`] calls this whenever its degradation level is mutated
753    /// outside the controller's own decision (guardrail emergencies, the
754    /// conformal risk gate, manual `set_degradation`). Without it the
755    /// controller keeps reasoning from a stale level: believing it is at
756    /// `Full` it reports `AtFullQuality` and holds forever, so an externally
757    /// degraded UI never recovers, and its floor clamp computes from the
758    /// wrong base. Starts a cooldown window, since a transition just
759    /// happened.
760    pub fn sync_level(&mut self, level: DegradationLevel) {
761        if self.current_level != level {
762            if level > self.current_level {
763                self.recovery_streak = 0;
764            }
765            self.current_level = level;
766            self.frames_since_change = 0;
767        }
768    }
769
770    /// Get the current recovery streak (consecutive upgrade-eligible frames).
771    #[inline]
772    pub fn recovery_streak(&self) -> u32 {
773        self.recovery_streak
774    }
775
776    /// Total degrade events enacted by the controller.
777    #[inline]
778    pub fn total_degrades(&self) -> u64 {
779        self.total_degrades
780    }
781
782    /// Total recovery (upgrade) events enacted by the controller.
783    #[inline]
784    pub fn total_recoveries(&self) -> u64 {
785        self.total_recoveries
786    }
787
788    /// Get the current e-process value (for diagnostics/logging).
789    #[inline]
790    pub fn e_value(&self) -> f64 {
791        self.eprocess.e_value
792    }
793
794    /// Get the current e-process predictable betting fraction λ (for diagnostics/logging).
795    #[inline]
796    pub fn eprocess_lambda(&self) -> f64 {
797        self.eprocess.lambda
798    }
799
800    /// Get the current e-process sigma estimate (ms).
801    #[inline]
802    pub fn eprocess_sigma_ms(&self) -> f64 {
803        self.eprocess
804            .sigma_ema
805            .max(self.config.eprocess.sigma_floor_ms)
806    }
807
808    /// Get the current PID integral term (for diagnostics/logging).
809    #[inline]
810    pub fn pid_integral(&self) -> f64 {
811        self.pid.integral
812    }
813
814    /// Get the number of frames observed by the e-process.
815    #[inline]
816    pub fn frames_observed(&self) -> u32 {
817        self.eprocess.frames_observed
818    }
819
820    /// Capture a telemetry snapshot of the controller state.
821    ///
822    /// This is allocation-free and suitable for calling every frame.
823    /// Forward the result to a debug overlay or structured logger.
824    #[inline]
825    pub fn telemetry(&self) -> BudgetTelemetry {
826        BudgetTelemetry {
827            schema_version: BUDGET_TELEMETRY_SCHEMA_VERSION,
828            level: self.current_level,
829            pid_output: self.last_pid_output,
830            pid_p: self.pid.last_p,
831            pid_i: self.pid.last_i,
832            pid_d: self.pid.last_d,
833            e_value: self.eprocess.e_value,
834            eprocess_lambda: self.eprocess.lambda,
835            frames_observed: self.eprocess.frames_observed,
836            frames_since_change: self.frames_since_change,
837            last_decision: self.last_decision,
838            decision_reason: self.last_decision_reason,
839            transition_seq: self.transition_seq,
840            transition_correlation_id: self.last_transition_correlation_id,
841            frame_time_ms: self.last_frame_ms,
842            target_ms: self.config.target.as_secs_f64() * 1000.0,
843            pid_gate_threshold: self.last_pid_gate_threshold,
844            pid_gate_margin: self.last_pid_gate_margin,
845            evidence_threshold: self.last_evidence_threshold,
846            evidence_margin: self.last_evidence_margin,
847            in_warmup: self.eprocess.frames_observed < self.config.eprocess.warmup_frames,
848            recovery_streak: self.recovery_streak,
849            total_degrades: self.total_degrades,
850            total_recoveries: self.total_recoveries,
851        }
852    }
853
854    /// Reset the controller to initial state.
855    pub fn reset(&mut self) {
856        self.pid.reset();
857        self.eprocess.reset(&self.config.eprocess);
858        self.current_level = DegradationLevel::Full;
859        self.frames_since_change = 0;
860        self.last_pid_output = 0.0;
861        self.last_decision = BudgetDecision::Hold;
862        self.last_decision_reason = BudgetDecisionReason::WithinThresholdBand;
863        self.last_frame_ms = 0.0;
864        self.transition_seq = 0;
865        self.last_transition_correlation_id = 0;
866        self.last_pid_gate_threshold = 0.0;
867        self.last_pid_gate_margin = 0.0;
868        self.last_evidence_threshold = 0.0;
869        self.last_evidence_margin = 0.0;
870        self.recovery_streak = 0;
871        self.total_degrades = 0;
872        self.total_recoveries = 0;
873    }
874
875    /// Get a reference to the controller configuration.
876    #[inline]
877    #[must_use]
878    pub fn config(&self) -> &BudgetControllerConfig {
879        &self.config
880    }
881}
882
883/// Snapshot of budget controller telemetry for diagnostics and debug overlay.
884///
885/// All fields are `Copy` — no allocations. Intended to be cheaply captured
886/// once per frame and forwarded to a tracing subscriber or debug overlay widget.
887#[derive(Debug, Clone, Copy, PartialEq)]
888pub struct BudgetTelemetry {
889    /// Telemetry schema version for CI/E2E consumers.
890    pub schema_version: u16,
891    /// Current degradation level.
892    pub level: DegradationLevel,
893    /// Last PID control signal (positive = over budget).
894    pub pid_output: f64,
895    /// Last PID proportional term.
896    pub pid_p: f64,
897    /// Last PID integral term.
898    pub pid_i: f64,
899    /// Last PID derivative term.
900    pub pid_d: f64,
901    /// Current e-process value E_t.
902    pub e_value: f64,
903    /// Current e-process betting fraction λ_t.
904    pub eprocess_lambda: f64,
905    /// Frames observed by the e-process.
906    pub frames_observed: u32,
907    /// Frames since last level change.
908    pub frames_since_change: u32,
909    /// Last decision made by the controller.
910    pub last_decision: BudgetDecision,
911    /// Rationale code describing why the last decision was taken.
912    pub decision_reason: BudgetDecisionReason,
913    /// Monotonic transition sequence number (increments on degrade/upgrade).
914    pub transition_seq: u64,
915    /// Correlation ID for the most recent transition event (0 if none yet).
916    pub transition_correlation_id: u64,
917    /// Last observed frame time in milliseconds.
918    pub frame_time_ms: f64,
919    /// Current target frame budget in milliseconds.
920    pub target_ms: f64,
921    /// PID gate threshold used for the last decision path.
922    pub pid_gate_threshold: f64,
923    /// PID gate margin (positive values indicate stronger gate pass).
924    pub pid_gate_margin: f64,
925    /// Evidence (e-process) threshold used for the last decision path.
926    pub evidence_threshold: f64,
927    /// Evidence gate margin (positive values indicate stronger gate pass).
928    pub evidence_margin: f64,
929    /// Whether the controller is in warmup (e-process not yet active).
930    pub in_warmup: bool,
931    /// Current recovery streak (consecutive upgrade-eligible frames).
932    pub recovery_streak: u32,
933    /// Total degrade events enacted by the controller.
934    pub total_degrades: u64,
935    /// Total recovery (upgrade) events enacted by the controller.
936    pub total_recoveries: u64,
937}
938
939/// Progressive degradation levels for render quality.
940///
941/// Higher levels mean less visual fidelity but faster rendering.
942/// The ordering is significant: `Full` < `SimpleBorders` < ... < `SkipFrame`.
943#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
944#[repr(u8)]
945pub enum DegradationLevel {
946    /// All visual features enabled.
947    #[default]
948    Full = 0,
949    /// Unicode box-drawing replaced with ASCII (+--+).
950    SimpleBorders = 1,
951    /// Colors disabled, monochrome output.
952    NoStyling = 2,
953    /// Skip decorative widgets, essential content only.
954    EssentialOnly = 3,
955    /// Just layout boxes, no content.
956    Skeleton = 4,
957    /// Emergency: skip frame entirely.
958    SkipFrame = 5,
959}
960
961impl DegradationLevel {
962    /// Move to the next degradation level.
963    ///
964    /// Returns `SkipFrame` if already at maximum degradation.
965    #[inline]
966    #[must_use]
967    pub fn next(self) -> Self {
968        match self {
969            Self::Full => Self::SimpleBorders,
970            Self::SimpleBorders => Self::NoStyling,
971            Self::NoStyling => Self::EssentialOnly,
972            Self::EssentialOnly => Self::Skeleton,
973            Self::Skeleton | Self::SkipFrame => Self::SkipFrame,
974        }
975    }
976
977    /// Move to the previous (better quality) degradation level.
978    ///
979    /// Returns `Full` if already at minimum degradation.
980    #[inline]
981    #[must_use]
982    pub fn prev(self) -> Self {
983        match self {
984            Self::SkipFrame => Self::Skeleton,
985            Self::Skeleton => Self::EssentialOnly,
986            Self::EssentialOnly => Self::NoStyling,
987            Self::NoStyling => Self::SimpleBorders,
988            Self::SimpleBorders | Self::Full => Self::Full,
989        }
990    }
991
992    /// Check if this is the maximum degradation level.
993    #[inline]
994    pub fn is_max(self) -> bool {
995        self == Self::SkipFrame
996    }
997
998    /// Check if this is full quality (no degradation).
999    #[inline]
1000    pub fn is_full(self) -> bool {
1001        self == Self::Full
1002    }
1003
1004    /// Get a human-readable name for logging.
1005    #[inline]
1006    pub fn as_str(self) -> &'static str {
1007        match self {
1008            Self::Full => "Full",
1009            Self::SimpleBorders => "SimpleBorders",
1010            Self::NoStyling => "NoStyling",
1011            Self::EssentialOnly => "EssentialOnly",
1012            Self::Skeleton => "Skeleton",
1013            Self::SkipFrame => "SkipFrame",
1014        }
1015    }
1016
1017    /// Number of levels from Full (0) to this level.
1018    #[inline]
1019    pub fn level(self) -> u8 {
1020        self as u8
1021    }
1022
1023    // ---- Widget convenience queries ----
1024
1025    /// Whether to use Unicode box-drawing characters.
1026    ///
1027    /// Returns `false` at `SimpleBorders` and above (use ASCII instead).
1028    #[inline]
1029    pub fn use_unicode_borders(self) -> bool {
1030        self < Self::SimpleBorders
1031    }
1032
1033    /// Whether to apply colors and style attributes to cells.
1034    ///
1035    /// Returns `false` at `NoStyling` and above.
1036    #[inline]
1037    pub fn apply_styling(self) -> bool {
1038        self < Self::NoStyling
1039    }
1040
1041    /// Whether to render decorative (non-essential) elements.
1042    ///
1043    /// Returns `false` at `EssentialOnly` and above.
1044    /// Decorative elements include borders, scrollbars, spinners, rules.
1045    #[inline]
1046    pub fn render_decorative(self) -> bool {
1047        self < Self::EssentialOnly
1048    }
1049
1050    /// Whether to render content text.
1051    ///
1052    /// Returns `false` at `Skeleton` and above.
1053    #[inline]
1054    pub fn render_content(self) -> bool {
1055        self < Self::Skeleton
1056    }
1057
1058    /// Whether a widget is allowed to render at this degradation level.
1059    ///
1060    /// - `Full`, `SimpleBorders`, `NoStyling`: all widgets allowed.
1061    /// - `EssentialOnly`, `Skeleton`: only essential widgets allowed.
1062    /// - `SkipFrame`: no widgets allowed.
1063    #[inline]
1064    #[must_use]
1065    pub fn allows_widget(self, essential: bool) -> bool {
1066        match self {
1067            Self::Full | Self::SimpleBorders | Self::NoStyling => true,
1068            Self::EssentialOnly | Self::Skeleton => essential,
1069            Self::SkipFrame => false,
1070        }
1071    }
1072}
1073
1074/// Per-phase time budgets within a frame.
1075#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1076pub struct PhaseBudgets {
1077    /// Budget for diff computation.
1078    pub diff: Duration,
1079    /// Budget for ANSI presentation/emission.
1080    pub present: Duration,
1081    /// Budget for widget rendering.
1082    pub render: Duration,
1083}
1084
1085impl Default for PhaseBudgets {
1086    fn default() -> Self {
1087        Self {
1088            diff: Duration::from_millis(2),
1089            present: Duration::from_millis(4),
1090            render: Duration::from_millis(8),
1091        }
1092    }
1093}
1094
1095/// Configuration for frame budget behavior.
1096#[derive(Debug, Clone, PartialEq)]
1097pub struct FrameBudgetConfig {
1098    /// Total time budget per frame.
1099    pub total: Duration,
1100    /// Per-phase budgets.
1101    pub phase_budgets: PhaseBudgets,
1102    /// Allow skipping frames entirely once degradation reaches
1103    /// [`DegradationLevel::SkipFrame`]. A frame that has been rendered is
1104    /// always presented, even when it ran over budget.
1105    pub allow_frame_skip: bool,
1106    /// Frames to wait between degradation level changes.
1107    pub degradation_cooldown: u32,
1108    /// Threshold (as fraction of total) above which we consider upgrading.
1109    /// Default: 0.5 (upgrade when >50% budget remains).
1110    pub upgrade_threshold: f32,
1111}
1112
1113impl Default for FrameBudgetConfig {
1114    fn default() -> Self {
1115        Self {
1116            total: Duration::from_millis(16), // ~60fps feel
1117            phase_budgets: PhaseBudgets::default(),
1118            allow_frame_skip: true,
1119            degradation_cooldown: 3,
1120            upgrade_threshold: 0.5,
1121        }
1122    }
1123}
1124
1125impl FrameBudgetConfig {
1126    /// Create a new config with the specified total budget.
1127    pub fn with_total(total: Duration) -> Self {
1128        Self {
1129            total,
1130            ..Default::default()
1131        }
1132    }
1133
1134    /// Create a strict config that never skips frames.
1135    ///
1136    /// Every frame is rendered and presented, even at the deepest
1137    /// degradation level; the budget still lowers rendering quality.
1138    pub fn strict(total: Duration) -> Self {
1139        Self {
1140            total,
1141            allow_frame_skip: false,
1142            ..Default::default()
1143        }
1144    }
1145
1146    /// Create a relaxed config for slower refresh rates.
1147    pub fn relaxed() -> Self {
1148        Self {
1149            total: Duration::from_millis(33), // ~30fps
1150            degradation_cooldown: 5,
1151            ..Default::default()
1152        }
1153    }
1154}
1155
1156/// Render time budget with graceful degradation.
1157///
1158/// Tracks elapsed time within a frame and manages degradation level
1159/// to maintain responsive rendering under load.
1160#[derive(Debug, Clone)]
1161pub struct RenderBudget {
1162    /// Total time budget for this frame.
1163    total: Duration,
1164    /// When this frame started.
1165    start: Instant,
1166    /// Measured render+present time for the last frame (if recorded).
1167    last_frame_time: Option<Duration>,
1168    /// Current degradation level.
1169    degradation: DegradationLevel,
1170    /// Per-phase budgets.
1171    phase_budgets: PhaseBudgets,
1172    /// Allow frame skip at maximum degradation.
1173    allow_frame_skip: bool,
1174    /// Upgrade threshold fraction.
1175    upgrade_threshold: f32,
1176    /// Frames since last degradation change (for cooldown).
1177    frames_since_change: u32,
1178    /// Cooldown frames required between changes.
1179    cooldown: u32,
1180    /// Optional adaptive budget controller (PID + e-process).
1181    /// When present, `next_frame()` delegates degradation decisions to the controller.
1182    controller: Option<BudgetController>,
1183}
1184
1185impl RenderBudget {
1186    /// Create a new budget with the specified total time.
1187    pub fn new(total: Duration) -> Self {
1188        Self {
1189            total,
1190            start: Instant::now(),
1191            last_frame_time: None,
1192            degradation: DegradationLevel::Full,
1193            phase_budgets: PhaseBudgets::default(),
1194            allow_frame_skip: true,
1195            upgrade_threshold: 0.5,
1196            frames_since_change: 0,
1197            cooldown: 3,
1198            controller: None,
1199        }
1200    }
1201
1202    /// Create a budget from configuration.
1203    pub fn from_config(config: &FrameBudgetConfig) -> Self {
1204        Self {
1205            total: config.total,
1206            start: Instant::now(),
1207            last_frame_time: None,
1208            degradation: DegradationLevel::Full,
1209            phase_budgets: config.phase_budgets,
1210            allow_frame_skip: config.allow_frame_skip,
1211            upgrade_threshold: config.upgrade_threshold,
1212            frames_since_change: 0,
1213            cooldown: config.degradation_cooldown,
1214            controller: None,
1215        }
1216    }
1217
1218    /// Attach an adaptive budget controller to this render budget.
1219    ///
1220    /// When a controller is attached, `next_frame()` feeds the measured frame
1221    /// duration to the controller and applies its degradation decisions
1222    /// instead of the simple threshold-based upgrade logic.
1223    ///
1224    /// # Example
1225    ///
1226    /// ```
1227    /// use ftui_render::budget::{RenderBudget, BudgetControllerConfig};
1228    /// use std::time::Duration;
1229    ///
1230    /// let budget = RenderBudget::new(Duration::from_millis(16))
1231    ///     .with_controller(BudgetControllerConfig::default());
1232    /// ```
1233    #[must_use]
1234    pub fn with_controller(mut self, config: BudgetControllerConfig) -> Self {
1235        self.controller = Some(BudgetController::new(config));
1236        self
1237    }
1238
1239    /// Get the total budget duration.
1240    #[inline]
1241    pub fn total(&self) -> Duration {
1242        self.total
1243    }
1244
1245    /// Get the elapsed time since budget started.
1246    #[inline]
1247    pub fn elapsed(&self) -> Duration {
1248        self.start.elapsed()
1249    }
1250
1251    /// Get the remaining time in the budget.
1252    #[inline]
1253    pub fn remaining(&self) -> Duration {
1254        self.total.saturating_sub(self.start.elapsed())
1255    }
1256
1257    /// Get the remaining time as a fraction of total (0.0 to 1.0).
1258    #[inline]
1259    pub fn remaining_fraction(&self) -> f32 {
1260        if self.total.is_zero() {
1261            return 0.0;
1262        }
1263        let remaining = self.remaining().as_secs_f32();
1264        let total = self.total.as_secs_f32();
1265        (remaining / total).clamp(0.0, 1.0)
1266    }
1267
1268    /// Check if we should degrade given an estimated operation cost.
1269    ///
1270    /// Returns `true` if the estimated cost exceeds remaining budget.
1271    #[inline]
1272    pub fn should_degrade(&self, estimated_cost: Duration) -> bool {
1273        self.remaining() < estimated_cost
1274    }
1275
1276    /// Degrade to the next level.
1277    ///
1278    /// Logs a warning when degradation occurs. An attached controller is
1279    /// kept in sync so it reasons (and can later upgrade) from the actual
1280    /// level. External callers may degrade past the controller's
1281    /// `degradation_floor` — emergency paths (memory/queue guardrails)
1282    /// deliberately outrank the visual-quality floor; frame-time gates
1283    /// that should honor the configured floor use
1284    /// [`degrade_respecting_floor`](Self::degrade_respecting_floor).
1285    pub fn degrade(&mut self) {
1286        let from = self.degradation;
1287        self.degradation = self.degradation.next();
1288        self.frames_since_change = 0;
1289        self.sync_controller_level();
1290
1291        #[cfg(feature = "tracing")]
1292        if from != self.degradation {
1293            warn!(
1294                from = from.as_str(),
1295                to = self.degradation.as_str(),
1296                remaining_ms = self.remaining().as_millis() as u32,
1297                "render budget degradation"
1298            );
1299        }
1300        let _ = from; // Suppress unused warning when tracing is disabled
1301    }
1302
1303    /// Return the configured degradation floor from the attached controller,
1304    /// or [`DegradationLevel::SkipFrame`] if no controller is attached.
1305    #[inline]
1306    pub fn degradation_floor(&self) -> DegradationLevel {
1307        self.controller
1308            .as_ref()
1309            .map_or(DegradationLevel::SkipFrame, |ctrl| {
1310                ctrl.config().degradation_floor
1311            })
1312    }
1313
1314    /// Degrade to the next level only if currently below [`degradation_floor`](Self::degradation_floor).
1315    ///
1316    /// Returns `true` if the degradation level increased, or `false` if
1317    /// already at or beyond the configured floor (or [`DegradationLevel::SkipFrame`]).
1318    pub fn degrade_respecting_floor(&mut self) -> bool {
1319        let floor = self.degradation_floor();
1320        if self.degradation >= floor {
1321            return false;
1322        }
1323        let from = self.degradation;
1324        self.degrade();
1325        self.degradation > from
1326    }
1327
1328    /// Keep an attached controller's level in lockstep with the budget's.
1329    #[inline]
1330    fn sync_controller_level(&mut self) {
1331        if let Some(controller) = self.controller.as_mut() {
1332            controller.sync_level(self.degradation);
1333        }
1334    }
1335
1336    /// Get the current degradation level.
1337    #[inline]
1338    pub fn degradation(&self) -> DegradationLevel {
1339        self.degradation
1340    }
1341
1342    /// Set the degradation level directly.
1343    ///
1344    /// Use with caution - prefer `degrade()` and `upgrade()` for gradual
1345    /// changes. An attached controller is kept in sync so recovery from an
1346    /// externally forced level remains possible.
1347    pub fn set_degradation(&mut self, level: DegradationLevel) {
1348        if self.degradation != level {
1349            self.degradation = level;
1350            self.frames_since_change = 0;
1351            self.sync_controller_level();
1352        }
1353    }
1354
1355    /// Check if the budget is exhausted.
1356    ///
1357    /// Returns `true` if no time remains OR if at SkipFrame level (when frame
1358    /// skipping is allowed). This is an advisory signal for work inside a
1359    /// frame, such as a widget that can stop early. It does not decide whether
1360    /// a frame is skipped or presented; see [`should_skip_frame`](Self::should_skip_frame).
1361    #[inline]
1362    pub fn exhausted(&self) -> bool {
1363        self.remaining().is_zero() || self.should_skip_frame()
1364    }
1365
1366    /// Check if the next frame should be skipped entirely.
1367    ///
1368    /// Returns `true` only at [`DegradationLevel::SkipFrame`] with frame
1369    /// skipping allowed. Running out of time is not a reason to skip: a frame
1370    /// that was rendered late is still presented, and the budget only lowers
1371    /// the quality of later frames (frankentui#104). With
1372    /// [`FrameBudgetConfig::strict`] this is always `false`.
1373    #[inline]
1374    pub fn should_skip_frame(&self) -> bool {
1375        self.degradation == DegradationLevel::SkipFrame && self.allow_frame_skip
1376    }
1377
1378    /// Check if we should attempt to upgrade quality.
1379    ///
1380    /// Returns `true` if more than `upgrade_threshold` of budget remains
1381    /// and we're not already at full quality, and cooldown has passed.
1382    pub fn should_upgrade(&self) -> bool {
1383        !self.degradation.is_full()
1384            && self.remaining_fraction() > self.upgrade_threshold
1385            && self.frames_since_change >= self.cooldown
1386    }
1387
1388    /// Check if we should upgrade using a measured frame time.
1389    fn should_upgrade_with_elapsed(&self, elapsed: Duration) -> bool {
1390        if self.degradation.is_full() || self.frames_since_change < self.cooldown {
1391            return false;
1392        }
1393        self.remaining_fraction_for_elapsed(elapsed) > self.upgrade_threshold
1394    }
1395
1396    /// Remaining fraction computed from an elapsed frame time.
1397    fn remaining_fraction_for_elapsed(&self, elapsed: Duration) -> f32 {
1398        if self.total.is_zero() {
1399            return 0.0;
1400        }
1401        let remaining = self.total.saturating_sub(elapsed);
1402        let remaining = remaining.as_secs_f32();
1403        let total = self.total.as_secs_f32();
1404        (remaining / total).clamp(0.0, 1.0)
1405    }
1406
1407    /// Upgrade to the previous (better quality) level.
1408    ///
1409    /// Logs when upgrade occurs.
1410    pub fn upgrade(&mut self) {
1411        let from = self.degradation;
1412        self.degradation = self.degradation.prev();
1413        self.frames_since_change = 0;
1414        self.sync_controller_level();
1415
1416        #[cfg(feature = "tracing")]
1417        if from != self.degradation {
1418            trace!(
1419                from = from.as_str(),
1420                to = self.degradation.as_str(),
1421                remaining_fraction = self.remaining_fraction(),
1422                "render budget upgrade"
1423            );
1424        }
1425        let _ = from; // Suppress unused warning when tracing is disabled
1426    }
1427
1428    /// Reset the budget for a new frame.
1429    ///
1430    /// Keeps the current degradation level but resets timing.
1431    pub fn reset(&mut self) {
1432        self.start = Instant::now();
1433        self.frames_since_change = self.frames_since_change.saturating_add(1);
1434    }
1435
1436    /// Reset the budget and attempt upgrade if conditions are met.
1437    ///
1438    /// Call this at the start of each frame to enable recovery.
1439    ///
1440    /// When an adaptive controller is attached (via [`with_controller`](Self::with_controller)),
1441    /// the measured frame duration is fed to the controller and its decision
1442    /// (degrade / upgrade / hold) is applied automatically. The simple
1443    /// threshold-based upgrade path is skipped in that case.
1444    pub fn next_frame(&mut self) {
1445        // Consume the recorded time: each observation feeds the controller
1446        // exactly once. Without take(), a frame that skips recording (e.g.
1447        // the emergency drop-frame path) re-feeds the previous frame's
1448        // duration, accumulating PID/e-process evidence from a measurement
1449        // that never happened; the elapsed-time fallback below also becomes
1450        // permanently dead after the first record_frame_time call.
1451        let frame_time = self
1452            .last_frame_time
1453            .take()
1454            .unwrap_or_else(|| self.start.elapsed());
1455
1456        if self.controller.is_some() {
1457            // Measure how long the previous frame took
1458
1459            // SAFETY: we just checked is_some; this avoids a borrow-checker
1460            // conflict with `&mut self` needed for degrade/upgrade below.
1461            let decision = self
1462                .controller
1463                .as_mut()
1464                .expect("controller guaranteed by is_some guard")
1465                .update(frame_time);
1466
1467            match decision {
1468                BudgetDecision::Degrade => self.degrade(),
1469                BudgetDecision::Upgrade => self.upgrade(),
1470                BudgetDecision::Hold => {}
1471            }
1472        } else {
1473            // Legacy path: simple threshold-based upgrade
1474            if self.should_upgrade_with_elapsed(frame_time) {
1475                self.upgrade();
1476            }
1477        }
1478        self.reset();
1479    }
1480
1481    /// Record the measured render+present time for the last frame.
1482    pub fn record_frame_time(&mut self, elapsed: Duration) {
1483        self.last_frame_time = Some(elapsed);
1484    }
1485
1486    /// Get a telemetry snapshot from the adaptive controller, if attached.
1487    ///
1488    /// Returns `None` if no controller is attached.
1489    /// This is allocation-free and safe to call every frame.
1490    #[inline]
1491    pub fn telemetry(&self) -> Option<BudgetTelemetry> {
1492        self.controller.as_ref().map(BudgetController::telemetry)
1493    }
1494
1495    /// Get a reference to the adaptive controller, if attached.
1496    #[inline]
1497    pub fn controller(&self) -> Option<&BudgetController> {
1498        self.controller.as_ref()
1499    }
1500
1501    /// Get the phase budgets.
1502    #[inline]
1503    #[must_use]
1504    pub fn phase_budgets(&self) -> &PhaseBudgets {
1505        &self.phase_budgets
1506    }
1507
1508    /// Check if a specific phase has budget remaining.
1509    pub fn phase_has_budget(&self, phase: Phase) -> bool {
1510        let phase_budget = match phase {
1511            Phase::Diff => self.phase_budgets.diff,
1512            Phase::Present => self.phase_budgets.present,
1513            Phase::Render => self.phase_budgets.render,
1514        };
1515        self.remaining() >= phase_budget
1516    }
1517
1518    /// Create a sub-budget for a specific phase.
1519    ///
1520    /// The sub-budget's clock starts now and its total is the phase
1521    /// allocation clamped to the frame's remaining time, so the phase gets
1522    /// its full allowance from the moment it begins. (Inheriting the frame's
1523    /// start instant would count time spent in earlier phases against this
1524    /// phase, leaving any phase entered later than its own allocation into
1525    /// the frame born exhausted.)
1526    #[must_use]
1527    pub fn phase_budget(&self, phase: Phase) -> Self {
1528        let phase_total = match phase {
1529            Phase::Diff => self.phase_budgets.diff,
1530            Phase::Present => self.phase_budgets.present,
1531            Phase::Render => self.phase_budgets.render,
1532        };
1533        Self {
1534            total: phase_total.min(self.remaining()),
1535            start: Instant::now(),
1536            last_frame_time: self.last_frame_time,
1537            degradation: self.degradation,
1538            phase_budgets: self.phase_budgets,
1539            allow_frame_skip: self.allow_frame_skip,
1540            upgrade_threshold: self.upgrade_threshold,
1541            frames_since_change: self.frames_since_change,
1542            cooldown: self.cooldown,
1543            controller: None, // Phase sub-budgets don't carry the controller
1544        }
1545    }
1546}
1547
1548/// Render phases for budget allocation.
1549#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1550pub enum Phase {
1551    /// Buffer diff computation.
1552    Diff,
1553    /// ANSI sequence presentation.
1554    Present,
1555    /// Widget tree rendering.
1556    Render,
1557}
1558
1559impl Phase {
1560    /// Get a human-readable name.
1561    pub fn as_str(self) -> &'static str {
1562        match self {
1563            Self::Diff => "diff",
1564            Self::Present => "present",
1565            Self::Render => "render",
1566        }
1567    }
1568}
1569
1570#[cfg(test)]
1571mod tests {
1572    use super::*;
1573    use std::thread;
1574
1575    #[test]
1576    fn degradation_level_ordering() {
1577        assert!(DegradationLevel::Full < DegradationLevel::SimpleBorders);
1578        assert!(DegradationLevel::SimpleBorders < DegradationLevel::NoStyling);
1579        assert!(DegradationLevel::NoStyling < DegradationLevel::EssentialOnly);
1580        assert!(DegradationLevel::EssentialOnly < DegradationLevel::Skeleton);
1581        assert!(DegradationLevel::Skeleton < DegradationLevel::SkipFrame);
1582    }
1583
1584    #[test]
1585    fn degradation_level_next() {
1586        assert_eq!(
1587            DegradationLevel::Full.next(),
1588            DegradationLevel::SimpleBorders
1589        );
1590        assert_eq!(
1591            DegradationLevel::SimpleBorders.next(),
1592            DegradationLevel::NoStyling
1593        );
1594        assert_eq!(
1595            DegradationLevel::NoStyling.next(),
1596            DegradationLevel::EssentialOnly
1597        );
1598        assert_eq!(
1599            DegradationLevel::EssentialOnly.next(),
1600            DegradationLevel::Skeleton
1601        );
1602        assert_eq!(
1603            DegradationLevel::Skeleton.next(),
1604            DegradationLevel::SkipFrame
1605        );
1606        assert_eq!(
1607            DegradationLevel::SkipFrame.next(),
1608            DegradationLevel::SkipFrame
1609        );
1610    }
1611
1612    #[test]
1613    fn degradation_level_prev() {
1614        assert_eq!(
1615            DegradationLevel::SkipFrame.prev(),
1616            DegradationLevel::Skeleton
1617        );
1618        assert_eq!(
1619            DegradationLevel::Skeleton.prev(),
1620            DegradationLevel::EssentialOnly
1621        );
1622        assert_eq!(
1623            DegradationLevel::EssentialOnly.prev(),
1624            DegradationLevel::NoStyling
1625        );
1626        assert_eq!(
1627            DegradationLevel::NoStyling.prev(),
1628            DegradationLevel::SimpleBorders
1629        );
1630        assert_eq!(
1631            DegradationLevel::SimpleBorders.prev(),
1632            DegradationLevel::Full
1633        );
1634        assert_eq!(DegradationLevel::Full.prev(), DegradationLevel::Full);
1635    }
1636
1637    #[test]
1638    fn degradation_level_is_max() {
1639        assert!(!DegradationLevel::Full.is_max());
1640        assert!(!DegradationLevel::Skeleton.is_max());
1641        assert!(DegradationLevel::SkipFrame.is_max());
1642    }
1643
1644    #[test]
1645    fn degradation_level_is_full() {
1646        assert!(DegradationLevel::Full.is_full());
1647        assert!(!DegradationLevel::SimpleBorders.is_full());
1648        assert!(!DegradationLevel::SkipFrame.is_full());
1649    }
1650
1651    #[test]
1652    fn degradation_level_as_str() {
1653        assert_eq!(DegradationLevel::Full.as_str(), "Full");
1654        assert_eq!(DegradationLevel::SimpleBorders.as_str(), "SimpleBorders");
1655        assert_eq!(DegradationLevel::NoStyling.as_str(), "NoStyling");
1656        assert_eq!(DegradationLevel::EssentialOnly.as_str(), "EssentialOnly");
1657        assert_eq!(DegradationLevel::Skeleton.as_str(), "Skeleton");
1658        assert_eq!(DegradationLevel::SkipFrame.as_str(), "SkipFrame");
1659    }
1660
1661    #[test]
1662    fn degradation_level_values() {
1663        assert_eq!(DegradationLevel::Full.level(), 0);
1664        assert_eq!(DegradationLevel::SimpleBorders.level(), 1);
1665        assert_eq!(DegradationLevel::NoStyling.level(), 2);
1666        assert_eq!(DegradationLevel::EssentialOnly.level(), 3);
1667        assert_eq!(DegradationLevel::Skeleton.level(), 4);
1668        assert_eq!(DegradationLevel::SkipFrame.level(), 5);
1669    }
1670
1671    #[test]
1672    fn degradation_level_allows_widget_matrix() {
1673        // Levels 0..=2: both essential and decorative widgets are allowed
1674        assert!(DegradationLevel::Full.allows_widget(true));
1675        assert!(DegradationLevel::Full.allows_widget(false));
1676        assert!(DegradationLevel::SimpleBorders.allows_widget(true));
1677        assert!(DegradationLevel::SimpleBorders.allows_widget(false));
1678        assert!(DegradationLevel::NoStyling.allows_widget(true));
1679        assert!(DegradationLevel::NoStyling.allows_widget(false));
1680
1681        // EssentialOnly (level 3): only essential widgets allowed
1682        assert!(DegradationLevel::EssentialOnly.allows_widget(true));
1683        assert!(!DegradationLevel::EssentialOnly.allows_widget(false));
1684
1685        // Skeleton (level 4): only essential widgets allowed
1686        assert!(DegradationLevel::Skeleton.allows_widget(true));
1687        assert!(!DegradationLevel::Skeleton.allows_widget(false));
1688
1689        // SkipFrame (level 5): no widgets allowed
1690        assert!(!DegradationLevel::SkipFrame.allows_widget(true));
1691        assert!(!DegradationLevel::SkipFrame.allows_widget(false));
1692    }
1693
1694    #[test]
1695    fn budget_remaining_decreases() {
1696        let budget = RenderBudget::new(Duration::from_millis(100));
1697        let initial = budget.remaining();
1698
1699        thread::sleep(Duration::from_millis(10));
1700
1701        let later = budget.remaining();
1702        assert!(later < initial);
1703    }
1704
1705    #[test]
1706    fn budget_remaining_fraction() {
1707        let mut budget = RenderBudget::new(Duration::from_millis(100));
1708
1709        // Initially should be close to 1.0
1710        let initial = budget.remaining_fraction();
1711        assert!(initial > 0.9);
1712
1713        // Pin elapsed to ~50ms deterministically instead of `thread::sleep`,
1714        // which overshoots under CI scheduling jitter and made this test flaky
1715        // on contended runners (macOS CI). The few microseconds between setting
1716        // `start` and reading are negligible against the 0.3..0.6 margins.
1717        budget.start = Instant::now() - Duration::from_millis(50);
1718
1719        // Should be around 0.5 now
1720        let later = budget.remaining_fraction();
1721        assert!(
1722            later < 0.6,
1723            "expected remaining_fraction < 0.6, got {later}"
1724        );
1725        assert!(
1726            later > 0.3,
1727            "expected remaining_fraction > 0.3, got {later}"
1728        );
1729    }
1730
1731    #[test]
1732    fn should_degrade_when_cost_exceeds_remaining() {
1733        // Pin elapsed to ~50ms deterministically (no `thread::sleep`, which is
1734        // flaky under CI scheduling jitter), leaving ~50ms of the 100ms budget.
1735        let mut budget = RenderBudget::new(Duration::from_millis(100));
1736        budget.start = Instant::now() - Duration::from_millis(50);
1737
1738        // Should degrade for expensive operations (80ms > ~50ms remaining)
1739        assert!(budget.should_degrade(Duration::from_millis(80)));
1740        // Should not degrade for cheap operations (10ms < ~50ms remaining)
1741        assert!(!budget.should_degrade(Duration::from_millis(10)));
1742    }
1743
1744    #[test]
1745    fn degrade_advances_level() {
1746        let mut budget = RenderBudget::new(Duration::from_millis(16));
1747
1748        assert_eq!(budget.degradation(), DegradationLevel::Full);
1749
1750        budget.degrade();
1751        assert_eq!(budget.degradation(), DegradationLevel::SimpleBorders);
1752
1753        budget.degrade();
1754        assert_eq!(budget.degradation(), DegradationLevel::NoStyling);
1755    }
1756
1757    #[test]
1758    fn exhausted_when_no_time_left() {
1759        let budget = RenderBudget::new(Duration::from_millis(5));
1760
1761        assert!(!budget.exhausted());
1762
1763        thread::sleep(Duration::from_millis(10));
1764
1765        assert!(budget.exhausted());
1766    }
1767
1768    #[test]
1769    fn exhausted_at_skip_frame() {
1770        let mut budget = RenderBudget::new(Duration::from_millis(1000));
1771
1772        // Set to SkipFrame
1773        budget.set_degradation(DegradationLevel::SkipFrame);
1774
1775        // Should be exhausted even with time remaining
1776        assert!(budget.exhausted());
1777    }
1778
1779    #[test]
1780    fn should_skip_frame_only_at_skip_frame_when_allowed() {
1781        let mut budget = RenderBudget::new(Duration::from_millis(1000));
1782        for level in [
1783            DegradationLevel::Full,
1784            DegradationLevel::SimpleBorders,
1785            DegradationLevel::NoStyling,
1786            DegradationLevel::EssentialOnly,
1787            DegradationLevel::Skeleton,
1788        ] {
1789            budget.set_degradation(level);
1790            assert!(!budget.should_skip_frame(), "{level:?} must not skip");
1791        }
1792        budget.set_degradation(DegradationLevel::SkipFrame);
1793        assert!(budget.should_skip_frame());
1794
1795        budget.allow_frame_skip = false;
1796        assert!(
1797            !budget.should_skip_frame(),
1798            "SkipFrame must not skip when frame skips are disallowed"
1799        );
1800    }
1801
1802    #[test]
1803    fn running_out_of_time_does_not_request_a_frame_skip() {
1804        // frankentui#104: a frame that ran over budget is still presented;
1805        // only a SkipFrame decision skips a frame.
1806        let budget = RenderBudget::new(Duration::ZERO);
1807        assert!(budget.exhausted(), "no time remains");
1808        assert!(!budget.should_skip_frame());
1809    }
1810
1811    #[test]
1812    fn strict_config_never_requests_a_frame_skip() {
1813        let mut budget =
1814            RenderBudget::from_config(&FrameBudgetConfig::strict(Duration::from_millis(16)));
1815        budget.set_degradation(DegradationLevel::SkipFrame);
1816        assert!(
1817            !budget.should_skip_frame(),
1818            "strict() is documented to never skip frames"
1819        );
1820    }
1821
1822    #[test]
1823    fn should_upgrade_with_remaining_budget() {
1824        let mut budget = RenderBudget::new(Duration::from_millis(1000));
1825
1826        // At Full, should not upgrade
1827        assert!(!budget.should_upgrade());
1828
1829        // Degrade and set cooldown frames
1830        budget.degrade();
1831        budget.frames_since_change = 5;
1832
1833        // With lots of budget remaining, should upgrade
1834        assert!(budget.should_upgrade());
1835    }
1836
1837    #[test]
1838    fn upgrade_improves_level() {
1839        let mut budget = RenderBudget::new(Duration::from_millis(16));
1840
1841        budget.set_degradation(DegradationLevel::Skeleton);
1842        assert_eq!(budget.degradation(), DegradationLevel::Skeleton);
1843
1844        budget.upgrade();
1845        assert_eq!(budget.degradation(), DegradationLevel::EssentialOnly);
1846
1847        budget.upgrade();
1848        assert_eq!(budget.degradation(), DegradationLevel::NoStyling);
1849    }
1850
1851    #[test]
1852    fn upgrade_downgrade_symmetric() {
1853        let mut budget = RenderBudget::new(Duration::from_millis(16));
1854
1855        // Degrade all the way
1856        while !budget.degradation().is_max() {
1857            budget.degrade();
1858        }
1859        assert_eq!(budget.degradation(), DegradationLevel::SkipFrame);
1860
1861        // Upgrade all the way
1862        while !budget.degradation().is_full() {
1863            budget.upgrade();
1864        }
1865        assert_eq!(budget.degradation(), DegradationLevel::Full);
1866    }
1867
1868    #[test]
1869    fn reset_preserves_degradation() {
1870        let mut budget = RenderBudget::new(Duration::from_millis(16));
1871
1872        budget.degrade();
1873        budget.degrade();
1874        let level = budget.degradation();
1875
1876        budget.reset();
1877
1878        assert_eq!(budget.degradation(), level);
1879        // Remaining should be close to full again
1880        assert!(budget.remaining_fraction() > 0.9);
1881    }
1882
1883    #[test]
1884    fn next_frame_upgrades_when_possible() {
1885        let mut budget = RenderBudget::new(Duration::from_millis(1000));
1886
1887        // Degrade and simulate several frames
1888        budget.degrade();
1889        for _ in 0..5 {
1890            budget.reset();
1891        }
1892
1893        let before = budget.degradation();
1894        budget.next_frame();
1895
1896        // Should have upgraded
1897        assert!(budget.degradation() < before);
1898    }
1899
1900    #[test]
1901    fn next_frame_prefers_recorded_frame_time_for_upgrade() {
1902        let mut budget = RenderBudget::new(Duration::from_millis(16));
1903
1904        budget.degrade();
1905        for _ in 0..5 {
1906            budget.reset();
1907        }
1908
1909        // Record a fast frame, then wait long enough that start.elapsed()
1910        // would otherwise exceed the budget.
1911        budget.record_frame_time(Duration::from_millis(1));
1912        std::thread::sleep(Duration::from_millis(25));
1913
1914        let before = budget.degradation();
1915        budget.next_frame();
1916
1917        assert!(budget.degradation() < before);
1918    }
1919
1920    #[test]
1921    fn config_defaults() {
1922        let config = FrameBudgetConfig::default();
1923
1924        assert_eq!(config.total, Duration::from_millis(16));
1925        assert!(config.allow_frame_skip);
1926        assert_eq!(config.degradation_cooldown, 3);
1927        assert!((config.upgrade_threshold - 0.5).abs() < f32::EPSILON);
1928    }
1929
1930    #[test]
1931    fn config_with_total() {
1932        let config = FrameBudgetConfig::with_total(Duration::from_millis(33));
1933
1934        assert_eq!(config.total, Duration::from_millis(33));
1935        // Other defaults preserved
1936        assert!(config.allow_frame_skip);
1937    }
1938
1939    #[test]
1940    fn config_strict() {
1941        let config = FrameBudgetConfig::strict(Duration::from_millis(16));
1942
1943        assert!(!config.allow_frame_skip);
1944    }
1945
1946    #[test]
1947    fn config_relaxed() {
1948        let config = FrameBudgetConfig::relaxed();
1949
1950        assert_eq!(config.total, Duration::from_millis(33));
1951        assert_eq!(config.degradation_cooldown, 5);
1952    }
1953
1954    #[test]
1955    fn from_config() {
1956        let config = FrameBudgetConfig {
1957            total: Duration::from_millis(20),
1958            allow_frame_skip: false,
1959            ..Default::default()
1960        };
1961
1962        let budget = RenderBudget::from_config(&config);
1963
1964        assert_eq!(budget.total(), Duration::from_millis(20));
1965        assert!(!budget.exhausted()); // allow_frame_skip is false
1966
1967        // Set to SkipFrame - should NOT be exhausted since frame skip disabled
1968        let mut budget = RenderBudget::from_config(&config);
1969        budget.set_degradation(DegradationLevel::SkipFrame);
1970        assert!(!budget.exhausted());
1971    }
1972
1973    #[test]
1974    fn phase_budgets_default() {
1975        let budgets = PhaseBudgets::default();
1976
1977        assert_eq!(budgets.diff, Duration::from_millis(2));
1978        assert_eq!(budgets.present, Duration::from_millis(4));
1979        assert_eq!(budgets.render, Duration::from_millis(8));
1980    }
1981
1982    #[test]
1983    fn phase_has_budget() {
1984        let budget = RenderBudget::new(Duration::from_millis(100));
1985
1986        assert!(budget.phase_has_budget(Phase::Diff));
1987        assert!(budget.phase_has_budget(Phase::Present));
1988        assert!(budget.phase_has_budget(Phase::Render));
1989    }
1990
1991    #[test]
1992    fn phase_budget_respects_remaining() {
1993        let budget = RenderBudget::new(Duration::from_millis(100));
1994
1995        let diff_budget = budget.phase_budget(Phase::Diff);
1996        assert_eq!(diff_budget.total(), Duration::from_millis(2));
1997
1998        let present_budget = budget.phase_budget(Phase::Present);
1999        assert_eq!(present_budget.total(), Duration::from_millis(4));
2000    }
2001
2002    #[test]
2003    fn phase_as_str() {
2004        assert_eq!(Phase::Diff.as_str(), "diff");
2005        assert_eq!(Phase::Present.as_str(), "present");
2006        assert_eq!(Phase::Render.as_str(), "render");
2007    }
2008
2009    #[test]
2010    fn zero_budget_is_immediately_exhausted() {
2011        let budget = RenderBudget::new(Duration::ZERO);
2012        assert!(budget.exhausted());
2013        assert_eq!(budget.remaining_fraction(), 0.0);
2014    }
2015
2016    #[test]
2017    fn degradation_level_never_exceeds_skip_frame() {
2018        let mut level = DegradationLevel::Full;
2019
2020        for _ in 0..100 {
2021            level = level.next();
2022        }
2023
2024        assert_eq!(level, DegradationLevel::SkipFrame);
2025    }
2026
2027    #[test]
2028    fn budget_remaining_never_negative() {
2029        let budget = RenderBudget::new(Duration::from_millis(1));
2030
2031        // Wait well past the budget
2032        thread::sleep(Duration::from_millis(10));
2033
2034        // Should be zero, not negative
2035        assert_eq!(budget.remaining(), Duration::ZERO);
2036        assert_eq!(budget.remaining_fraction(), 0.0);
2037    }
2038
2039    #[test]
2040    fn infinite_budget_stays_at_full() {
2041        let mut budget = RenderBudget::new(Duration::from_secs(1000));
2042
2043        // With huge budget, should never need to degrade
2044        assert!(!budget.should_degrade(Duration::from_millis(100)));
2045        assert_eq!(budget.degradation(), DegradationLevel::Full);
2046
2047        // Next frame should not upgrade since already at full
2048        budget.next_frame();
2049        assert_eq!(budget.degradation(), DegradationLevel::Full);
2050    }
2051
2052    #[test]
2053    fn cooldown_prevents_immediate_upgrade() {
2054        let mut budget = RenderBudget::new(Duration::from_millis(1000));
2055        budget.cooldown = 3;
2056
2057        // Degrade
2058        budget.degrade();
2059        assert_eq!(budget.frames_since_change, 0);
2060
2061        // Should not upgrade immediately (cooldown not met)
2062        assert!(!budget.should_upgrade());
2063
2064        // Simulate frames
2065        budget.frames_since_change = 3;
2066
2067        // Now should be able to upgrade
2068        assert!(budget.should_upgrade());
2069    }
2070
2071    #[test]
2072    fn set_degradation_resets_cooldown() {
2073        let mut budget = RenderBudget::new(Duration::from_millis(16));
2074        budget.frames_since_change = 10;
2075
2076        budget.set_degradation(DegradationLevel::NoStyling);
2077
2078        assert_eq!(budget.frames_since_change, 0);
2079    }
2080
2081    #[test]
2082    fn set_degradation_same_level_preserves_cooldown() {
2083        let mut budget = RenderBudget::new(Duration::from_millis(16));
2084        budget.frames_since_change = 10;
2085
2086        // Set to same level
2087        budget.set_degradation(DegradationLevel::Full);
2088
2089        // Cooldown preserved since level didn't change
2090        assert_eq!(budget.frames_since_change, 10);
2091    }
2092
2093    // -----------------------------------------------------------------------
2094    // Budget Controller Tests (bd-4kq0.3.1)
2095    // -----------------------------------------------------------------------
2096
2097    mod controller_tests {
2098        use super::super::*;
2099
2100        fn make_controller() -> BudgetController {
2101            BudgetController::new(BudgetControllerConfig::default())
2102        }
2103
2104        fn make_controller_with_config(
2105            target_ms: u64,
2106            warmup: u32,
2107            cooldown: u32,
2108        ) -> BudgetController {
2109            BudgetController::new(BudgetControllerConfig {
2110                target: Duration::from_millis(target_ms),
2111                eprocess: EProcessConfig {
2112                    warmup_frames: warmup,
2113                    ..Default::default()
2114                },
2115                cooldown_frames: cooldown,
2116                ..Default::default()
2117            })
2118        }
2119
2120        // --- PID response tests ---
2121
2122        #[test]
2123        fn pid_step_input_yields_nonzero_output() {
2124            let mut state = PidState::default();
2125            let gains = PidGains::default();
2126
2127            // Step input: constant error of 1.0
2128            let u = state.update(1.0, &gains);
2129            // Kp*1.0 + Ki*1.0 + Kd*(1.0 - 0.0) = 0.5 + 0.05 + 0.2 = 0.75
2130            assert!(
2131                (u - 0.75).abs() < 1e-10,
2132                "First PID output should be 0.75, got {}",
2133                u
2134            );
2135        }
2136
2137        #[test]
2138        fn pid_zero_error_zero_output() {
2139            let mut state = PidState::default();
2140            let gains = PidGains::default();
2141
2142            let u = state.update(0.0, &gains);
2143            assert!(
2144                u.abs() < 1e-10,
2145                "Zero error should produce zero output, got {}",
2146                u
2147            );
2148        }
2149
2150        #[test]
2151        fn pid_integral_accumulates() {
2152            let mut state = PidState::default();
2153            let gains = PidGains::default();
2154
2155            // Feed constant error
2156            state.update(1.0, &gains);
2157            state.update(1.0, &gains);
2158            state.update(1.0, &gains);
2159
2160            assert!(
2161                state.integral > 2.5,
2162                "Integral should accumulate: {}",
2163                state.integral
2164            );
2165        }
2166
2167        #[test]
2168        fn pid_integral_anti_windup() {
2169            let mut state = PidState::default();
2170            let gains = PidGains {
2171                integral_max: 2.0,
2172                ..Default::default()
2173            };
2174
2175            // Feed many frames of error to saturate integral
2176            for _ in 0..100 {
2177                state.update(10.0, &gains);
2178            }
2179
2180            assert!(
2181                state.integral <= 2.0 + f64::EPSILON,
2182                "Integral should be clamped to max: {}",
2183                state.integral
2184            );
2185            assert!(
2186                state.integral >= -2.0 - f64::EPSILON,
2187                "Integral should be clamped to -max: {}",
2188                state.integral
2189            );
2190        }
2191
2192        #[test]
2193        fn pid_derivative_responds_to_change() {
2194            let mut state = PidState::default();
2195            let gains = PidGains::default();
2196
2197            // First frame: error=0
2198            let u1 = state.update(0.0, &gains);
2199            // Second frame: error=1.0 (step change)
2200            let u2 = state.update(1.0, &gains);
2201
2202            // u2 should include derivative component Kd*(1.0 - 0.0) = 0.2
2203            assert!(
2204                u2 > u1,
2205                "Step change should produce larger output: u1={}, u2={}",
2206                u1,
2207                u2
2208            );
2209        }
2210
2211        #[test]
2212        fn pid_settling_after_step() {
2213            let mut state = PidState::default();
2214            let gains = PidGains::default();
2215
2216            // Apply step error then zero error (simulate settling)
2217            state.update(1.0, &gains);
2218            state.update(1.0, &gains);
2219            state.update(1.0, &gains);
2220
2221            // Now remove the error
2222            let mut outputs = Vec::new();
2223            for _ in 0..20 {
2224                outputs.push(state.update(0.0, &gains));
2225            }
2226
2227            // Output should trend toward zero (settling)
2228            let last = *outputs.last().unwrap();
2229            assert!(
2230                last.abs() < 0.5,
2231                "PID should settle toward zero: last={}",
2232                last
2233            );
2234        }
2235
2236        #[test]
2237        fn pid_reset_clears_state() {
2238            let mut state = PidState::default();
2239            let gains = PidGains::default();
2240
2241            state.update(5.0, &gains);
2242            state.update(5.0, &gains);
2243            assert!(state.integral.abs() > 0.0);
2244
2245            state.reset();
2246            assert_eq!(state.integral, 0.0);
2247            assert_eq!(state.prev_error, 0.0);
2248        }
2249
2250        // --- E-process tests ---
2251
2252        #[test]
2253        fn eprocess_starts_at_one() {
2254            let state = EProcessState::default();
2255            assert!(
2256                (state.e_value - 1.0).abs() < f64::EPSILON,
2257                "E-process should start at 1.0"
2258            );
2259        }
2260
2261        #[test]
2262        fn eprocess_grows_under_overload() {
2263            let mut state = EProcessState::default();
2264            let config = EProcessConfig {
2265                warmup_frames: 0,
2266                ..Default::default()
2267            };
2268
2269            // Feed sustained overload (30ms vs 16ms target)
2270            for _ in 0..20 {
2271                state.update(30.0, 16.0, &config);
2272            }
2273
2274            assert!(
2275                state.e_value > 1.0,
2276                "E-value should grow under overload: {}",
2277                state.e_value
2278            );
2279        }
2280
2281        #[test]
2282        fn eprocess_shrinks_under_underload() {
2283            let mut state = EProcessState::default();
2284            let config = EProcessConfig {
2285                warmup_frames: 0,
2286                ..Default::default()
2287            };
2288
2289            // Feed fast frames (8ms vs 16ms target)
2290            for _ in 0..20 {
2291                state.update(8.0, 16.0, &config);
2292            }
2293
2294            assert!(
2295                state.e_value < 1.0,
2296                "E-value should shrink under underload: {}",
2297                state.e_value
2298            );
2299        }
2300
2301        #[test]
2302        fn eprocess_gate_blocks_during_warmup() {
2303            let mut state = EProcessState::default();
2304            let config = EProcessConfig {
2305                warmup_frames: 10,
2306                ..Default::default()
2307            };
2308
2309            // Feed overload during warmup
2310            for _ in 0..5 {
2311                state.update(50.0, 16.0, &config);
2312            }
2313
2314            assert!(
2315                !state.should_degrade(&config),
2316                "E-process should not permit degradation during warmup"
2317            );
2318        }
2319
2320        #[test]
2321        fn eprocess_gate_allows_after_warmup() {
2322            let mut state = EProcessState::default();
2323            let config = EProcessConfig {
2324                warmup_frames: 5,
2325                alpha: 0.05,
2326                ..Default::default()
2327            };
2328
2329            // Feed severe overload past warmup
2330            for _ in 0..50 {
2331                state.update(80.0, 16.0, &config);
2332            }
2333
2334            assert!(
2335                state.should_degrade(&config),
2336                "E-process should permit degradation after sustained overload: E={}",
2337                state.e_value
2338            );
2339        }
2340
2341        #[test]
2342        fn eprocess_recovery_after_overload() {
2343            let mut state = EProcessState::default();
2344            let config = EProcessConfig {
2345                warmup_frames: 0,
2346                ..Default::default()
2347            };
2348
2349            // Overload phase
2350            for _ in 0..30 {
2351                state.update(40.0, 16.0, &config);
2352            }
2353            let peak = state.e_value;
2354
2355            // Recovery phase (fast frames)
2356            for _ in 0..100 {
2357                state.update(8.0, 16.0, &config);
2358            }
2359
2360            assert!(
2361                state.e_value < peak,
2362                "E-value should decrease after recovery: peak={}, now={}",
2363                peak,
2364                state.e_value
2365            );
2366        }
2367
2368        #[test]
2369        fn eprocess_sigma_floor_prevents_instability() {
2370            let mut state = EProcessState::default();
2371            let config = EProcessConfig {
2372                sigma_floor_ms: 1.0,
2373                warmup_frames: 0,
2374                ..Default::default()
2375            };
2376
2377            // Feed identical frames (zero variance)
2378            for _ in 0..20 {
2379                state.update(16.0, 16.0, &config);
2380            }
2381
2382            // sigma_ema should not be below floor
2383            assert!(
2384                state.sigma_ema >= 0.0,
2385                "Sigma should be non-negative: {}",
2386                state.sigma_ema
2387            );
2388            // E-value should remain finite
2389            assert!(
2390                state.e_value.is_finite(),
2391                "E-value should be finite: {}",
2392                state.e_value
2393            );
2394        }
2395
2396        #[test]
2397        fn eprocess_reset_returns_to_initial() {
2398            let mut state = EProcessState::default();
2399            let config = EProcessConfig::default();
2400
2401            state.update(50.0, 16.0, &config);
2402            state.update(50.0, 16.0, &config);
2403
2404            state.reset(&config);
2405            assert!((state.e_value - 1.0).abs() < f64::EPSILON);
2406            assert_eq!(state.frames_observed, 0);
2407        }
2408
2409        // --- Controller integration tests ---
2410
2411        #[test]
2412        fn controller_holds_under_normal_load() {
2413            let mut ctrl = make_controller_with_config(16, 0, 0);
2414
2415            // Feed on-target frames
2416            for _ in 0..20 {
2417                let decision = ctrl.update(Duration::from_millis(16));
2418                assert_eq!(
2419                    decision,
2420                    BudgetDecision::Hold,
2421                    "On-target frames should hold"
2422                );
2423            }
2424            assert_eq!(ctrl.level(), DegradationLevel::Full);
2425        }
2426
2427        #[test]
2428        fn controller_degrades_under_sustained_overload() {
2429            let mut ctrl = make_controller_with_config(16, 0, 0);
2430
2431            let mut degraded = false;
2432            // Feed severe overload
2433            for _ in 0..50 {
2434                let decision = ctrl.update(Duration::from_millis(40));
2435                if decision == BudgetDecision::Degrade {
2436                    degraded = true;
2437                }
2438            }
2439
2440            assert!(
2441                degraded,
2442                "Controller should degrade under sustained overload"
2443            );
2444            assert!(
2445                ctrl.level() > DegradationLevel::Full,
2446                "Level should be degraded: {:?}",
2447                ctrl.level()
2448            );
2449        }
2450
2451        #[test]
2452        fn controller_upgrades_after_recovery() {
2453            let mut ctrl = make_controller_with_config(16, 0, 0);
2454
2455            // Overload to degrade
2456            for _ in 0..50 {
2457                ctrl.update(Duration::from_millis(40));
2458            }
2459            let degraded_level = ctrl.level();
2460            assert!(degraded_level > DegradationLevel::Full);
2461
2462            // Recovery: fast frames
2463            let mut upgraded = false;
2464            for _ in 0..200 {
2465                let decision = ctrl.update(Duration::from_millis(4));
2466                if decision == BudgetDecision::Upgrade {
2467                    upgraded = true;
2468                }
2469            }
2470
2471            assert!(upgraded, "Controller should upgrade after recovery");
2472            assert!(
2473                ctrl.level() < degraded_level,
2474                "Level should improve: before={:?}, after={:?}",
2475                degraded_level,
2476                ctrl.level()
2477            );
2478        }
2479
2480        #[test]
2481        fn controller_cooldown_prevents_oscillation() {
2482            let mut ctrl = make_controller_with_config(16, 0, 5);
2483
2484            // Trigger degradation
2485            for _ in 0..50 {
2486                ctrl.update(Duration::from_millis(40));
2487            }
2488
2489            // Immediately try fast frames
2490            let mut decisions_during_cooldown = Vec::new();
2491            for _ in 0..4 {
2492                decisions_during_cooldown.push(ctrl.update(Duration::from_millis(4)));
2493            }
2494
2495            // During cooldown (frames 0-4), should all be Hold
2496            assert!(
2497                decisions_during_cooldown
2498                    .iter()
2499                    .all(|d| *d == BudgetDecision::Hold),
2500                "Cooldown should prevent changes: {:?}",
2501                decisions_during_cooldown
2502            );
2503        }
2504
2505        #[test]
2506        fn controller_no_oscillation_under_constant_load() {
2507            let mut ctrl = make_controller_with_config(16, 0, 3);
2508
2509            // Moderate overload (20ms vs 16ms)
2510            let mut transitions = 0u32;
2511            let mut prev_level = ctrl.level();
2512            for _ in 0..100 {
2513                ctrl.update(Duration::from_millis(20));
2514                if ctrl.level() != prev_level {
2515                    transitions += 1;
2516                    prev_level = ctrl.level();
2517                }
2518            }
2519
2520            // Under constant load, transitions should be limited
2521            // (progressive degradation, not oscillation)
2522            assert!(
2523                transitions < 10,
2524                "Too many transitions under constant load: {}",
2525                transitions
2526            );
2527        }
2528
2529        #[test]
2530        fn controller_reset_restores_full_quality() {
2531            let mut ctrl = make_controller();
2532
2533            // Degrade
2534            for _ in 0..50 {
2535                ctrl.update(Duration::from_millis(40));
2536            }
2537
2538            ctrl.reset();
2539
2540            assert_eq!(ctrl.level(), DegradationLevel::Full);
2541            assert!((ctrl.e_value() - 1.0).abs() < f64::EPSILON);
2542            assert_eq!(ctrl.pid_integral(), 0.0);
2543        }
2544
2545        #[test]
2546        fn controller_transient_spike_does_not_degrade() {
2547            let mut ctrl = make_controller_with_config(16, 5, 3);
2548
2549            // Normal frames to build history
2550            for _ in 0..20 {
2551                ctrl.update(Duration::from_millis(16));
2552            }
2553
2554            // Single spike
2555            ctrl.update(Duration::from_millis(100));
2556
2557            // Back to normal
2558            for _ in 0..5 {
2559                ctrl.update(Duration::from_millis(16));
2560            }
2561
2562            // Should still be at full quality (spike was transient)
2563            assert_eq!(
2564                ctrl.level(),
2565                DegradationLevel::Full,
2566                "Single spike should not cause degradation"
2567            );
2568        }
2569
2570        #[test]
2571        fn controller_never_exceeds_skip_frame() {
2572            let mut ctrl = make_controller_with_config(16, 0, 0);
2573
2574            // Extreme overload
2575            for _ in 0..500 {
2576                ctrl.update(Duration::from_millis(200));
2577            }
2578
2579            assert!(
2580                ctrl.level() <= DegradationLevel::SkipFrame,
2581                "Level should not exceed SkipFrame: {:?}",
2582                ctrl.level()
2583            );
2584        }
2585
2586        #[test]
2587        fn controller_never_goes_below_full() {
2588            let mut ctrl = make_controller_with_config(16, 0, 0);
2589
2590            // Extreme underload
2591            for _ in 0..200 {
2592                ctrl.update(Duration::from_millis(1));
2593            }
2594
2595            assert_eq!(
2596                ctrl.level(),
2597                DegradationLevel::Full,
2598                "Level should not go below Full"
2599            );
2600        }
2601
2602        // --- Config tests ---
2603
2604        #[test]
2605        fn pid_gains_default_valid() {
2606            let gains = PidGains::default();
2607            assert!(gains.kp > 0.0);
2608            assert!(gains.ki > 0.0);
2609            assert!(gains.kd > 0.0);
2610            assert!(gains.integral_max > 0.0);
2611        }
2612
2613        #[test]
2614        fn eprocess_config_default_valid() {
2615            let config = EProcessConfig::default();
2616            assert!(config.lambda > 0.0);
2617            assert!(config.alpha > 0.0 && config.alpha < 1.0);
2618            assert!(config.beta > 0.0 && config.beta < 1.0);
2619            assert!(config.sigma_floor_ms > 0.0);
2620        }
2621
2622        #[test]
2623        fn controller_config_default_valid() {
2624            let config = BudgetControllerConfig::default();
2625            assert!(config.degrade_threshold > 0.0);
2626            assert!(config.upgrade_threshold > 0.0);
2627            assert!(config.target > Duration::ZERO);
2628        }
2629
2630        #[test]
2631        fn budget_decision_equality() {
2632            assert_eq!(BudgetDecision::Hold, BudgetDecision::Hold);
2633            assert_ne!(BudgetDecision::Hold, BudgetDecision::Degrade);
2634            assert_ne!(BudgetDecision::Degrade, BudgetDecision::Upgrade);
2635        }
2636    }
2637
2638    // -----------------------------------------------------------------------
2639    // Budget Controller Integration + Telemetry Tests (bd-4kq0.3.2)
2640    // -----------------------------------------------------------------------
2641
2642    mod integration_tests {
2643        use super::super::*;
2644
2645        #[test]
2646        fn render_budget_without_controller_returns_no_telemetry() {
2647            let budget = RenderBudget::new(Duration::from_millis(16));
2648            assert!(budget.telemetry().is_none());
2649            assert!(budget.controller().is_none());
2650        }
2651
2652        #[test]
2653        fn render_budget_with_controller_returns_telemetry() {
2654            let budget = RenderBudget::new(Duration::from_millis(16))
2655                .with_controller(BudgetControllerConfig::default());
2656            assert!(budget.controller().is_some());
2657
2658            let telem = budget.telemetry().unwrap();
2659            assert_eq!(telem.level, DegradationLevel::Full);
2660            assert_eq!(telem.last_decision, BudgetDecision::Hold);
2661            assert_eq!(telem.frames_observed, 0);
2662            assert!(telem.in_warmup);
2663        }
2664
2665        #[test]
2666        fn telemetry_fields_update_after_next_frame() {
2667            let mut budget = RenderBudget::new(Duration::from_millis(16)).with_controller(
2668                BudgetControllerConfig {
2669                    eprocess: EProcessConfig {
2670                        warmup_frames: 0,
2671                        ..Default::default()
2672                    },
2673                    cooldown_frames: 0,
2674                    ..Default::default()
2675                },
2676            );
2677
2678            // Simulate a few frames
2679            for _ in 0..5 {
2680                budget.next_frame();
2681            }
2682
2683            let telem = budget.telemetry().unwrap();
2684            assert_eq!(telem.frames_observed, 5);
2685            assert!(!telem.in_warmup);
2686            // PID output should be non-positive (frames are fast, under budget)
2687            // but the exact value depends on timing, so just check it's finite
2688            assert!(telem.pid_output.is_finite());
2689            assert!(telem.e_value.is_finite());
2690        }
2691
2692        #[test]
2693        fn controller_next_frame_degrades_under_simulated_overload() {
2694            // We can't easily simulate slow frames in unit tests (thread::sleep
2695            // would be flaky), so we test the controller integration by verifying
2696            // the decision path works: attach controller, manually check that
2697            // the controller's level is reflected in the budget's degradation.
2698            let config = BudgetControllerConfig {
2699                target: Duration::from_millis(16),
2700                eprocess: EProcessConfig {
2701                    warmup_frames: 0,
2702                    ..Default::default()
2703                },
2704                cooldown_frames: 0,
2705                ..Default::default()
2706            };
2707            let mut ctrl = BudgetController::new(config);
2708
2709            // Feed severe overload to the controller directly
2710            for _ in 0..50 {
2711                ctrl.update(Duration::from_millis(40));
2712            }
2713
2714            // Controller should have degraded
2715            assert!(
2716                ctrl.level() > DegradationLevel::Full,
2717                "Controller should degrade: {:?}",
2718                ctrl.level()
2719            );
2720
2721            // Telemetry should reflect the degradation
2722            let telem = ctrl.telemetry();
2723            assert!(telem.level > DegradationLevel::Full);
2724            assert!(
2725                telem.pid_output > 0.0,
2726                "PID output should be positive under overload"
2727            );
2728            assert!(telem.e_value > 1.0, "E-value should grow under overload");
2729        }
2730
2731        #[test]
2732        fn next_frame_delegates_to_controller_when_attached() {
2733            // With a controller, next_frame should not use the simple
2734            // threshold-based upgrade path
2735            let mut budget = RenderBudget::new(Duration::from_millis(1000))
2736                .with_controller(BudgetControllerConfig::default());
2737
2738            // Degrade manually
2739            budget.degrade();
2740            assert_eq!(budget.degradation(), DegradationLevel::SimpleBorders);
2741
2742            // In legacy mode, next_frame would upgrade immediately (lots of budget).
2743            // With controller, it should hold because the controller hasn't seen
2744            // enough underload evidence yet.
2745            budget.next_frame();
2746
2747            // The controller may or may not upgrade depending on the single frame
2748            // measurement, but the key assertion is that the code path works.
2749            // With a fresh controller, the fast frame should eventually allow upgrade.
2750            // Just verify it doesn't panic and telemetry is populated.
2751            let telem = budget.telemetry().unwrap();
2752            assert_eq!(telem.frames_observed, 1);
2753        }
2754
2755        #[test]
2756        fn telemetry_is_copy_and_no_alloc() {
2757            let budget = RenderBudget::new(Duration::from_millis(16))
2758                .with_controller(BudgetControllerConfig::default());
2759
2760            let telem = budget.telemetry().unwrap();
2761            // BudgetTelemetry is Copy — verify by copying
2762            let telem2 = telem;
2763            assert_eq!(telem.level, telem2.level);
2764            assert_eq!(telem.e_value, telem2.e_value);
2765        }
2766
2767        #[test]
2768        fn telemetry_warmup_flag_transitions() {
2769            let mut budget = RenderBudget::new(Duration::from_millis(16)).with_controller(
2770                BudgetControllerConfig {
2771                    eprocess: EProcessConfig {
2772                        warmup_frames: 3,
2773                        ..Default::default()
2774                    },
2775                    ..Default::default()
2776                },
2777            );
2778
2779            // During warmup
2780            budget.next_frame();
2781            budget.next_frame();
2782            let telem = budget.telemetry().unwrap();
2783            assert!(telem.in_warmup, "Should be in warmup at frame 2");
2784
2785            // After warmup
2786            budget.next_frame();
2787            let telem = budget.telemetry().unwrap();
2788            assert!(!telem.in_warmup, "Should exit warmup at frame 3");
2789        }
2790
2791        #[test]
2792        fn phase_sub_budget_does_not_carry_controller() {
2793            let budget = RenderBudget::new(Duration::from_millis(100))
2794                .with_controller(BudgetControllerConfig::default());
2795
2796            let phase = budget.phase_budget(Phase::Render);
2797            assert!(
2798                phase.controller().is_none(),
2799                "Phase sub-budgets should not carry the controller"
2800            );
2801        }
2802
2803        #[test]
2804        fn controller_telemetry_tracks_frames_since_change() {
2805            let mut ctrl = BudgetController::new(BudgetControllerConfig {
2806                eprocess: EProcessConfig {
2807                    warmup_frames: 0,
2808                    ..Default::default()
2809                },
2810                cooldown_frames: 0,
2811                ..Default::default()
2812            });
2813
2814            // On-target frames: frames_since_change should increase
2815            for i in 1..=5 {
2816                ctrl.update(Duration::from_millis(16));
2817                let telem = ctrl.telemetry();
2818                assert_eq!(
2819                    telem.frames_since_change, i,
2820                    "frames_since_change should be {} after {} frames",
2821                    i, i
2822                );
2823            }
2824        }
2825
2826        #[test]
2827        fn telemetry_last_decision_reflects_controller_decision() {
2828            let mut ctrl = BudgetController::new(BudgetControllerConfig {
2829                eprocess: EProcessConfig {
2830                    warmup_frames: 0,
2831                    ..Default::default()
2832                },
2833                cooldown_frames: 0,
2834                ..Default::default()
2835            });
2836
2837            // On-target: should hold
2838            ctrl.update(Duration::from_millis(16));
2839            assert_eq!(ctrl.telemetry().last_decision, BudgetDecision::Hold);
2840
2841            // Feed enough overload to trigger degrade
2842            let mut saw_degrade = false;
2843            for _ in 0..50 {
2844                let d = ctrl.update(Duration::from_millis(50));
2845                if d == BudgetDecision::Degrade {
2846                    saw_degrade = true;
2847                    assert_eq!(ctrl.telemetry().last_decision, BudgetDecision::Degrade);
2848                    break;
2849                }
2850            }
2851            assert!(saw_degrade, "Should have seen a Degrade decision");
2852        }
2853
2854        #[test]
2855        fn perf_overhead_controller_update_is_fast() {
2856            // Verify the controller update is a lightweight arithmetic operation.
2857            // We run 10_000 iterations and check they complete quickly.
2858            // This is a smoke test, not a precise benchmark (that's bd-4kq0.3.3).
2859            let mut ctrl = BudgetController::new(BudgetControllerConfig::default());
2860
2861            let start = Instant::now();
2862            for _ in 0..10_000 {
2863                ctrl.update(Duration::from_millis(16));
2864            }
2865            let elapsed = start.elapsed();
2866
2867            // 10k iterations should complete in well under 10ms on any modern CPU.
2868            // At 16ms target, 2% overhead = 0.32ms per frame, so 10k frames
2869            // budget = 3.2 seconds worth of overhead budget. We check <50ms total.
2870            assert!(
2871                elapsed < Duration::from_millis(50),
2872                "10k controller updates took {:?}, expected <50ms",
2873                elapsed
2874            );
2875        }
2876
2877        #[test]
2878        fn perf_overhead_telemetry_snapshot_is_fast() {
2879            let mut ctrl = BudgetController::new(BudgetControllerConfig::default());
2880            ctrl.update(Duration::from_millis(16));
2881
2882            let start = Instant::now();
2883            for _ in 0..10_000 {
2884                let _telem = ctrl.telemetry();
2885            }
2886            let elapsed = start.elapsed();
2887
2888            assert!(
2889                elapsed < Duration::from_millis(10),
2890                "10k telemetry snapshots took {:?}, expected <10ms",
2891                elapsed
2892            );
2893        }
2894    }
2895
2896    // -----------------------------------------------------------------------
2897    // Budget Stability + E2E Replay Tests (bd-4kq0.3.3)
2898    // -----------------------------------------------------------------------
2899
2900    mod stability_tests {
2901        use super::super::*;
2902
2903        #[derive(Debug, Clone)]
2904        struct CampaignFrameLog {
2905            frame_idx: u64,
2906            phase: &'static str,
2907            frame_time_us: u64,
2908            telemetry: BudgetTelemetry,
2909        }
2910
2911        /// Helper: create a controller with minimal warmup/cooldown for testing.
2912        fn fast_controller(target_ms: u64) -> BudgetController {
2913            BudgetController::new(BudgetControllerConfig {
2914                target: Duration::from_millis(target_ms),
2915                eprocess: EProcessConfig {
2916                    warmup_frames: 0,
2917                    ..Default::default()
2918                },
2919                cooldown_frames: 0,
2920                ..Default::default()
2921            })
2922        }
2923
2924        /// Helper: run a frame time trace through the controller and collect
2925        /// JSONL-style telemetry records (as structured tuples).
2926        /// Returns `(frame_index, frame_time_us, telemetry)` for each frame.
2927        fn run_trace(
2928            ctrl: &mut BudgetController,
2929            trace: &[Duration],
2930        ) -> Vec<(u64, u64, BudgetTelemetry)> {
2931            trace
2932                .iter()
2933                .enumerate()
2934                .map(|(i, &ft)| {
2935                    ctrl.update(ft);
2936                    let telem = ctrl.telemetry();
2937                    (i as u64, ft.as_micros() as u64, telem)
2938                })
2939                .collect()
2940        }
2941
2942        /// Run a labeled phase campaign and collect deterministic replay logs.
2943        fn run_campaign(
2944            ctrl: &mut BudgetController,
2945            phases: &[(&'static str, usize, Duration)],
2946        ) -> Vec<CampaignFrameLog> {
2947            let mut logs = Vec::new();
2948            let mut frame_idx: u64 = 0;
2949            for &(phase, count, frame_time) in phases {
2950                for _ in 0..count {
2951                    ctrl.update(frame_time);
2952                    logs.push(CampaignFrameLog {
2953                        frame_idx,
2954                        phase,
2955                        frame_time_us: frame_time.as_micros() as u64,
2956                        telemetry: ctrl.telemetry(),
2957                    });
2958                    frame_idx = frame_idx.saturating_add(1);
2959                }
2960            }
2961            logs
2962        }
2963
2964        /// Count level transitions in a trace log.
2965        fn count_transitions(log: &[(u64, u64, BudgetTelemetry)]) -> u32 {
2966            let mut transitions = 0u32;
2967            for pair in log.windows(2) {
2968                if pair[0].2.level != pair[1].2.level {
2969                    transitions += 1;
2970                }
2971            }
2972            transitions
2973        }
2974
2975        // --- e2e_burst_logs ---
2976
2977        #[test]
2978        fn e2e_burst_logs_no_oscillation() {
2979            // Simulate bursty output: alternating bursts of slow frames
2980            // and calm periods. Verify no oscillation (bounded transitions).
2981            let mut ctrl = fast_controller(16);
2982
2983            let mut trace = Vec::new();
2984            for _cycle in 0..5 {
2985                // Burst: 10 frames at 40ms
2986                for _ in 0..10 {
2987                    trace.push(Duration::from_millis(40));
2988                }
2989                // Calm: 20 frames at 16ms
2990                for _ in 0..20 {
2991                    trace.push(Duration::from_millis(16));
2992                }
2993            }
2994
2995            let log = run_trace(&mut ctrl, &trace);
2996
2997            // Count level transitions. Under bursty load, transitions should
2998            // be bounded — no rapid oscillation. With 5 cycles of 30 frames
2999            // each (150 total), we expect at most ~15 transitions (degrade
3000            // during each burst, upgrade during each calm).
3001            let transitions = count_transitions(&log);
3002            assert!(
3003                transitions < 20,
3004                "Too many transitions under bursty load: {} (expected <20)",
3005                transitions
3006            );
3007
3008            // Verify all telemetry fields are populated
3009            for (frame, ft_us, telem) in &log {
3010                assert!(
3011                    telem.pid_output.is_finite(),
3012                    "frame {}: NaN pid_output",
3013                    frame
3014                );
3015                assert!(telem.e_value.is_finite(), "frame {}: NaN e_value", frame);
3016                assert!(telem.pid_p.is_finite(), "frame {}: NaN pid_p", frame);
3017                assert!(telem.pid_i.is_finite(), "frame {}: NaN pid_i", frame);
3018                assert!(telem.pid_d.is_finite(), "frame {}: NaN pid_d", frame);
3019                assert!(*ft_us > 0, "frame {}: zero frame time", frame);
3020            }
3021        }
3022
3023        #[test]
3024        fn e2e_burst_recovers_after_moderate_overload() {
3025            // Moderate bursts (30ms vs 16ms target) followed by calm periods.
3026            // The controller may degrade during bursts, but should recover
3027            // during calm periods — final state should not be SkipFrame.
3028            let mut ctrl = BudgetController::new(BudgetControllerConfig {
3029                target: Duration::from_millis(16),
3030                eprocess: EProcessConfig {
3031                    warmup_frames: 5,
3032                    ..Default::default()
3033                },
3034                cooldown_frames: 3,
3035                ..Default::default()
3036            });
3037
3038            let mut trace = Vec::new();
3039            for _cycle in 0..3 {
3040                // Moderate burst
3041                for _ in 0..15 {
3042                    trace.push(Duration::from_millis(30));
3043                }
3044                // Extended calm to allow recovery
3045                for _ in 0..50 {
3046                    trace.push(Duration::from_millis(10));
3047                }
3048            }
3049
3050            let log = run_trace(&mut ctrl, &trace);
3051
3052            // After each calm period, level should have recovered below Skeleton.
3053            // Check at the end of each calm phase (frames 64, 129, 194).
3054            for cycle in 0..3 {
3055                let calm_end = (cycle + 1) * 65 - 1;
3056                if calm_end < log.len() {
3057                    assert!(
3058                        log[calm_end].2.level < DegradationLevel::SkipFrame,
3059                        "cycle {}: should recover after calm period, got {:?} at frame {}",
3060                        cycle,
3061                        log[calm_end].2.level,
3062                        calm_end
3063                    );
3064                }
3065            }
3066
3067            // Final level should be better than Skeleton
3068            let final_level = log.last().unwrap().2.level;
3069            assert!(
3070                final_level < DegradationLevel::Skeleton,
3071                "Final level should recover below Skeleton: {:?}",
3072                final_level
3073            );
3074        }
3075
3076        // --- e2e_idle_to_burst ---
3077
3078        #[test]
3079        fn e2e_idle_to_burst_recovery() {
3080            // Start idle (well under budget), then sudden burst, then back to idle.
3081            // Verify: fast recovery without over-degrading.
3082            let mut ctrl = fast_controller(16);
3083
3084            let mut trace = Vec::new();
3085            // Phase 1: idle (8ms frames)
3086            for _ in 0..50 {
3087                trace.push(Duration::from_millis(8));
3088            }
3089            // Phase 2: sudden burst (50ms frames)
3090            for _ in 0..20 {
3091                trace.push(Duration::from_millis(50));
3092            }
3093            // Phase 3: recovery (8ms frames)
3094            for _ in 0..100 {
3095                trace.push(Duration::from_millis(8));
3096            }
3097
3098            let log = run_trace(&mut ctrl, &trace);
3099
3100            // After idle phase (frame 49), should still be Full
3101            assert_eq!(
3102                log[49].2.level,
3103                DegradationLevel::Full,
3104                "Should be Full during idle phase"
3105            );
3106
3107            // During burst, should degrade
3108            let max_during_burst = log[50..70].iter().map(|(_, _, t)| t.level).max().unwrap();
3109            assert!(
3110                max_during_burst > DegradationLevel::Full,
3111                "Should degrade during burst"
3112            );
3113
3114            // After recovery (last 20 frames), should have recovered toward Full
3115            let final_level = log.last().unwrap().2.level;
3116            assert!(
3117                final_level < max_during_burst,
3118                "Should recover after burst: final={:?}, max_during_burst={:?}",
3119                final_level,
3120                max_during_burst
3121            );
3122        }
3123
3124        #[test]
3125        fn e2e_idle_to_burst_no_over_degrade() {
3126            // A brief burst (5 frames) should not cause more than 1-2 levels
3127            // of degradation, even with zero warmup.
3128            let mut ctrl = fast_controller(16);
3129
3130            // Idle
3131            for _ in 0..30 {
3132                ctrl.update(Duration::from_millis(8));
3133            }
3134
3135            // Brief burst (only 5 frames)
3136            for _ in 0..5 {
3137                ctrl.update(Duration::from_millis(40));
3138            }
3139
3140            // Check degradation is modest
3141            let level = ctrl.level();
3142            assert!(
3143                level <= DegradationLevel::NoStyling,
3144                "Brief burst should not over-degrade: {:?}",
3145                level
3146            );
3147        }
3148
3149        #[test]
3150        fn e2e_overload_campaign_burst_sustained_recovery_with_replay_logs() {
3151            // bd-2vr05.15.4.5:
3152            // 1) burst overload
3153            // 2) sustained overload
3154            // 3) recovery/underload
3155            //
3156            // This test validates full-range degradation, so remove the floor.
3157            let phases: [(&str, usize, Duration); 3] = [
3158                ("burst_overload", 24, Duration::from_millis(28)),
3159                ("sustained_overload", 80, Duration::from_millis(52)),
3160                ("recovery_underload", 140, Duration::from_millis(8)),
3161            ];
3162
3163            let mut ctrl = BudgetController::new(BudgetControllerConfig {
3164                target: Duration::from_millis(16),
3165                eprocess: EProcessConfig {
3166                    warmup_frames: 0,
3167                    ..Default::default()
3168                },
3169                cooldown_frames: 0,
3170                degradation_floor: DegradationLevel::SkipFrame,
3171                ..Default::default()
3172            });
3173            let logs = run_campaign(&mut ctrl, &phases);
3174            assert!(!logs.is_empty(), "campaign logs must be non-empty");
3175
3176            let mut burst_degrades = 0u32;
3177            let mut sustained_degrades = 0u32;
3178            let mut sustained_degraded_frames = 0u32;
3179            let mut recovery_upgrades = 0u32;
3180            let mut max_level = DegradationLevel::Full;
3181
3182            for log in &logs {
3183                let telem = &log.telemetry;
3184                if telem.level > max_level {
3185                    max_level = telem.level;
3186                }
3187                if log.phase == "burst_overload" && telem.last_decision == BudgetDecision::Degrade {
3188                    burst_degrades = burst_degrades.saturating_add(1);
3189                }
3190                if log.phase == "sustained_overload"
3191                    && telem.last_decision == BudgetDecision::Degrade
3192                {
3193                    sustained_degrades = sustained_degrades.saturating_add(1);
3194                }
3195                if log.phase == "sustained_overload" && telem.level > DegradationLevel::Full {
3196                    sustained_degraded_frames = sustained_degraded_frames.saturating_add(1);
3197                }
3198                if log.phase == "recovery_underload"
3199                    && telem.last_decision == BudgetDecision::Upgrade
3200                {
3201                    recovery_upgrades = recovery_upgrades.saturating_add(1);
3202                }
3203
3204                // Semantic integrity invariants (no corruption under degradation)
3205                assert!(
3206                    telem.level <= DegradationLevel::SkipFrame,
3207                    "frame {}: invalid degradation level {:?}",
3208                    log.frame_idx,
3209                    telem.level
3210                );
3211                assert!(
3212                    telem.e_value.is_finite() && telem.e_value > 0.0,
3213                    "frame {}: invalid e_value {}",
3214                    log.frame_idx,
3215                    telem.e_value
3216                );
3217                assert!(
3218                    telem.pid_output.is_finite(),
3219                    "frame {}: invalid pid_output {}",
3220                    log.frame_idx,
3221                    telem.pid_output
3222                );
3223            }
3224
3225            // Adjacent level changes must be stepwise (no jump corruption).
3226            for pair in logs.windows(2) {
3227                let prev = pair[0].telemetry.level.level();
3228                let curr = pair[1].telemetry.level.level();
3229                let delta = (curr as i16 - prev as i16).unsigned_abs();
3230                assert!(
3231                    delta <= 1,
3232                    "frame {}->{} level jump {}: {:?} -> {:?}",
3233                    pair[0].frame_idx,
3234                    pair[1].frame_idx,
3235                    delta,
3236                    pair[0].telemetry.level,
3237                    pair[1].telemetry.level
3238                );
3239            }
3240
3241            assert!(
3242                burst_degrades > 0,
3243                "burst phase should trigger degradation decisions"
3244            );
3245            assert!(
3246                sustained_degrades > 0 || sustained_degraded_frames > 0,
3247                "sustained overload phase should maintain degraded operation"
3248            );
3249            assert!(
3250                max_level >= DegradationLevel::Skeleton,
3251                "sustained overload should reach deep degradation (got {:?})",
3252                max_level
3253            );
3254            assert!(
3255                recovery_upgrades > 0,
3256                "recovery phase should trigger upgrade decisions"
3257            );
3258
3259            let final_level = logs
3260                .last()
3261                .map(|entry| entry.telemetry.level)
3262                .unwrap_or(DegradationLevel::SkipFrame);
3263            assert!(
3264                final_level < max_level,
3265                "final level should recover below peak degradation: final={:?} peak={:?}",
3266                final_level,
3267                max_level
3268            );
3269
3270            // Deterministic replay contract: same scenario -> same decisions/telemetry.
3271            let mut ctrl_replay = BudgetController::new(BudgetControllerConfig {
3272                target: Duration::from_millis(16),
3273                eprocess: EProcessConfig {
3274                    warmup_frames: 0,
3275                    ..Default::default()
3276                },
3277                cooldown_frames: 0,
3278                degradation_floor: DegradationLevel::SkipFrame,
3279                ..Default::default()
3280            });
3281            let replay_logs = run_campaign(&mut ctrl_replay, &phases);
3282            assert_eq!(
3283                logs.len(),
3284                replay_logs.len(),
3285                "log length mismatch in replay"
3286            );
3287            for (lhs, rhs) in logs.iter().zip(replay_logs.iter()) {
3288                assert_eq!(lhs.frame_idx, rhs.frame_idx);
3289                assert_eq!(lhs.phase, rhs.phase);
3290                assert_eq!(lhs.frame_time_us, rhs.frame_time_us);
3291                assert_eq!(lhs.telemetry.schema_version, rhs.telemetry.schema_version);
3292                assert_eq!(lhs.telemetry.level, rhs.telemetry.level);
3293                assert_eq!(lhs.telemetry.last_decision, rhs.telemetry.last_decision);
3294                assert_eq!(
3295                    lhs.telemetry.decision_reason, rhs.telemetry.decision_reason,
3296                    "decision_reason mismatch at frame {}",
3297                    lhs.frame_idx
3298                );
3299                assert_eq!(
3300                    lhs.telemetry.transition_seq, rhs.telemetry.transition_seq,
3301                    "transition_seq mismatch at frame {}",
3302                    lhs.frame_idx
3303                );
3304                assert_eq!(
3305                    lhs.telemetry.transition_correlation_id,
3306                    rhs.telemetry.transition_correlation_id,
3307                    "transition_correlation_id mismatch at frame {}",
3308                    lhs.frame_idx
3309                );
3310                assert!(
3311                    (lhs.telemetry.pid_output - rhs.telemetry.pid_output).abs() < 1e-12,
3312                    "pid_output mismatch at frame {}",
3313                    lhs.frame_idx
3314                );
3315                assert!(
3316                    (lhs.telemetry.e_value - rhs.telemetry.e_value).abs() < 1e-12,
3317                    "e_value mismatch at frame {}",
3318                    lhs.frame_idx
3319                );
3320            }
3321
3322            // Replay-grade diagnostics for controller postmortems.
3323            for entry in &logs {
3324                let t = &entry.telemetry;
3325                eprintln!(
3326                    r#"{{"event":"control_campaign_frame","schema_version":{},"scenario":"bd-2vr05.15.4.5","frame_idx":{},"phase":"{}","frame_time_us":{},"decision":"{}","decision_reason":"{}","transition_seq":{},"transition_correlation_id":{},"level":"{}","pid_output":{:.6},"pid_p":{:.6},"pid_i":{:.6},"pid_d":{:.6},"e_value":{:.6},"frame_time_ms":{:.6},"target_ms":{:.6},"pid_gate_threshold":{:.6},"pid_gate_margin":{:.6},"evidence_threshold":{:.6},"evidence_margin":{:.6},"frames_observed":{},"frames_since_change":{}}}"#,
3327                    t.schema_version,
3328                    entry.frame_idx,
3329                    entry.phase,
3330                    entry.frame_time_us,
3331                    t.last_decision.as_str(),
3332                    t.decision_reason.as_str(),
3333                    t.transition_seq,
3334                    t.transition_correlation_id,
3335                    t.level.as_str(),
3336                    t.pid_output,
3337                    t.pid_p,
3338                    t.pid_i,
3339                    t.pid_d,
3340                    t.e_value,
3341                    t.frame_time_ms,
3342                    t.target_ms,
3343                    t.pid_gate_threshold,
3344                    t.pid_gate_margin,
3345                    t.evidence_threshold,
3346                    t.evidence_margin,
3347                    t.frames_observed,
3348                    t.frames_since_change
3349                );
3350            }
3351            eprintln!(
3352                r#"{{"event":"control_campaign_summary","schema_version":{},"scenario":"bd-2vr05.15.4.5","frames":{},"burst_degrades":{},"sustained_degrades":{},"recovery_upgrades":{},"peak_level":"{}","final_level":"{}"}}"#,
3353                BUDGET_TELEMETRY_SCHEMA_VERSION,
3354                logs.len(),
3355                burst_degrades,
3356                sustained_degrades,
3357                recovery_upgrades,
3358                max_level.as_str(),
3359                final_level.as_str()
3360            );
3361        }
3362
3363        // --- property_random_load ---
3364
3365        #[test]
3366        fn property_random_load_hysteresis_bounds() {
3367            // Verify: degradation changes are bounded by hysteresis constraints.
3368            // Specifically, level can only change by 1 step per decision.
3369            let mut ctrl = fast_controller(16);
3370
3371            // Generate a deterministic pseudo-random load trace using a simple
3372            // linear congruential generator (no std::rand dependency).
3373            let mut rng_state: u64 = 0xDEAD_BEEF_CAFE_BABE;
3374            let mut trace = Vec::new();
3375            for _ in 0..1000 {
3376                // LCG: next = (a * state + c) mod m
3377                rng_state = rng_state
3378                    .wrapping_mul(6_364_136_223_846_793_005)
3379                    .wrapping_add(1_442_695_040_888_963_407);
3380                // Map to frame time: 4ms..80ms
3381                let frame_ms = 4 + ((rng_state >> 33) % 77);
3382                trace.push(Duration::from_millis(frame_ms));
3383            }
3384
3385            let log = run_trace(&mut ctrl, &trace);
3386
3387            // Property 1: Level only changes by at most 1 step per frame
3388            for pair in log.windows(2) {
3389                let prev = pair[0].2.level.level();
3390                let curr = pair[1].2.level.level();
3391                let delta = (curr as i16 - prev as i16).unsigned_abs();
3392                assert!(
3393                    delta <= 1,
3394                    "Level jumped {} steps at frame {}: {:?} -> {:?}",
3395                    delta,
3396                    pair[1].0,
3397                    pair[0].2.level,
3398                    pair[1].2.level
3399                );
3400            }
3401
3402            // Property 2: Level never exceeds valid range
3403            for (frame, _, telem) in &log {
3404                assert!(
3405                    telem.level <= DegradationLevel::SkipFrame,
3406                    "frame {}: level out of range: {:?}",
3407                    frame,
3408                    telem.level
3409                );
3410            }
3411
3412            // Property 3: All numeric fields are finite
3413            for (frame, _, telem) in &log {
3414                assert!(
3415                    telem.pid_output.is_finite(),
3416                    "frame {}: NaN pid_output",
3417                    frame
3418                );
3419                assert!(telem.pid_p.is_finite(), "frame {}: NaN pid_p", frame);
3420                assert!(telem.pid_i.is_finite(), "frame {}: NaN pid_i", frame);
3421                assert!(telem.pid_d.is_finite(), "frame {}: NaN pid_d", frame);
3422                assert!(telem.e_value.is_finite(), "frame {}: NaN e_value", frame);
3423                assert!(
3424                    telem.e_value > 0.0,
3425                    "frame {}: e_value not positive: {}",
3426                    frame,
3427                    telem.e_value
3428                );
3429            }
3430        }
3431
3432        #[test]
3433        fn property_random_load_bounded_transitions() {
3434            // Under random load, transitions should be bounded and not exceed
3435            // a reasonable rate (no rapid oscillation).
3436            let mut ctrl = BudgetController::new(BudgetControllerConfig {
3437                target: Duration::from_millis(16),
3438                eprocess: EProcessConfig {
3439                    warmup_frames: 5,
3440                    ..Default::default()
3441                },
3442                cooldown_frames: 3,
3443                ..Default::default()
3444            });
3445
3446            // Deterministic pseudo-random trace
3447            let mut rng_state: u64 = 0x1234_5678_9ABC_DEF0;
3448            let mut trace = Vec::new();
3449            for _ in 0..500 {
3450                rng_state = rng_state
3451                    .wrapping_mul(6_364_136_223_846_793_005)
3452                    .wrapping_add(1_442_695_040_888_963_407);
3453                let frame_ms = 8 + ((rng_state >> 33) % 40);
3454                trace.push(Duration::from_millis(frame_ms));
3455            }
3456
3457            let log = run_trace(&mut ctrl, &trace);
3458            let transitions = count_transitions(&log);
3459
3460            // With cooldown=3 and 500 frames, max theoretical transitions = 500/4 = 125.
3461            // In practice with hysteresis + e-process gating, much less.
3462            assert!(
3463                transitions < 80,
3464                "Too many transitions under random load: {} (expected <80 with cooldown=3)",
3465                transitions
3466            );
3467        }
3468
3469        #[test]
3470        fn property_deterministic_replay() {
3471            // Same trace should produce identical telemetry every time.
3472            let trace: Vec<Duration> = (0..100)
3473                .map(|i| Duration::from_millis(10 + (i * 7 % 30)))
3474                .collect();
3475
3476            let mut ctrl1 = fast_controller(16);
3477            let log1 = run_trace(&mut ctrl1, &trace);
3478
3479            let mut ctrl2 = fast_controller(16);
3480            let log2 = run_trace(&mut ctrl2, &trace);
3481
3482            for (r1, r2) in log1.iter().zip(log2.iter()) {
3483                assert_eq!(r1.0, r2.0, "frame index mismatch");
3484                assert_eq!(r1.1, r2.1, "frame time mismatch");
3485                assert_eq!(r1.2.schema_version, r2.2.schema_version);
3486                assert_eq!(r1.2.level, r2.2.level, "level mismatch at frame {}", r1.0);
3487                assert_eq!(
3488                    r1.2.last_decision, r2.2.last_decision,
3489                    "decision mismatch at frame {}",
3490                    r1.0
3491                );
3492                assert_eq!(
3493                    r1.2.decision_reason, r2.2.decision_reason,
3494                    "decision_reason mismatch at frame {}",
3495                    r1.0
3496                );
3497                assert_eq!(
3498                    r1.2.transition_seq, r2.2.transition_seq,
3499                    "transition_seq mismatch at frame {}",
3500                    r1.0
3501                );
3502                assert_eq!(
3503                    r1.2.transition_correlation_id, r2.2.transition_correlation_id,
3504                    "transition_correlation_id mismatch at frame {}",
3505                    r1.0
3506                );
3507                assert!(
3508                    (r1.2.pid_output - r2.2.pid_output).abs() < 1e-10,
3509                    "pid_output mismatch at frame {}: {} vs {}",
3510                    r1.0,
3511                    r1.2.pid_output,
3512                    r2.2.pid_output
3513                );
3514                assert!(
3515                    (r1.2.e_value - r2.2.e_value).abs() < 1e-10,
3516                    "e_value mismatch at frame {}: {} vs {}",
3517                    r1.0,
3518                    r1.2.e_value,
3519                    r2.2.e_value
3520                );
3521            }
3522        }
3523
3524        // --- JSONL schema validation ---
3525
3526        #[test]
3527        fn telemetry_jsonl_fields_complete() {
3528            // Verify all JSONL schema fields are accessible from BudgetTelemetry.
3529            let mut ctrl = fast_controller(16);
3530            ctrl.update(Duration::from_millis(20));
3531
3532            let telem = ctrl.telemetry();
3533
3534            // All schema fields present and accessible:
3535            let _schema_version: u16 = telem.schema_version;
3536            let _degradation: &str = telem.level.as_str();
3537            let _pid_p: f64 = telem.pid_p;
3538            let _pid_i: f64 = telem.pid_i;
3539            let _pid_d: f64 = telem.pid_d;
3540            let _e_value: f64 = telem.e_value;
3541            let _decision: &str = telem.last_decision.as_str();
3542            let _reason: &str = telem.decision_reason.as_str();
3543            let _transition_seq: u64 = telem.transition_seq;
3544            let _transition_correlation_id: u64 = telem.transition_correlation_id;
3545            let _frame_time_ms: f64 = telem.frame_time_ms;
3546            let _target_ms: f64 = telem.target_ms;
3547            let _pid_gate_threshold: f64 = telem.pid_gate_threshold;
3548            let _pid_gate_margin: f64 = telem.pid_gate_margin;
3549            let _evidence_threshold: f64 = telem.evidence_threshold;
3550            let _evidence_margin: f64 = telem.evidence_margin;
3551            let _frames: u32 = telem.frames_observed;
3552
3553            // Verify decision string mapping
3554            assert_eq!(BudgetDecision::Hold.as_str(), "stay");
3555            assert_eq!(BudgetDecision::Degrade.as_str(), "degrade");
3556            assert_eq!(BudgetDecision::Upgrade.as_str(), "upgrade");
3557            assert_eq!(
3558                BUDGET_TELEMETRY_SCHEMA_VERSION, telem.schema_version,
3559                "schema version mismatch"
3560            );
3561        }
3562
3563        #[test]
3564        fn telemetry_transition_records_correlation_reason_and_evidence() {
3565            let mut ctrl = fast_controller(16);
3566
3567            // Drive toward a degrade transition.
3568            let mut degrade_telem = None;
3569            for _ in 0..64 {
3570                ctrl.update(Duration::from_millis(48));
3571                let telem = ctrl.telemetry();
3572                if telem.last_decision == BudgetDecision::Degrade {
3573                    degrade_telem = Some(telem);
3574                    break;
3575                }
3576            }
3577            let degrade_telem =
3578                degrade_telem.expect("expected degrade transition with correlation metadata");
3579            assert_eq!(
3580                degrade_telem.decision_reason,
3581                BudgetDecisionReason::OverloadEvidencePassed
3582            );
3583            assert!(
3584                degrade_telem.transition_seq > 0,
3585                "transition_seq should increment on transitions"
3586            );
3587            assert!(
3588                degrade_telem.transition_correlation_id > 0,
3589                "transition correlation id should be populated on transitions"
3590            );
3591            assert!(
3592                degrade_telem.pid_gate_margin > 0.0,
3593                "degrade transition should have positive PID gate margin"
3594            );
3595            assert!(
3596                degrade_telem.evidence_margin > 0.0,
3597                "degrade transition should have positive evidence margin"
3598            );
3599
3600            // Drive toward an upgrade transition.
3601            let mut upgrade_telem = None;
3602            for _ in 0..160 {
3603                ctrl.update(Duration::from_millis(4));
3604                let telem = ctrl.telemetry();
3605                if telem.last_decision == BudgetDecision::Upgrade {
3606                    upgrade_telem = Some(telem);
3607                    break;
3608                }
3609            }
3610            let upgrade_telem =
3611                upgrade_telem.expect("expected upgrade transition with correlation metadata");
3612            assert_eq!(
3613                upgrade_telem.decision_reason,
3614                BudgetDecisionReason::UnderloadEvidencePassed
3615            );
3616            assert!(
3617                upgrade_telem.transition_seq >= degrade_telem.transition_seq,
3618                "transition sequence should be monotonic"
3619            );
3620            assert!(
3621                upgrade_telem.transition_correlation_id >= degrade_telem.transition_correlation_id,
3622                "transition correlation id should be monotonic"
3623            );
3624            assert!(
3625                upgrade_telem.pid_gate_margin > 0.0,
3626                "upgrade transition should have positive PID gate margin"
3627            );
3628            assert!(
3629                upgrade_telem.evidence_margin > 0.0,
3630                "upgrade transition should have positive evidence margin"
3631            );
3632        }
3633
3634        #[test]
3635        fn telemetry_pid_components_sum_to_output() {
3636            // Verify P + I + D == total PID output.
3637            let mut ctrl = fast_controller(16);
3638
3639            for ms in [10u64, 16, 20, 30, 8, 50] {
3640                ctrl.update(Duration::from_millis(ms));
3641                let telem = ctrl.telemetry();
3642                let sum = telem.pid_p + telem.pid_i + telem.pid_d;
3643                assert!(
3644                    (sum - telem.pid_output).abs() < 1e-10,
3645                    "P+I+D != output at {}ms: {} + {} + {} = {} != {}",
3646                    ms,
3647                    telem.pid_p,
3648                    telem.pid_i,
3649                    telem.pid_d,
3650                    sum,
3651                    telem.pid_output
3652                );
3653            }
3654        }
3655    }
3656
3657    // -----------------------------------------------------------------------
3658    // Edge-case tests (bd-1x69n)
3659    // -----------------------------------------------------------------------
3660
3661    mod edge_case_tests {
3662        use super::super::*;
3663
3664        // --- PID edge cases ---
3665
3666        #[test]
3667        fn pid_negative_integral_windup() {
3668            // Sustained negative error should clamp integral at -integral_max
3669            let mut state = PidState::default();
3670            let gains = PidGains {
3671                integral_max: 3.0,
3672                ..Default::default()
3673            };
3674
3675            for _ in 0..200 {
3676                state.update(-10.0, &gains);
3677            }
3678
3679            assert!(
3680                state.integral >= -3.0 - f64::EPSILON,
3681                "Negative integral should be clamped to -max: {}",
3682                state.integral
3683            );
3684            assert!(
3685                state.integral <= -3.0 + f64::EPSILON,
3686                "Negative integral should saturate at -max: {}",
3687                state.integral
3688            );
3689        }
3690
3691        #[test]
3692        fn pid_zero_gains_zero_output() {
3693            let mut state = PidState::default();
3694            let gains = PidGains {
3695                kp: 0.0,
3696                ki: 0.0,
3697                kd: 0.0,
3698                integral_max: 5.0,
3699            };
3700
3701            let u = state.update(42.0, &gains);
3702            assert!(
3703                u.abs() < 1e-10,
3704                "Zero gains should yield zero output: {}",
3705                u
3706            );
3707        }
3708
3709        #[test]
3710        fn pid_large_error_stays_finite() {
3711            let mut state = PidState::default();
3712            let gains = PidGains::default();
3713
3714            // Very large error
3715            let u = state.update(1e12, &gains);
3716            assert!(
3717                u.is_finite(),
3718                "PID output should be finite for large error: {}",
3719                u
3720            );
3721
3722            // Integral should be clamped
3723            assert!(
3724                state.integral <= gains.integral_max + f64::EPSILON,
3725                "Integral should be clamped: {}",
3726                state.integral
3727            );
3728        }
3729
3730        #[test]
3731        fn pid_alternating_error_derivative_responds() {
3732            let mut state = PidState::default();
3733            let gains = PidGains::default();
3734
3735            // Alternating +1/-1 error
3736            let u1 = state.update(1.0, &gains);
3737            let u2 = state.update(-1.0, &gains);
3738
3739            // Derivative component for second call: Kd * (-1.0 - 1.0) = 0.2 * -2.0 = -0.4
3740            // So u2 should have negative derivative contribution
3741            assert!(
3742                u2 < u1,
3743                "Alternating error should reduce output: u1={}, u2={}",
3744                u1,
3745                u2
3746            );
3747        }
3748
3749        #[test]
3750        fn pid_telemetry_terms_match_after_update() {
3751            let mut state = PidState::default();
3752            let gains = PidGains::default();
3753
3754            state.update(2.0, &gains);
3755
3756            // P = Kp * error = 0.5 * 2.0 = 1.0
3757            assert!(
3758                (state.last_p - 1.0).abs() < 1e-10,
3759                "P term: {}",
3760                state.last_p
3761            );
3762            // I = Ki * integral = 0.05 * 2.0 = 0.1
3763            assert!(
3764                (state.last_i - 0.1).abs() < 1e-10,
3765                "I term: {}",
3766                state.last_i
3767            );
3768            // D = Kd * (error - prev_error) = 0.2 * (2.0 - 0.0) = 0.4
3769            assert!(
3770                (state.last_d - 0.4).abs() < 1e-10,
3771                "D term: {}",
3772                state.last_d
3773            );
3774        }
3775
3776        #[test]
3777        fn pid_integral_clamping_symmetric() {
3778            let mut state = PidState::default();
3779            let gains = PidGains {
3780                integral_max: 1.0,
3781                ..Default::default()
3782            };
3783
3784            // Positive saturation
3785            for _ in 0..50 {
3786                state.update(100.0, &gains);
3787            }
3788            let pos_integral = state.integral;
3789
3790            state.reset();
3791
3792            // Negative saturation
3793            for _ in 0..50 {
3794                state.update(-100.0, &gains);
3795            }
3796            let neg_integral = state.integral;
3797
3798            assert!(
3799                (pos_integral + neg_integral).abs() < f64::EPSILON,
3800                "Clamping should be symmetric: pos={}, neg={}",
3801                pos_integral,
3802                neg_integral
3803            );
3804        }
3805
3806        // --- E-process edge cases ---
3807
3808        #[test]
3809        fn eprocess_first_frame_initializes_mean() {
3810            let mut state = EProcessState::default();
3811            let config = EProcessConfig::default();
3812
3813            state.update(25.0, 16.0, &config);
3814
3815            assert!(
3816                (state.mean_ema - 25.0).abs() < f64::EPSILON,
3817                "First frame should set mean_ema directly: {}",
3818                state.mean_ema
3819            );
3820            assert!(
3821                (state.sigma_ema - config.sigma_floor_ms).abs() < f64::EPSILON,
3822                "First frame should set sigma_ema to floor: {}",
3823                state.sigma_ema
3824            );
3825            assert_eq!(state.frames_observed, 1);
3826        }
3827
3828        #[test]
3829        fn eprocess_e_value_clamped_at_upper_bound() {
3830            let mut state = EProcessState::default();
3831            let config = EProcessConfig {
3832                lambda: 2.0, // High sensitivity to force rapid growth
3833                warmup_frames: 0,
3834                sigma_floor_ms: 0.001, // Tiny floor to amplify residuals
3835                ..Default::default()
3836            };
3837
3838            // Extreme overload to push e_value toward upper clamp
3839            for _ in 0..1000 {
3840                state.update(1e6, 16.0, &config);
3841            }
3842
3843            assert!(
3844                state.e_value <= 1e10,
3845                "E-value should be clamped at 1e10: {}",
3846                state.e_value
3847            );
3848        }
3849
3850        #[test]
3851        fn eprocess_e_value_clamped_at_lower_bound() {
3852            let mut state = EProcessState::default();
3853            let config = EProcessConfig {
3854                lambda: 2.0,
3855                warmup_frames: 0,
3856                sigma_floor_ms: 0.001,
3857                ..Default::default()
3858            };
3859
3860            // Extreme underload to push e_value toward lower clamp
3861            for _ in 0..1000 {
3862                state.update(0.001, 1e6, &config);
3863            }
3864
3865            assert!(
3866                state.e_value >= 1e-10,
3867                "E-value should be clamped at 1e-10: {}",
3868                state.e_value
3869            );
3870        }
3871
3872        #[test]
3873        fn eprocess_should_upgrade_during_warmup() {
3874            let state = EProcessState::default();
3875            let config = EProcessConfig {
3876                warmup_frames: 10,
3877                ..Default::default()
3878            };
3879
3880            // During warmup, should_upgrade returns true to allow PID-driven upgrades
3881            assert!(
3882                state.should_upgrade(&config),
3883                "should_upgrade should return true during warmup"
3884            );
3885        }
3886
3887        #[test]
3888        fn eprocess_frames_observed_saturates() {
3889            let mut state = EProcessState {
3890                frames_observed: u32::MAX,
3891                ..EProcessState::default()
3892            };
3893            let config = EProcessConfig::default();
3894
3895            // Should not panic or wrap around
3896            state.update(16.0, 16.0, &config);
3897            assert_eq!(
3898                state.frames_observed,
3899                u32::MAX,
3900                "frames_observed should saturate at u32::MAX"
3901            );
3902        }
3903
3904        #[test]
3905        fn eprocess_sigma_ema_decay_boundary_zero() {
3906            let mut state = EProcessState::default();
3907            let config = EProcessConfig {
3908                sigma_ema_decay: 0.0,
3909                warmup_frames: 0,
3910                ..Default::default()
3911            };
3912
3913            // With decay=0, each update fully replaces the EMA
3914            state.update(20.0, 16.0, &config);
3915            state.update(30.0, 16.0, &config);
3916
3917            // mean_ema should be exactly the latest value
3918            assert!(
3919                (state.mean_ema - 30.0).abs() < f64::EPSILON,
3920                "decay=0 should fully replace mean_ema: {}",
3921                state.mean_ema
3922            );
3923        }
3924
3925        #[test]
3926        fn eprocess_sigma_ema_decay_boundary_one() {
3927            let mut state = EProcessState::default();
3928            let config = EProcessConfig {
3929                sigma_ema_decay: 1.0,
3930                warmup_frames: 0,
3931                ..Default::default()
3932            };
3933
3934            // With decay=1, EMA never changes from initial
3935            state.update(20.0, 16.0, &config);
3936            let first_mean = state.mean_ema;
3937            state.update(100.0, 16.0, &config);
3938
3939            assert!(
3940                (state.mean_ema - first_mean).abs() < f64::EPSILON,
3941                "decay=1 should lock mean_ema at first value: got {}, expected {}",
3942                state.mean_ema,
3943                first_mean
3944            );
3945        }
3946
3947        #[test]
3948        fn eprocess_zero_target_no_panic() {
3949            let mut state = EProcessState::default();
3950            let config = EProcessConfig {
3951                warmup_frames: 0,
3952                ..Default::default()
3953            };
3954
3955            // Zero target — residual computation divides by sigma (floored), not target
3956            let e = state.update(16.0, 0.0, &config);
3957            assert!(
3958                e.is_finite(),
3959                "E-value should be finite with zero target: {}",
3960                e
3961            );
3962        }
3963
3964        // --- DegradationLevel edge cases ---
3965
3966        #[test]
3967        fn degradation_level_default_is_full() {
3968            assert_eq!(DegradationLevel::default(), DegradationLevel::Full);
3969        }
3970
3971        #[test]
3972        fn degradation_level_hash_unique() {
3973            use std::collections::HashSet;
3974            let levels = [
3975                DegradationLevel::Full,
3976                DegradationLevel::SimpleBorders,
3977                DegradationLevel::NoStyling,
3978                DegradationLevel::EssentialOnly,
3979                DegradationLevel::Skeleton,
3980                DegradationLevel::SkipFrame,
3981            ];
3982            let set: HashSet<DegradationLevel> = levels.iter().copied().collect();
3983            assert_eq!(set.len(), 6, "All levels should hash uniquely");
3984        }
3985
3986        #[test]
3987        fn degradation_level_widget_queries_full() {
3988            let l = DegradationLevel::Full;
3989            assert!(l.use_unicode_borders());
3990            assert!(l.apply_styling());
3991            assert!(l.render_decorative());
3992            assert!(l.render_content());
3993        }
3994
3995        #[test]
3996        fn degradation_level_widget_queries_simple_borders() {
3997            let l = DegradationLevel::SimpleBorders;
3998            assert!(!l.use_unicode_borders());
3999            assert!(l.apply_styling());
4000            assert!(l.render_decorative());
4001            assert!(l.render_content());
4002        }
4003
4004        #[test]
4005        fn degradation_level_widget_queries_no_styling() {
4006            let l = DegradationLevel::NoStyling;
4007            assert!(!l.use_unicode_borders());
4008            assert!(!l.apply_styling());
4009            assert!(l.render_decorative());
4010            assert!(l.render_content());
4011        }
4012
4013        #[test]
4014        fn degradation_level_widget_queries_essential_only() {
4015            let l = DegradationLevel::EssentialOnly;
4016            assert!(!l.use_unicode_borders());
4017            assert!(!l.apply_styling());
4018            assert!(!l.render_decorative());
4019            assert!(l.render_content());
4020        }
4021
4022        #[test]
4023        fn degradation_level_widget_queries_skeleton() {
4024            let l = DegradationLevel::Skeleton;
4025            assert!(!l.use_unicode_borders());
4026            assert!(!l.apply_styling());
4027            assert!(!l.render_decorative());
4028            assert!(!l.render_content());
4029        }
4030
4031        #[test]
4032        fn degradation_level_widget_queries_skip_frame() {
4033            let l = DegradationLevel::SkipFrame;
4034            assert!(!l.use_unicode_borders());
4035            assert!(!l.apply_styling());
4036            assert!(!l.render_decorative());
4037            assert!(!l.render_content());
4038        }
4039
4040        #[test]
4041        fn degradation_level_partial_ord_consistent() {
4042            // PartialOrd should agree with Ord for all pairs
4043            let levels = [
4044                DegradationLevel::Full,
4045                DegradationLevel::SimpleBorders,
4046                DegradationLevel::NoStyling,
4047                DegradationLevel::EssentialOnly,
4048                DegradationLevel::Skeleton,
4049                DegradationLevel::SkipFrame,
4050            ];
4051            for (i, a) in levels.iter().enumerate() {
4052                for (j, b) in levels.iter().enumerate() {
4053                    let po = a.partial_cmp(b);
4054                    let o = a.cmp(b);
4055                    assert_eq!(po, Some(o), "PartialOrd != Ord for {:?} vs {:?}", a, b);
4056                    if i < j {
4057                        assert!(*a < *b, "{:?} should be < {:?}", a, b);
4058                    }
4059                }
4060            }
4061        }
4062
4063        #[test]
4064        fn degradation_level_clone_eq() {
4065            let a = DegradationLevel::NoStyling;
4066            let b = a;
4067            assert_eq!(a, b);
4068        }
4069
4070        #[test]
4071        fn degradation_level_debug() {
4072            let s = format!("{:?}", DegradationLevel::EssentialOnly);
4073            assert!(s.contains("EssentialOnly"), "Debug output: {}", s);
4074        }
4075
4076        // --- BudgetController accessor edge cases ---
4077
4078        #[test]
4079        fn controller_eprocess_sigma_ms_uses_floor() {
4080            let ctrl = BudgetController::new(BudgetControllerConfig {
4081                eprocess: EProcessConfig {
4082                    sigma_floor_ms: 2.5,
4083                    ..Default::default()
4084                },
4085                ..Default::default()
4086            });
4087
4088            // Before any updates, sigma_ema is 0.0, so should return floor
4089            assert!(
4090                (ctrl.eprocess_sigma_ms() - 2.5).abs() < f64::EPSILON,
4091                "Should return sigma_floor_ms when sigma_ema < floor: {}",
4092                ctrl.eprocess_sigma_ms()
4093            );
4094        }
4095
4096        #[test]
4097        fn controller_config_accessor() {
4098            let config = BudgetControllerConfig {
4099                degrade_threshold: 0.42,
4100                ..Default::default()
4101            };
4102            let ctrl = BudgetController::new(config.clone());
4103
4104            assert_eq!(ctrl.config().degrade_threshold, 0.42);
4105            assert_eq!(ctrl.config().target, Duration::from_millis(16));
4106        }
4107
4108        #[test]
4109        fn controller_frames_observed_accessor() {
4110            let mut ctrl = BudgetController::new(BudgetControllerConfig::default());
4111
4112            assert_eq!(ctrl.frames_observed(), 0);
4113
4114            ctrl.update(Duration::from_millis(16));
4115            assert_eq!(ctrl.frames_observed(), 1);
4116
4117            ctrl.update(Duration::from_millis(16));
4118            assert_eq!(ctrl.frames_observed(), 2);
4119        }
4120
4121        // --- RenderBudget edge cases ---
4122
4123        #[test]
4124        fn render_budget_record_frame_time_used_by_next_frame() {
4125            let mut budget = RenderBudget::new(Duration::from_millis(1000));
4126            budget.degrade();
4127
4128            // Simulate many frames to pass cooldown
4129            for _ in 0..10 {
4130                budget.reset();
4131            }
4132
4133            // Record a very fast frame time
4134            budget.record_frame_time(Duration::from_millis(1));
4135            // Sleep past the budget so start.elapsed() would be large
4136            std::thread::sleep(Duration::from_millis(15));
4137
4138            let before = budget.degradation();
4139            budget.next_frame();
4140
4141            // The recorded frame time (1ms) should trigger upgrade
4142            // since remaining_fraction_for_elapsed(1ms) > upgrade_threshold
4143            assert!(
4144                budget.degradation() < before,
4145                "Recorded frame time should enable upgrade: before={:?}, after={:?}",
4146                before,
4147                budget.degradation()
4148            );
4149        }
4150
4151        #[test]
4152        fn render_budget_phase_budget_clamped_by_remaining() {
4153            // Create a budget that has very little remaining
4154            let budget = RenderBudget::new(Duration::from_millis(1));
4155            std::thread::sleep(Duration::from_millis(5));
4156
4157            // Phase budget should be clamped to remaining (0ms)
4158            let phase = budget.phase_budget(Phase::Render);
4159            assert!(
4160                phase.total() <= Duration::from_millis(1),
4161                "Phase budget should be clamped by remaining: {:?}",
4162                phase.total()
4163            );
4164        }
4165
4166        #[test]
4167        fn render_budget_exhausted_skipframe_with_no_frame_skip() {
4168            let mut budget = RenderBudget::new(Duration::from_millis(1000));
4169            budget.allow_frame_skip = false;
4170            budget.set_degradation(DegradationLevel::SkipFrame);
4171
4172            // With allow_frame_skip = false, SkipFrame should NOT cause exhaustion
4173            // (only time-based exhaustion matters)
4174            assert!(
4175                !budget.exhausted(),
4176                "SkipFrame should not exhaust when frame skip disabled"
4177            );
4178        }
4179
4180        #[test]
4181        fn render_budget_remaining_fraction_zero_total() {
4182            let budget = RenderBudget::new(Duration::ZERO);
4183            assert_eq!(budget.remaining_fraction(), 0.0);
4184        }
4185
4186        #[test]
4187        fn render_budget_total_accessor() {
4188            let budget = RenderBudget::new(Duration::from_millis(42));
4189            assert_eq!(budget.total(), Duration::from_millis(42));
4190        }
4191
4192        #[test]
4193        fn render_budget_phase_budgets_accessor() {
4194            let budget = RenderBudget::new(Duration::from_millis(16));
4195            let pb = budget.phase_budgets();
4196            assert_eq!(pb.diff, Duration::from_millis(2));
4197            assert_eq!(pb.present, Duration::from_millis(4));
4198            assert_eq!(pb.render, Duration::from_millis(8));
4199        }
4200
4201        #[test]
4202        fn render_budget_set_degradation_no_op_preserves_cooldown() {
4203            let mut budget = RenderBudget::new(Duration::from_millis(16));
4204            budget.set_degradation(DegradationLevel::NoStyling);
4205            budget.frames_since_change = 7;
4206
4207            // Setting to same level is a no-op
4208            budget.set_degradation(DegradationLevel::NoStyling);
4209            assert_eq!(budget.frames_since_change, 7);
4210
4211            // Setting to different level resets cooldown
4212            budget.set_degradation(DegradationLevel::Skeleton);
4213            assert_eq!(budget.frames_since_change, 0);
4214        }
4215
4216        #[test]
4217        fn render_budget_should_upgrade_false_at_full() {
4218            let budget = RenderBudget::new(Duration::from_millis(1000));
4219            assert!(!budget.should_upgrade(), "Full level should never upgrade");
4220        }
4221
4222        #[test]
4223        fn render_budget_should_upgrade_false_during_cooldown() {
4224            let mut budget = RenderBudget::new(Duration::from_millis(1000));
4225            budget.degrade();
4226            // frames_since_change is 0, cooldown is 3
4227            assert!(
4228                !budget.should_upgrade(),
4229                "Should not upgrade during cooldown"
4230            );
4231        }
4232
4233        #[test]
4234        fn render_budget_degrade_at_max_stays_at_max() {
4235            let mut budget = RenderBudget::new(Duration::from_millis(16));
4236            budget.set_degradation(DegradationLevel::SkipFrame);
4237            budget.degrade();
4238            assert_eq!(budget.degradation(), DegradationLevel::SkipFrame);
4239        }
4240
4241        #[test]
4242        fn render_budget_upgrade_at_full_stays_at_full() {
4243            let mut budget = RenderBudget::new(Duration::from_millis(16));
4244            budget.upgrade();
4245            assert_eq!(budget.degradation(), DegradationLevel::Full);
4246        }
4247
4248        // --- Config edge cases ---
4249
4250        #[test]
4251        fn frame_budget_config_partial_eq() {
4252            let a = FrameBudgetConfig::default();
4253            let b = FrameBudgetConfig::default();
4254            assert_eq!(a, b);
4255
4256            let c = FrameBudgetConfig::strict(Duration::from_millis(16));
4257            assert_ne!(a, c, "Different configs should not be equal");
4258        }
4259
4260        #[test]
4261        fn phase_budgets_eq_and_copy() {
4262            let a = PhaseBudgets::default();
4263            let b = a; // Copy
4264            assert_eq!(a, b);
4265
4266            let c = PhaseBudgets {
4267                diff: Duration::from_millis(1),
4268                ..Default::default()
4269            };
4270            assert_ne!(a, c);
4271        }
4272
4273        #[test]
4274        fn budget_controller_config_partial_eq() {
4275            let a = BudgetControllerConfig::default();
4276            let b = BudgetControllerConfig::default();
4277            assert_eq!(a, b);
4278        }
4279
4280        #[test]
4281        fn pid_gains_partial_eq() {
4282            let a = PidGains::default();
4283            let b = PidGains::default();
4284            assert_eq!(a, b);
4285        }
4286
4287        #[test]
4288        fn eprocess_config_partial_eq() {
4289            let a = EProcessConfig::default();
4290            let b = EProcessConfig::default();
4291            assert_eq!(a, b);
4292        }
4293
4294        // --- BudgetDecision edge cases ---
4295
4296        #[test]
4297        fn budget_decision_debug_format() {
4298            assert!(format!("{:?}", BudgetDecision::Hold).contains("Hold"));
4299            assert!(format!("{:?}", BudgetDecision::Degrade).contains("Degrade"));
4300            assert!(format!("{:?}", BudgetDecision::Upgrade).contains("Upgrade"));
4301        }
4302
4303        #[test]
4304        fn budget_decision_clone_copy() {
4305            let d = BudgetDecision::Degrade;
4306            let d2 = d;
4307            assert_eq!(d, d2);
4308        }
4309
4310        #[test]
4311        fn budget_decision_as_str_coverage() {
4312            assert_eq!(BudgetDecision::Hold.as_str(), "stay");
4313            assert_eq!(BudgetDecision::Degrade.as_str(), "degrade");
4314            assert_eq!(BudgetDecision::Upgrade.as_str(), "upgrade");
4315        }
4316
4317        #[test]
4318        fn budget_decision_reason_debug_and_as_str() {
4319            assert!(
4320                format!("{:?}", BudgetDecisionReason::CooldownActive).contains("CooldownActive")
4321            );
4322            assert_eq!(
4323                BudgetDecisionReason::CooldownActive.as_str(),
4324                "cooldown_active"
4325            );
4326            assert_eq!(
4327                BudgetDecisionReason::OverloadEvidencePassed.as_str(),
4328                "overload_evidence_passed"
4329            );
4330            assert_eq!(
4331                BudgetDecisionReason::UnderloadEvidencePassed.as_str(),
4332                "underload_evidence_passed"
4333            );
4334            assert_eq!(
4335                BudgetDecisionReason::AtMaxDegradation.as_str(),
4336                "at_max_degradation"
4337            );
4338            assert_eq!(
4339                BudgetDecisionReason::AtDegradationFloor.as_str(),
4340                "at_degradation_floor"
4341            );
4342            assert_eq!(
4343                BudgetDecisionReason::AtFullQuality.as_str(),
4344                "at_full_quality"
4345            );
4346            assert_eq!(
4347                BudgetDecisionReason::WithinThresholdBand.as_str(),
4348                "within_threshold_band"
4349            );
4350        }
4351
4352        // --- Phase edge cases ---
4353
4354        #[test]
4355        fn phase_eq_and_hash() {
4356            use std::collections::HashSet;
4357            let mut set = HashSet::new();
4358            set.insert(Phase::Diff);
4359            set.insert(Phase::Present);
4360            set.insert(Phase::Render);
4361            assert_eq!(set.len(), 3);
4362
4363            // Same phase hashes to same bucket
4364            set.insert(Phase::Diff);
4365            assert_eq!(set.len(), 3);
4366        }
4367
4368        #[test]
4369        fn phase_debug() {
4370            assert!(format!("{:?}", Phase::Diff).contains("Diff"));
4371            assert!(format!("{:?}", Phase::Present).contains("Present"));
4372            assert!(format!("{:?}", Phase::Render).contains("Render"));
4373        }
4374
4375        #[test]
4376        fn phase_clone_copy() {
4377            let p = Phase::Present;
4378            let p2 = p;
4379            assert_eq!(p, p2);
4380        }
4381
4382        // --- BudgetTelemetry edge cases ---
4383
4384        #[test]
4385        fn budget_telemetry_debug() {
4386            let telem = BudgetTelemetry {
4387                schema_version: BUDGET_TELEMETRY_SCHEMA_VERSION,
4388                level: DegradationLevel::Full,
4389                pid_output: 0.0,
4390                pid_p: 0.0,
4391                pid_i: 0.0,
4392                pid_d: 0.0,
4393                e_value: 1.0,
4394                eprocess_lambda: 0.5,
4395                frames_observed: 0,
4396                frames_since_change: 0,
4397                last_decision: BudgetDecision::Hold,
4398                decision_reason: BudgetDecisionReason::WithinThresholdBand,
4399                transition_seq: 0,
4400                transition_correlation_id: 0,
4401                frame_time_ms: 0.0,
4402                target_ms: 16.0,
4403                pid_gate_threshold: 0.0,
4404                pid_gate_margin: 0.0,
4405                evidence_threshold: 0.0,
4406                evidence_margin: 0.0,
4407                in_warmup: true,
4408                recovery_streak: 0,
4409                total_degrades: 0,
4410                total_recoveries: 0,
4411            };
4412            let s = format!("{:?}", telem);
4413            assert!(s.contains("BudgetTelemetry"), "Debug output: {}", s);
4414        }
4415
4416        #[test]
4417        fn budget_telemetry_partial_eq() {
4418            let a = BudgetTelemetry {
4419                schema_version: BUDGET_TELEMETRY_SCHEMA_VERSION,
4420                level: DegradationLevel::Full,
4421                pid_output: 0.5,
4422                pid_p: 0.3,
4423                pid_i: 0.1,
4424                pid_d: 0.1,
4425                e_value: 1.0,
4426                eprocess_lambda: 0.5,
4427                frames_observed: 5,
4428                frames_since_change: 2,
4429                last_decision: BudgetDecision::Hold,
4430                decision_reason: BudgetDecisionReason::WithinThresholdBand,
4431                transition_seq: 0,
4432                transition_correlation_id: 0,
4433                frame_time_ms: 16.0,
4434                target_ms: 16.0,
4435                pid_gate_threshold: 0.0,
4436                pid_gate_margin: 0.0,
4437                evidence_threshold: 0.0,
4438                evidence_margin: 0.0,
4439                in_warmup: false,
4440                recovery_streak: 0,
4441                total_degrades: 0,
4442                total_recoveries: 0,
4443            };
4444            let b = a;
4445            assert_eq!(a, b);
4446
4447            let c = BudgetTelemetry {
4448                level: DegradationLevel::SimpleBorders,
4449                ..a
4450            };
4451            assert_ne!(a, c);
4452        }
4453
4454        // --- Controller + RenderBudget integration edge cases ---
4455
4456        #[test]
4457        fn next_frame_without_recorded_time_uses_elapsed() {
4458            let mut budget = RenderBudget::new(Duration::from_millis(1000));
4459
4460            // Don't record frame time — next_frame falls back to start.elapsed()
4461            budget.next_frame();
4462
4463            // Should not panic, remaining should reset
4464            assert!(budget.remaining_fraction() > 0.9);
4465        }
4466
4467        #[test]
4468        fn controller_at_max_degradation_holds() {
4469            let mut ctrl = BudgetController::new(BudgetControllerConfig {
4470                eprocess: EProcessConfig {
4471                    warmup_frames: 0,
4472                    ..Default::default()
4473                },
4474                cooldown_frames: 0,
4475                // Remove the floor so we can test reaching SkipFrame
4476                degradation_floor: DegradationLevel::SkipFrame,
4477                ..Default::default()
4478            });
4479
4480            // Drive to SkipFrame
4481            for _ in 0..500 {
4482                ctrl.update(Duration::from_millis(200));
4483            }
4484            assert_eq!(ctrl.level(), DegradationLevel::SkipFrame);
4485
4486            // At max level, further overload should Hold (can't degrade further)
4487            let d = ctrl.update(Duration::from_millis(200));
4488            assert_eq!(d, BudgetDecision::Hold, "At max level, should hold");
4489        }
4490
4491        #[test]
4492        fn controller_at_configured_degradation_floor_reports_floor_reason() {
4493            let mut ctrl = BudgetController::new(BudgetControllerConfig {
4494                eprocess: EProcessConfig {
4495                    warmup_frames: 0,
4496                    ..Default::default()
4497                },
4498                cooldown_frames: 0,
4499                degradation_floor: DegradationLevel::SimpleBorders,
4500                ..Default::default()
4501            });
4502
4503            ctrl.current_level = DegradationLevel::SimpleBorders;
4504
4505            let decision = ctrl.update(Duration::from_millis(200));
4506            let telemetry = ctrl.telemetry();
4507
4508            assert_eq!(decision, BudgetDecision::Hold);
4509            assert_eq!(telemetry.level, DegradationLevel::SimpleBorders);
4510            assert_eq!(
4511                telemetry.decision_reason,
4512                BudgetDecisionReason::AtDegradationFloor
4513            );
4514        }
4515
4516        #[test]
4517        fn controller_at_full_level_no_upgrade() {
4518            let mut ctrl = BudgetController::new(BudgetControllerConfig {
4519                eprocess: EProcessConfig {
4520                    warmup_frames: 0,
4521                    ..Default::default()
4522                },
4523                cooldown_frames: 0,
4524                ..Default::default()
4525            });
4526
4527            // Feed underload — already at Full, so no upgrade possible
4528            for _ in 0..50 {
4529                let d = ctrl.update(Duration::from_millis(1));
4530                assert_ne!(
4531                    d,
4532                    BudgetDecision::Upgrade,
4533                    "Full level should never upgrade"
4534                );
4535            }
4536        }
4537
4538        #[test]
4539        fn controller_recovers_after_external_degradation() {
4540            // Regression: external mutations (guardrail set_degradation,
4541            // conformal-gate degrade) used to leave the controller believing
4542            // it was still at Full, so it reported AtFullQuality and held
4543            // forever — the UI stayed degraded permanently. The controller
4544            // must track the budget's actual level and upgrade back out.
4545            let mut budget = RenderBudget::new(Duration::from_millis(16)).with_controller(
4546                BudgetControllerConfig {
4547                    eprocess: EProcessConfig {
4548                        warmup_frames: 0,
4549                        ..Default::default()
4550                    },
4551                    cooldown_frames: 0,
4552                    ..Default::default()
4553                },
4554            );
4555
4556            // Emergency path forces a jump (as program.rs guardrails do).
4557            budget.set_degradation(DegradationLevel::EssentialOnly);
4558            assert_eq!(
4559                budget.controller().expect("controller attached").level(),
4560                DegradationLevel::EssentialOnly,
4561                "controller must observe the external level change"
4562            );
4563
4564            // Load is healthy again: fast frames must upgrade back up.
4565            for _ in 0..300 {
4566                budget.record_frame_time(Duration::from_millis(2));
4567                budget.next_frame();
4568            }
4569            assert!(
4570                budget.degradation() < DegradationLevel::EssentialOnly,
4571                "externally degraded budget must recover under healthy load, got {:?}",
4572                budget.degradation()
4573            );
4574
4575            // Telemetry and rendered level agree at every step.
4576            assert_eq!(
4577                budget.controller().expect("controller attached").level(),
4578                budget.degradation(),
4579                "controller and budget level must stay in lockstep"
4580            );
4581        }
4582
4583        #[test]
4584        fn external_conformal_style_degrade_syncs_controller() {
4585            let mut budget = RenderBudget::new(Duration::from_millis(16)).with_controller(
4586                BudgetControllerConfig {
4587                    eprocess: EProcessConfig {
4588                        warmup_frames: 0,
4589                        ..Default::default()
4590                    },
4591                    cooldown_frames: 0,
4592                    ..Default::default()
4593                },
4594            );
4595
4596            // Conformal risk gate path calls degrade() directly.
4597            budget.degrade();
4598            assert_eq!(
4599                budget.controller().expect("controller attached").level(),
4600                budget.degradation()
4601            );
4602        }
4603
4604        #[test]
4605        fn phase_budget_starts_with_full_phase_allocation() {
4606            // Regression: phase sub-budgets inherited the frame's start
4607            // instant, so a phase entered later than its own allocation into
4608            // the frame was born exhausted.
4609            let budget = RenderBudget::new(Duration::from_millis(1000));
4610            std::thread::sleep(Duration::from_millis(20));
4611
4612            let sub = budget.phase_budget(Phase::Diff);
4613            assert!(
4614                !sub.exhausted(),
4615                "phase budget must not be exhausted at phase start"
4616            );
4617            // The allocation is bounded by the frame's remaining time and is
4618            // fully available at the moment the phase begins.
4619            assert!(sub.remaining() > Duration::ZERO);
4620            assert!(sub.remaining() <= sub.total());
4621        }
4622
4623        #[test]
4624        fn next_frame_consumes_recorded_time_once() {
4625            // Regression: last_frame_time was never cleared, so a frame that
4626            // skipped record_frame_time (emergency drop path) re-fed the
4627            // previous frame's duration to the controller.
4628            let mut budget = RenderBudget::new(Duration::from_millis(16)).with_controller(
4629                BudgetControllerConfig {
4630                    eprocess: EProcessConfig {
4631                        warmup_frames: 0,
4632                        ..Default::default()
4633                    },
4634                    cooldown_frames: 0,
4635                    ..Default::default()
4636                },
4637            );
4638
4639            budget.record_frame_time(Duration::from_millis(40));
4640            budget.next_frame();
4641            let after_first = budget
4642                .controller()
4643                .expect("controller attached")
4644                .telemetry()
4645                .frame_time_ms;
4646            assert!((after_first - 40.0).abs() < 1.0);
4647
4648            // No recording before the second call: the controller must see
4649            // the (tiny) actual elapsed time, not the stale 40ms again.
4650            budget.next_frame();
4651            let after_second = budget
4652                .controller()
4653                .expect("controller attached")
4654                .telemetry()
4655                .frame_time_ms;
4656            assert!(
4657                after_second < 20.0,
4658                "stale frame time re-fed to controller: {after_second}ms"
4659            );
4660        }
4661
4662        #[test]
4663        fn render_budget_full_degrade_cycle_with_controller() {
4664            let mut budget = RenderBudget::new(Duration::from_millis(16)).with_controller(
4665                BudgetControllerConfig {
4666                    eprocess: EProcessConfig {
4667                        warmup_frames: 0,
4668                        ..Default::default()
4669                    },
4670                    cooldown_frames: 0,
4671                    ..Default::default()
4672                },
4673            );
4674
4675            // Overload to degrade via controller
4676            for _ in 0..100 {
4677                budget.record_frame_time(Duration::from_millis(40));
4678                budget.next_frame();
4679            }
4680            let degraded = budget.degradation();
4681            assert!(
4682                degraded > DegradationLevel::Full,
4683                "Should degrade: {:?}",
4684                degraded
4685            );
4686
4687            // Recovery via controller
4688            for _ in 0..200 {
4689                budget.record_frame_time(Duration::from_millis(4));
4690                budget.next_frame();
4691            }
4692            let recovered = budget.degradation();
4693            assert!(
4694                recovered < degraded,
4695                "Should recover: {:?} -> {:?}",
4696                degraded,
4697                recovered
4698            );
4699        }
4700
4701        #[test]
4702        fn render_budget_phase_has_budget_exhausted() {
4703            let budget = RenderBudget::new(Duration::from_millis(1));
4704            std::thread::sleep(Duration::from_millis(10));
4705
4706            // All phases should report no budget
4707            assert!(!budget.phase_has_budget(Phase::Diff));
4708            assert!(!budget.phase_has_budget(Phase::Present));
4709            assert!(!budget.phase_has_budget(Phase::Render));
4710        }
4711
4712        #[test]
4713        fn render_budget_elapsed_increases() {
4714            let budget = RenderBudget::new(Duration::from_millis(1000));
4715            let e1 = budget.elapsed();
4716            std::thread::sleep(Duration::from_millis(5));
4717            let e2 = budget.elapsed();
4718            assert!(e2 > e1, "Elapsed should increase: {:?} vs {:?}", e1, e2);
4719        }
4720
4721        #[test]
4722        fn controller_pid_integral_accessor() {
4723            let mut ctrl = BudgetController::new(BudgetControllerConfig::default());
4724
4725            assert_eq!(ctrl.pid_integral(), 0.0);
4726
4727            // Feed overload to accumulate integral
4728            ctrl.update(Duration::from_millis(32)); // 2x target
4729            assert!(
4730                ctrl.pid_integral() > 0.0,
4731                "Integral should grow: {}",
4732                ctrl.pid_integral()
4733            );
4734        }
4735
4736        #[test]
4737        fn controller_e_value_accessor() {
4738            let ctrl = BudgetController::new(BudgetControllerConfig::default());
4739            assert!((ctrl.e_value() - 1.0).abs() < f64::EPSILON);
4740        }
4741
4742        #[test]
4743        fn budget_controller_counts_degrades_and_recoveries() {
4744            let mut ctrl = BudgetController::new(BudgetControllerConfig {
4745                target: Duration::from_millis(16),
4746                cooldown_frames: 0,
4747                upgrade_threshold: 0.1,
4748                degrade_threshold: 0.1,
4749                ..Default::default()
4750            });
4751
4752            assert_eq!(ctrl.recovery_streak(), 0);
4753            assert_eq!(ctrl.total_degrades(), 0);
4754            assert_eq!(ctrl.total_recoveries(), 0);
4755
4756            // Feed fast frames to build up recovery streak
4757            for _ in 0..5 {
4758                ctrl.update(Duration::from_millis(4));
4759            }
4760            assert!(ctrl.recovery_streak() > 0);
4761
4762            // Step up (degrade): overload frames until exactly 1 degrade
4763            for _ in 0..50 {
4764                ctrl.update(Duration::from_millis(50));
4765                if ctrl.total_degrades() == 1 {
4766                    break;
4767                }
4768            }
4769            assert_eq!(ctrl.total_degrades(), 1);
4770            assert_eq!(
4771                ctrl.recovery_streak(),
4772                0,
4773                "recovery_streak resets on degrade"
4774            );
4775
4776            // Recover (upgrade): fast frames until 1 recovery
4777            for _ in 0..200 {
4778                ctrl.update(Duration::from_millis(4));
4779                if ctrl.total_recoveries() == 1 {
4780                    break;
4781                }
4782            }
4783            assert_eq!(ctrl.total_recoveries(), 1);
4784            assert!(ctrl.recovery_streak() > 0);
4785
4786            // Test reset clears counters
4787            ctrl.reset();
4788            assert_eq!(ctrl.recovery_streak(), 0);
4789            assert_eq!(ctrl.total_degrades(), 0);
4790            assert_eq!(ctrl.total_recoveries(), 0);
4791        }
4792
4793        #[test]
4794        fn controller_telemetry_includes_counters() {
4795            let ctrl = BudgetController::new(BudgetControllerConfig::default());
4796            let t = ctrl.telemetry();
4797            assert_eq!(t.recovery_streak, 0);
4798            assert_eq!(t.total_degrades, 0);
4799            assert_eq!(t.total_recoveries, 0);
4800        }
4801
4802        #[test]
4803        fn degrade_respecting_floor_honors_controller_floor_and_syncs_level() {
4804            let mut budget = RenderBudget::new(Duration::from_millis(16)).with_controller(
4805                BudgetControllerConfig {
4806                    degradation_floor: DegradationLevel::NoStyling,
4807                    ..Default::default()
4808                },
4809            );
4810
4811            assert_eq!(budget.degradation_floor(), DegradationLevel::NoStyling);
4812            assert!(budget.degrade_respecting_floor());
4813            assert_eq!(budget.degradation(), DegradationLevel::SimpleBorders);
4814            assert_eq!(
4815                budget.controller().unwrap().level(),
4816                DegradationLevel::SimpleBorders
4817            );
4818
4819            assert!(budget.degrade_respecting_floor());
4820            assert_eq!(budget.degradation(), DegradationLevel::NoStyling);
4821            assert_eq!(
4822                budget.controller().unwrap().level(),
4823                DegradationLevel::NoStyling
4824            );
4825
4826            // At the floor, degrade_respecting_floor must hold instead of advancing to EssentialOnly.
4827            assert!(!budget.degrade_respecting_floor());
4828            assert_eq!(budget.degradation(), DegradationLevel::NoStyling);
4829        }
4830
4831        #[test]
4832        fn virtual_clock_overload_traverses_full_ladder_and_recovers_deterministically() {
4833            let make_budget = || {
4834                RenderBudget::new(Duration::from_millis(16)).with_controller(
4835                    BudgetControllerConfig {
4836                        target: Duration::from_millis(16),
4837                        degradation_floor: DegradationLevel::SkipFrame,
4838                        ..Default::default()
4839                    },
4840                )
4841            };
4842
4843            let run_virtual_trace = |budget: &mut RenderBudget| -> Vec<DegradationLevel> {
4844                let mut observed_levels = Vec::new();
4845                // 1) Warmup observations (frames_observed 1..10): warmup suppresses degradation
4846                for frame in 0..9 {
4847                    budget.record_frame_time(Duration::from_millis(80));
4848                    budget.next_frame();
4849                    assert_eq!(
4850                        budget.degradation(),
4851                        DegradationLevel::Full,
4852                        "warmup frame {frame} must not degrade"
4853                    );
4854                    observed_levels.push(budget.degradation());
4855                }
4856                // 2) Sustained 80ms overload drives step-by-step through all 6 levels to SkipFrame
4857                for _ in 0..40 {
4858                    budget.record_frame_time(Duration::from_millis(80));
4859                    budget.next_frame();
4860                    observed_levels.push(budget.degradation());
4861                }
4862                assert_eq!(budget.degradation(), DegradationLevel::SkipFrame);
4863
4864                // 3) Sustained 4ms recovery frames restore fidelity all the way back to Full
4865                for _ in 0..240 {
4866                    budget.record_frame_time(Duration::from_millis(4));
4867                    budget.next_frame();
4868                    observed_levels.push(budget.degradation());
4869                }
4870                assert_eq!(budget.degradation(), DegradationLevel::Full);
4871                observed_levels
4872            };
4873
4874            let mut budget_a = make_budget();
4875            let mut budget_b = make_budget();
4876            let path_a = run_virtual_trace(&mut budget_a);
4877            let path_b = run_virtual_trace(&mut budget_b);
4878
4879            // Determinism: identical virtual-clock duration sequences produce identical paths
4880            assert_eq!(path_a, path_b);
4881
4882            // Verify every level in the 6-level ladder was visited in order during degradation
4883            for expected in [
4884                DegradationLevel::Full,
4885                DegradationLevel::SimpleBorders,
4886                DegradationLevel::NoStyling,
4887                DegradationLevel::EssentialOnly,
4888                DegradationLevel::Skeleton,
4889                DegradationLevel::SkipFrame,
4890            ] {
4891                assert!(
4892                    path_a.contains(&expected),
4893                    "expected ladder traversal to visit {expected:?}"
4894                );
4895            }
4896        }
4897
4898        fn splitmix64_normal(state: &mut u64) -> (f64, f64) {
4899            fn next_u01(state: &mut u64) -> f64 {
4900                *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
4901                let mut z = *state;
4902                z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
4903                z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
4904                z ^= z >> 31;
4905                ((z >> 11) as f64) * (1.0 / ((1u64 << 53) as f64))
4906            }
4907            let u1 = next_u01(state).clamp(1e-12, 1.0 - 1e-12);
4908            let u2 = next_u01(state);
4909            let r = (-2.0 * u1.ln()).sqrt();
4910            let theta = 2.0 * std::f64::consts::PI * u2;
4911            (r * theta.cos(), r * theta.sin())
4912        }
4913
4914        #[test]
4915        fn budget_controller_grapa_adapts_lambda() {
4916            let target_ms = 16.0;
4917            let step_ms = target_ms * 1.8; // 28.8ms
4918            let base_eprocess = EProcessConfig {
4919                lambda: 0.5,
4920                adaptive_lambda: true,
4921                grapa_eta: 0.1,
4922                lambda_min: 0.05,
4923                lambda_max: 2.0,
4924                alpha: 0.05,
4925                beta: 0.5,
4926                sigma_ema_decay: 0.9,
4927                sigma_floor_ms: 4.0,
4928                warmup_frames: 10,
4929            };
4930
4931            let mut adaptive = BudgetController::new(BudgetControllerConfig {
4932                target: Duration::from_millis(16),
4933                eprocess: base_eprocess.clone(),
4934                ..Default::default()
4935            });
4936            let mut fixed = BudgetController::new(BudgetControllerConfig {
4937                target: Duration::from_millis(16),
4938                eprocess: EProcessConfig {
4939                    adaptive_lambda: false,
4940                    ..base_eprocess.clone()
4941                },
4942                ..Default::default()
4943            });
4944
4945            // 1. Feed 30 frames at target (16ms), then a step to 1.8x target (28.8ms).
4946            for _ in 0..30 {
4947                adaptive.update(Duration::from_millis(16));
4948                fixed.update(Duration::from_millis(16));
4949            }
4950
4951            let threshold = 1.0 / base_eprocess.alpha; // 20.0
4952            let step_dur = Duration::from_secs_f64(step_ms / 1000.0);
4953            let mut adaptive_cross = None;
4954            let mut fixed_cross = None;
4955
4956            for step_frame in 1..=50usize {
4957                adaptive.update(step_dur);
4958                fixed.update(step_dur);
4959                if adaptive_cross.is_none() && adaptive.e_value() > threshold {
4960                    adaptive_cross = Some(step_frame);
4961                }
4962                if fixed_cross.is_none() && fixed.e_value() > threshold {
4963                    fixed_cross = Some(step_frame);
4964                }
4965                if adaptive_cross.is_some() && fixed_cross.is_some() {
4966                    break;
4967                }
4968            }
4969
4970            let adaptive_frames = adaptive_cross.expect("adaptive controller must cross 1/alpha");
4971            let fixed_frames = fixed_cross.expect("fixed controller must cross 1/alpha");
4972            eprintln!(
4973                "budget_controller_grapa_adapts_lambda: adaptive_frames={adaptive_frames}, fixed_frames={fixed_frames}"
4974            );
4975            assert!(
4976                adaptive_frames < fixed_frames,
4977                "Expected adaptive controller ({adaptive_frames} frames) to cross 1/alpha={threshold} in strictly fewer frames than fixed ({fixed_frames} frames)"
4978            );
4979
4980            // 2. Feed 10,000 frames at target with N(0, 1*sigma) noise (seeded); neither crosses.
4981            let null_eprocess = EProcessConfig {
4982                sigma_floor_ms: 2.0,
4983                ..EProcessConfig::default()
4984            };
4985            let mut adaptive_null = BudgetController::new(BudgetControllerConfig {
4986                target: Duration::from_millis(16),
4987                eprocess: null_eprocess.clone(),
4988                ..Default::default()
4989            });
4990            let mut fixed_null = BudgetController::new(BudgetControllerConfig {
4991                target: Duration::from_millis(16),
4992                eprocess: EProcessConfig {
4993                    adaptive_lambda: false,
4994                    ..null_eprocess
4995                },
4996                ..Default::default()
4997            });
4998
4999            let mut rng = 0x6130_1720_2026_1016u64;
5000            for i in 0..5_000 {
5001                let (z0, z1) = splitmix64_normal(&mut rng);
5002                for (step_offset, z) in [(0usize, z0), (1usize, z1)] {
5003                    let frame_idx = i * 2 + step_offset;
5004                    // N(0, 1ms) noise around 16ms target with sigma_floor_ms = 2.0ms
5005                    let ms = (16.0 + z).clamp(1.0, 31.0);
5006                    let dur = Duration::from_secs_f64(ms / 1000.0);
5007                    adaptive_null.update(dur);
5008                    fixed_null.update(dur);
5009                    assert!(
5010                        adaptive_null.e_value() <= threshold,
5011                        "adaptive crossed threshold at null frame {frame_idx}: E={}",
5012                        adaptive_null.e_value()
5013                    );
5014                    assert!(
5015                        fixed_null.e_value() <= threshold,
5016                        "fixed crossed threshold at null frame {frame_idx}: E={}",
5017                        fixed_null.e_value()
5018                    );
5019                }
5020            }
5021        }
5022
5023        #[test]
5024        fn lambda_is_predictable() {
5025            // Verify that at every step t, the log-factor uses λ_{t-1} (reported in
5026            // telemetry at step t - 1 before observing r_t), reconstructing e_value_t
5027            // from e_value_{t-1} and λ_{t-1} within 1e-9.
5028            let cfg = BudgetControllerConfig {
5029                target: Duration::from_millis(16),
5030                eprocess: EProcessConfig {
5031                    warmup_frames: 3,
5032                    ..EProcessConfig::default()
5033                },
5034                ..Default::default()
5035            };
5036            let mut ctrl = BudgetController::new(cfg.clone());
5037            let mut mirror_state = EProcessState::new(&cfg.eprocess);
5038
5039            let sequence_ms = [
5040                16.0, 15.5, 16.5, 18.0, 22.0, 26.0, 30.0, 24.0, 16.0, 14.0, 12.0, 16.0, 20.0, 28.0,
5041            ];
5042
5043            let mut prev_e = ctrl.telemetry().e_value;
5044            let mut prev_lambda = ctrl.telemetry().eprocess_lambda;
5045
5046            for (idx, &ms) in sequence_ms.iter().enumerate() {
5047                // Compute exact residual r_t using the same sigma EMA update.
5048                mirror_state.frames_observed = mirror_state.frames_observed.saturating_add(1);
5049                if mirror_state.frames_observed == 1 {
5050                    mirror_state.mean_ema = ms;
5051                    mirror_state.sigma_ema = cfg.eprocess.sigma_floor_ms;
5052                } else {
5053                    let decay = cfg.eprocess.sigma_ema_decay;
5054                    mirror_state.mean_ema = decay * mirror_state.mean_ema + (1.0 - decay) * ms;
5055                    let deviation = (ms - mirror_state.mean_ema).abs();
5056                    mirror_state.sigma_ema =
5057                        decay * mirror_state.sigma_ema + (1.0 - decay) * deviation;
5058                }
5059                let sigma = mirror_state.sigma_ema.max(cfg.eprocess.sigma_floor_ms);
5060                let r_t = (ms - 16.0) / sigma;
5061
5062                ctrl.update(Duration::from_secs_f64(ms / 1000.0));
5063                let telem = ctrl.telemetry();
5064
5065                let expected_e = (prev_e
5066                    * (prev_lambda * r_t - prev_lambda * prev_lambda / 2.0).exp())
5067                .clamp(1e-10, 1e10);
5068                let rel_err = (telem.e_value - expected_e).abs() / expected_e.max(1.0);
5069                assert!(
5070                    (telem.e_value - expected_e).abs() < 1e-9 || rel_err < 1e-9,
5071                    "step {idx}: expected e_value {expected_e} from prev_e={prev_e} and prev_lambda={prev_lambda}, got {}",
5072                    telem.e_value
5073                );
5074
5075                prev_e = telem.e_value;
5076                prev_lambda = telem.eprocess_lambda;
5077            }
5078        }
5079
5080        #[test]
5081        fn lambda_stays_within_bounds() {
5082            let config = EProcessConfig {
5083                warmup_frames: 0,
5084                lambda_min: 0.05,
5085                lambda_max: 2.0,
5086                ..EProcessConfig::default()
5087            };
5088            let mut state = EProcessState::new(&config);
5089
5090            for &frame_ms in &[0.0, 1e6, 0.0, 1e6, 16.0, 1e6, 1e6, 0.0, 0.0, f64::NAN, 16.0] {
5091                state.update(frame_ms, 16.0, &config);
5092                assert!(
5093                    state.lambda.is_finite(),
5094                    "lambda must remain finite, got {}",
5095                    state.lambda
5096                );
5097                assert!(
5098                    state.lambda >= config.lambda_min && state.lambda <= config.lambda_max,
5099                    "lambda {} out of [{}, {}]",
5100                    state.lambda,
5101                    config.lambda_min,
5102                    config.lambda_max
5103                );
5104            }
5105        }
5106
5107        proptest::proptest! {
5108            #![proptest_config(proptest::test_runner::Config::with_cases(32))]
5109
5110            #[test]
5111            fn proptest_e_value_is_supermartingale_under_null(seed in 1u64..1_000_000u64) {
5112                let cfg = EProcessConfig {
5113                    warmup_frames: 10,
5114                    sigma_floor_ms: 2.0,
5115                    ..EProcessConfig::default()
5116                };
5117                let runs = 200usize;
5118                let frames = 500usize;
5119                let mut total_final_e = 0.0;
5120
5121                for run in 0..runs {
5122                    let mut rng = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(run as u64);
5123                    let mut state = EProcessState::new(&cfg);
5124                    for _ in 0..(frames / 2) {
5125                        let (z0, z1) = splitmix64_normal(&mut rng);
5126                        let f0 = (16.0 + z0).clamp(1.0, 31.0);
5127                        let f1 = (16.0 + z1).clamp(1.0, 31.0);
5128                        state.update(f0, 16.0, &cfg);
5129                        state.update(f1, 16.0, &cfg);
5130                    }
5131                    total_final_e += state.e_value;
5132                }
5133
5134                let mean_final_e = total_final_e / runs as f64;
5135                proptest::prop_assert!(
5136                    mean_final_e < 3.0,
5137                    "Expected mean final e_value < 3.0 over {runs} null runs of {frames} frames, got {mean_final_e}"
5138                );
5139            }
5140        }
5141    }
5142}