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