Skip to main content

ftui_render/
frame_guardrails.rs

1#![forbid(unsafe_code)]
2
3//! Frame guardrails: memory budget, queue depth limits, and unified enforcement.
4//!
5//! This module complements the time-based [`RenderBudget`](crate::budget::RenderBudget)
6//! with three resource guardrails:
7//!
8//! 1. **Memory budget** — enforces hard/soft limits on total rendering memory
9//!    (buffer cells, grapheme pool, arena).
10//! 2. **Queue depth** — prevents unbounded frame queuing under sustained load
11//!    with configurable drop policies.
12//! 3. **Capacity drift** — runs [`AllocLeakDetector`] over retained rendering
13//!    capacity without accumulating a per-frame ledger. Upward drift is advisory;
14//!    only absolute memory and queue limits recommend degradation or frame drops.
15//!
16//! A unified [`FrameGuardrails`] facade combines these three guardrails into a
17//! single per-frame checkpoint that returns an actionable [`GuardrailVerdict`].
18//!
19//! # Usage
20//!
21//! ```
22//! use ftui_render::frame_guardrails::{
23//!     FrameGuardrails, GuardrailsConfig, MemoryBudgetConfig, QueueConfig,
24//! };
25//! use ftui_render::budget::FrameBudgetConfig;
26//!
27//! let config = GuardrailsConfig::default();
28//! let mut guardrails = FrameGuardrails::new(config);
29//!
30//! // Each frame: report current resource usage
31//! let verdict = guardrails.check_frame(
32//!     1_048_576,  // current memory bytes
33//!     2,          // pending frames in queue
34//! );
35//!
36//! if verdict.should_drop_frame() {
37//!     // Skip this frame entirely
38//! } else if verdict.should_degrade() {
39//!     // Render at reduced fidelity
40//! }
41//! ```
42
43use crate::alloc_budget::{AllocLeakDetector, LeakAlert, LeakDetectorConfig};
44use crate::budget::DegradationLevel;
45
46// =========================================================================
47// Alerts
48// =========================================================================
49
50/// Category of guardrail that triggered.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52pub enum GuardrailKind {
53    /// Memory usage exceeded a threshold.
54    Memory,
55    /// Queue depth exceeded a threshold.
56    QueueDepth,
57    /// Retained rendering capacity shows sustained upward drift.
58    AllocationLeak,
59}
60
61/// Severity of a guardrail alert.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
63pub enum AlertSeverity {
64    /// Approaching limit — consider reducing work.
65    Warning,
66    /// At or near limit — degrade immediately.
67    Critical,
68    /// Past hard limit — drop frames or backpressure.
69    Emergency,
70}
71
72/// A single guardrail alert.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct GuardrailAlert {
75    /// Which guardrail triggered.
76    pub kind: GuardrailKind,
77    /// How severe the overage is.
78    pub severity: AlertSeverity,
79    /// Recommended minimum degradation level.
80    pub recommended_level: DegradationLevel,
81}
82
83// =========================================================================
84// Memory budget
85// =========================================================================
86
87/// Configuration for memory budget enforcement.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct MemoryBudgetConfig {
90    /// Soft limit in bytes — triggers `Warning` alert and suggests degradation.
91    /// Default: 8 MiB (enough for ~524K cells at 16 bytes each, i.e. ~540×970).
92    pub soft_limit_bytes: usize,
93    /// Hard limit in bytes — triggers `Critical` alert with aggressive degradation.
94    /// Default: 16 MiB.
95    pub hard_limit_bytes: usize,
96    /// Emergency limit in bytes — triggers `Emergency` alert, drop frames.
97    /// Default: 32 MiB.
98    pub emergency_limit_bytes: usize,
99}
100
101impl Default for MemoryBudgetConfig {
102    fn default() -> Self {
103        Self {
104            soft_limit_bytes: 8 * 1024 * 1024,
105            hard_limit_bytes: 16 * 1024 * 1024,
106            emergency_limit_bytes: 32 * 1024 * 1024,
107        }
108    }
109}
110
111impl MemoryBudgetConfig {
112    /// Create a config scaled for small terminals (e.g. 80×24).
113    #[must_use]
114    pub fn small() -> Self {
115        Self {
116            soft_limit_bytes: 2 * 1024 * 1024,
117            hard_limit_bytes: 4 * 1024 * 1024,
118            emergency_limit_bytes: 8 * 1024 * 1024,
119        }
120    }
121
122    /// Create a config scaled for large terminals (e.g. 300×100).
123    #[must_use]
124    pub fn large() -> Self {
125        Self {
126            soft_limit_bytes: 32 * 1024 * 1024,
127            hard_limit_bytes: 64 * 1024 * 1024,
128            emergency_limit_bytes: 128 * 1024 * 1024,
129        }
130    }
131
132    /// Return a normalized copy with sane, monotone thresholds.
133    ///
134    /// User-supplied configs (via `ProgramConfig`) can be zero-initialized
135    /// or inverted; the classifier uses `>=` comparisons, so an all-zero
136    /// config would classify EVERY frame as Emergency (blank screen from
137    /// startup) and inverted watermarks silently misclassify. Zero limits
138    /// fall back to the defaults; hard/emergency are raised to keep
139    /// soft <= hard <= emergency.
140    #[must_use]
141    pub fn normalized(self) -> Self {
142        let defaults = Self::default();
143        let soft = if self.soft_limit_bytes == 0 {
144            defaults.soft_limit_bytes
145        } else {
146            self.soft_limit_bytes
147        };
148        let hard = if self.hard_limit_bytes == 0 {
149            defaults.hard_limit_bytes
150        } else {
151            self.hard_limit_bytes
152        }
153        .max(soft);
154        let emergency = if self.emergency_limit_bytes == 0 {
155            defaults.emergency_limit_bytes
156        } else {
157            self.emergency_limit_bytes
158        }
159        .max(hard);
160        Self {
161            soft_limit_bytes: soft,
162            hard_limit_bytes: hard,
163            emergency_limit_bytes: emergency,
164        }
165    }
166}
167
168/// Memory budget tracker.
169///
170/// Checks reported memory usage against configured thresholds and produces
171/// alerts with recommended degradation levels.
172#[derive(Debug, Clone)]
173pub struct MemoryBudget {
174    config: MemoryBudgetConfig,
175    /// Peak memory observed (bytes).
176    peak_bytes: usize,
177    /// Last reported memory (bytes).
178    current_bytes: usize,
179    /// Number of frames where soft limit was exceeded.
180    soft_violations: u32,
181    /// Number of frames where hard limit was exceeded.
182    hard_violations: u32,
183    /// Number of frames where the emergency limit was exceeded.
184    ///
185    /// Counted separately from [`Self::hard_violations`]: emergency is a
186    /// distinct tier (frame shed + arena rebuild), and conflating it with
187    /// hard-limit hits made the snapshot unable to distinguish "hard limit
188    /// pressure" from "emergency shedding" (bd-1za0z F5).
189    emergency_violations: u32,
190}
191
192impl MemoryBudget {
193    /// Create a new memory budget with the given configuration.
194    #[must_use]
195    pub fn new(config: MemoryBudgetConfig) -> Self {
196        Self {
197            // Normalize at the boundary: the classifier's >= comparisons
198            // must never see zero or inverted thresholds (see
199            // MemoryBudgetConfig::normalized).
200            config: config.normalized(),
201            peak_bytes: 0,
202            current_bytes: 0,
203            soft_violations: 0,
204            hard_violations: 0,
205            emergency_violations: 0,
206        }
207    }
208
209    /// Report current memory usage and get an alert if thresholds are exceeded.
210    pub fn check(&mut self, current_bytes: usize) -> Option<GuardrailAlert> {
211        self.current_bytes = current_bytes;
212        if current_bytes > self.peak_bytes {
213            self.peak_bytes = current_bytes;
214        }
215
216        if current_bytes >= self.config.emergency_limit_bytes {
217            // Emergency is its OWN tier: counting it as a hard violation
218            // conflated "hard limit pressure" with "emergency shedding" in
219            // the snapshot (bd-1za0z F5).
220            self.emergency_violations = self.emergency_violations.saturating_add(1);
221            Some(GuardrailAlert {
222                kind: GuardrailKind::Memory,
223                severity: AlertSeverity::Emergency,
224                recommended_level: DegradationLevel::SkipFrame,
225            })
226        } else if current_bytes >= self.config.hard_limit_bytes {
227            self.hard_violations = self.hard_violations.saturating_add(1);
228            Some(GuardrailAlert {
229                kind: GuardrailKind::Memory,
230                severity: AlertSeverity::Critical,
231                recommended_level: DegradationLevel::Skeleton,
232            })
233        } else if current_bytes >= self.config.soft_limit_bytes {
234            self.soft_violations = self.soft_violations.saturating_add(1);
235            Some(GuardrailAlert {
236                kind: GuardrailKind::Memory,
237                severity: AlertSeverity::Warning,
238                recommended_level: DegradationLevel::SimpleBorders,
239            })
240        } else {
241            None
242        }
243    }
244
245    /// Current memory usage in bytes.
246    #[inline]
247    #[must_use]
248    pub fn current_bytes(&self) -> usize {
249        self.current_bytes
250    }
251
252    /// Peak memory usage observed since creation or last reset.
253    #[inline]
254    #[must_use]
255    pub fn peak_bytes(&self) -> usize {
256        self.peak_bytes
257    }
258
259    /// Fraction of soft limit currently used (0.0 = empty, 1.0 = at limit).
260    #[inline]
261    #[must_use]
262    pub fn usage_fraction(&self) -> f64 {
263        if self.config.soft_limit_bytes == 0 {
264            return 1.0;
265        }
266        self.current_bytes as f64 / self.config.soft_limit_bytes as f64
267    }
268
269    /// Number of frames where the soft limit was exceeded.
270    #[inline]
271    #[must_use]
272    pub fn soft_violations(&self) -> u32 {
273        self.soft_violations
274    }
275
276    /// Number of frames where the hard limit was exceeded.
277    #[inline]
278    #[must_use]
279    pub fn hard_violations(&self) -> u32 {
280        self.hard_violations
281    }
282
283    /// Number of frames where the emergency limit was exceeded.
284    #[inline]
285    #[must_use]
286    pub fn emergency_violations(&self) -> u32 {
287        self.emergency_violations
288    }
289
290    /// Get a reference to the configuration.
291    #[inline]
292    #[must_use]
293    pub fn config(&self) -> &MemoryBudgetConfig {
294        &self.config
295    }
296
297    /// Reset tracking state (preserves config).
298    pub fn reset(&mut self) {
299        self.peak_bytes = 0;
300        self.current_bytes = 0;
301        self.soft_violations = 0;
302        self.hard_violations = 0;
303        self.emergency_violations = 0;
304    }
305}
306
307// =========================================================================
308// Queue depth guardrails
309// =========================================================================
310
311/// Policy for handling frames when queue is full.
312#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
313pub enum QueueDropPolicy {
314    /// Drop the oldest pending frame (display freshest content).
315    #[default]
316    DropOldest,
317    /// Drop the newest frame (preserve sequential ordering).
318    DropNewest,
319    /// Signal backpressure to the producer (don't drop, slow input).
320    Backpressure,
321}
322
323/// Configuration for frame queue depth limits.
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub struct QueueConfig {
326    /// Maximum pending frames before warning.
327    /// Default: 3.
328    pub warn_depth: u32,
329    /// Maximum pending frames before critical action.
330    /// Default: 8.
331    pub max_depth: u32,
332    /// Emergency depth — at this depth the queue is drained hard:
333    /// `DropOldest` keeps only the latest frame, `DropNewest` keeps only the
334    /// oldest, `Backpressure` signals the producer (bd-1za0z: the old
335    /// "drop all but latest" wording described only the default policy).
336    /// Default: 16.
337    pub emergency_depth: u32,
338    pub drop_policy: QueueDropPolicy,
339}
340
341impl Default for QueueConfig {
342    fn default() -> Self {
343        Self {
344            warn_depth: 3,
345            max_depth: 8,
346            emergency_depth: 16,
347            drop_policy: QueueDropPolicy::DropOldest,
348        }
349    }
350}
351
352impl QueueConfig {
353    /// Strict config: small queue, backpressure policy.
354    #[must_use]
355    pub fn strict() -> Self {
356        Self {
357            warn_depth: 2,
358            max_depth: 4,
359            emergency_depth: 8,
360            drop_policy: QueueDropPolicy::Backpressure,
361        }
362    }
363
364    /// Relaxed config: larger queue, drop oldest.
365    #[must_use]
366    pub fn relaxed() -> Self {
367        Self {
368            warn_depth: 8,
369            max_depth: 16,
370            emergency_depth: 32,
371            drop_policy: QueueDropPolicy::DropOldest,
372        }
373    }
374}
375
376/// Queue depth tracker.
377///
378/// Monitors the number of pending frames and produces alerts when
379/// configured thresholds are exceeded.
380#[derive(Debug, Clone)]
381pub struct QueueGuardrails {
382    config: QueueConfig,
383    /// Peak queue depth observed.
384    peak_depth: u32,
385    /// Current queue depth.
386    current_depth: u32,
387    /// Total frames dropped due to queue overflow.
388    total_drops: u64,
389    /// Total backpressure events.
390    total_backpressure_events: u64,
391}
392
393impl QueueGuardrails {
394    /// Create a new queue guardrail with the given configuration.
395    ///
396    /// Thresholds are normalized at construction (same policy as
397    /// `MemoryBudgetConfig`): `warn_depth` is clamped to `max_depth` and
398    /// `max_depth` to `emergency_depth`. A malformed config like
399    /// `warn_depth > max_depth` would otherwise produce zero-excess
400    /// `DropOldest(0)` / `DropNewest(0)` actions at the critical tier —
401    /// alerts that look actionable but do nothing (bd-1za0z).
402    #[must_use]
403    pub fn new(config: QueueConfig) -> Self {
404        // Floor warn at 1: warn_depth 0 would flag an idle queue. Ordering
405        // is then enforced upward so every threshold tier is reachable.
406        let warn_depth = config.warn_depth.max(1);
407        let max_depth = config.max_depth.max(warn_depth);
408        let emergency_depth = config.emergency_depth.max(max_depth);
409        Self {
410            config: QueueConfig {
411                warn_depth,
412                max_depth,
413                emergency_depth,
414                drop_policy: config.drop_policy,
415            },
416            peak_depth: 0,
417            current_depth: 0,
418            total_drops: 0,
419            total_backpressure_events: 0,
420        }
421    }
422
423    /// Report current queue depth and get an alert if thresholds are exceeded.
424    ///
425    /// Returns `(alert, action)` where action indicates what the runtime should
426    /// do about queued frames (if anything).
427    pub fn check(&mut self, current_depth: u32) -> (Option<GuardrailAlert>, QueueAction) {
428        self.current_depth = current_depth;
429        if current_depth > self.peak_depth {
430            self.peak_depth = current_depth;
431        }
432
433        if current_depth >= self.config.emergency_depth {
434            let action = match self.config.drop_policy {
435                QueueDropPolicy::DropOldest => {
436                    let excess = current_depth - 1; // DropOldest: keep only the latest
437                    self.total_drops = self.total_drops.saturating_add(excess as u64);
438                    QueueAction::DropOldest(excess)
439                }
440                QueueDropPolicy::DropNewest => {
441                    let excess = current_depth - 1; // DropNewest: keep only the oldest
442                    self.total_drops = self.total_drops.saturating_add(excess as u64);
443                    QueueAction::DropNewest(excess)
444                }
445                QueueDropPolicy::Backpressure => {
446                    self.total_backpressure_events =
447                        self.total_backpressure_events.saturating_add(1);
448                    QueueAction::Backpressure
449                }
450            };
451            (
452                Some(GuardrailAlert {
453                    kind: GuardrailKind::QueueDepth,
454                    severity: AlertSeverity::Emergency,
455                    recommended_level: DegradationLevel::SkipFrame,
456                }),
457                action,
458            )
459        } else if current_depth >= self.config.max_depth {
460            let action = match self.config.drop_policy {
461                QueueDropPolicy::DropOldest => {
462                    let excess = current_depth.saturating_sub(self.config.warn_depth);
463                    if excess == 0 {
464                        // Thresholds collapsed (e.g. warn == max): the
465                        // critical alert still fires, but there is nothing
466                        // to drop — never emit a no-op Drop(excess=0).
467                        QueueAction::None
468                    } else {
469                        self.total_drops = self.total_drops.saturating_add(u64::from(excess));
470                        QueueAction::DropOldest(excess)
471                    }
472                }
473                QueueDropPolicy::DropNewest => {
474                    let excess = current_depth.saturating_sub(self.config.warn_depth);
475                    if excess == 0 {
476                        QueueAction::None
477                    } else {
478                        self.total_drops = self.total_drops.saturating_add(u64::from(excess));
479                        QueueAction::DropNewest(excess)
480                    }
481                }
482                QueueDropPolicy::Backpressure => {
483                    self.total_backpressure_events =
484                        self.total_backpressure_events.saturating_add(1);
485                    QueueAction::Backpressure
486                }
487            };
488            (
489                Some(GuardrailAlert {
490                    kind: GuardrailKind::QueueDepth,
491                    severity: AlertSeverity::Critical,
492                    recommended_level: DegradationLevel::EssentialOnly,
493                }),
494                action,
495            )
496        } else if current_depth >= self.config.warn_depth {
497            (
498                Some(GuardrailAlert {
499                    kind: GuardrailKind::QueueDepth,
500                    severity: AlertSeverity::Warning,
501                    recommended_level: DegradationLevel::SimpleBorders,
502                }),
503                QueueAction::None,
504            )
505        } else {
506            (None, QueueAction::None)
507        }
508    }
509
510    /// Current queue depth.
511    #[inline]
512    #[must_use]
513    pub fn current_depth(&self) -> u32 {
514        self.current_depth
515    }
516
517    /// Peak queue depth observed.
518    #[inline]
519    #[must_use]
520    pub fn peak_depth(&self) -> u32 {
521        self.peak_depth
522    }
523
524    /// Total frames dropped due to queue overflow.
525    #[inline]
526    #[must_use]
527    pub fn total_drops(&self) -> u64 {
528        self.total_drops
529    }
530
531    /// Total backpressure events.
532    #[inline]
533    #[must_use]
534    pub fn total_backpressure_events(&self) -> u64 {
535        self.total_backpressure_events
536    }
537
538    /// Get a reference to the configuration.
539    #[inline]
540    #[must_use]
541    pub fn config(&self) -> &QueueConfig {
542        &self.config
543    }
544
545    /// Reset tracking state (preserves config).
546    pub fn reset(&mut self) {
547        self.peak_depth = 0;
548        self.current_depth = 0;
549        self.total_drops = 0;
550        self.total_backpressure_events = 0;
551    }
552}
553
554/// Action the runtime should take in response to queue depth.
555#[derive(Debug, Clone, Copy, PartialEq, Eq)]
556pub enum QueueAction {
557    /// No action needed.
558    None,
559    /// Drop the N oldest pending frames.
560    DropOldest(u32),
561    /// Drop the N newest pending frames.
562    DropNewest(u32),
563    /// Signal backpressure to the input source.
564    Backpressure,
565}
566
567impl QueueAction {
568    /// Whether this action requires dropping any frames.
569    #[inline]
570    #[must_use]
571    pub fn drops_frames(self) -> bool {
572        matches!(self, Self::DropOldest(_) | Self::DropNewest(_))
573    }
574}
575
576// =========================================================================
577// Unified guardrails
578// =========================================================================
579
580/// Configuration for the unified frame guardrails.
581#[derive(Debug, Clone)]
582pub struct GuardrailsConfig {
583    /// Memory budget configuration.
584    pub memory: MemoryBudgetConfig,
585    /// Queue depth configuration.
586    pub queue: QueueConfig,
587    /// Optional retained-capacity drift detector; enabled by default.
588    pub leak: Option<LeakDetectorConfig>,
589}
590
591impl Default for GuardrailsConfig {
592    fn default() -> Self {
593        Self {
594            memory: MemoryBudgetConfig::default(),
595            queue: QueueConfig::default(),
596            leak: Some(LeakDetectorConfig::default()),
597        }
598    }
599}
600
601/// Verdict from a guardrail check, combining all subsystem results.
602#[derive(Debug, Clone)]
603pub struct GuardrailVerdict {
604    /// Alerts from all guardrails that fired (may be empty).
605    pub alerts: Vec<GuardrailAlert>,
606    /// Queue action recommended by queue guardrails.
607    pub queue_action: QueueAction,
608    /// The most aggressive degradation level recommended across all alerts.
609    pub recommended_level: DegradationLevel,
610    /// Upward drift evidence, present only when the detector fires.
611    pub leak_alert: Option<LeakAlert>,
612}
613
614impl GuardrailVerdict {
615    /// Whether any guardrail recommends dropping the current frame.
616    #[inline]
617    #[must_use]
618    pub fn should_drop_frame(&self) -> bool {
619        self.recommended_level >= DegradationLevel::SkipFrame
620    }
621
622    /// Whether any guardrail recommends degradation (but not frame skip).
623    #[inline]
624    #[must_use]
625    pub fn should_degrade(&self) -> bool {
626        self.recommended_level > DegradationLevel::Full
627            && self.recommended_level < DegradationLevel::SkipFrame
628    }
629
630    /// Whether all guardrails are satisfied (no alerts).
631    #[inline]
632    #[must_use]
633    pub fn is_clear(&self) -> bool {
634        self.alerts.is_empty()
635    }
636
637    /// The highest severity among all alerts, or `None` if clear.
638    #[must_use]
639    pub fn max_severity(&self) -> Option<AlertSeverity> {
640        self.alerts.iter().map(|a| a.severity).max()
641    }
642}
643
644/// Unified memory budget, queue depth limits, and retained-capacity drift detection.
645///
646/// Call [`check_frame`](Self::check_frame) once per frame with current resource
647/// usage. The returned [`GuardrailVerdict`] tells you what (if anything) to do.
648#[derive(Debug, Clone)]
649pub struct FrameGuardrails {
650    memory: MemoryBudget,
651    queue: QueueGuardrails,
652    leak: Option<AllocLeakDetector>,
653    leak_alert: bool,
654    /// Total frames checked.
655    frames_checked: u64,
656    /// Total frames where at least one alert fired.
657    frames_with_alerts: u64,
658}
659
660impl FrameGuardrails {
661    /// Create a new unified guardrails instance.
662    #[must_use]
663    pub fn new(config: GuardrailsConfig) -> Self {
664        Self {
665            memory: MemoryBudget::new(config.memory),
666            queue: QueueGuardrails::new(config.queue),
667            leak: config.leak.map(AllocLeakDetector::new),
668            leak_alert: false,
669            frames_checked: 0,
670            frames_with_alerts: 0,
671        }
672    }
673
674    /// Check all guardrails for the current frame.
675    ///
676    /// `memory_bytes`: retained rendering capacity (buffer + pools + arena),
677    /// not live allocator usage. A downward shift alone is not a leak.
678    /// `queue_depth`: number of pending frames waiting to be rendered.
679    pub fn check_frame(&mut self, memory_bytes: usize, queue_depth: u32) -> GuardrailVerdict {
680        self.frames_checked = self.frames_checked.saturating_add(1);
681
682        let mut alerts = Vec::new();
683        let mut max_level = DegradationLevel::Full;
684
685        // Memory check
686        if let Some(alert) = self.memory.check(memory_bytes) {
687            if alert.recommended_level > max_level {
688                max_level = alert.recommended_level;
689            }
690            alerts.push(alert);
691        }
692
693        // Queue check
694        let (queue_alert, queue_action) = self.queue.check(queue_depth);
695        if let Some(alert) = queue_alert {
696            if alert.recommended_level > max_level {
697                max_level = alert.recommended_level;
698            }
699            alerts.push(alert);
700        }
701
702        let leak_alert = self.leak.as_mut().and_then(|detector| {
703            let mut alert = detector.observe_unrecorded(memory_bytes as f64);
704            // The general detector is two-sided; releasing capacity is not
705            // an allocation leak. Keep only its upward CUSUM/e-process signal.
706            alert.cusum_triggered = alert.cusum_upper > detector.cusum_threshold();
707            alert.triggered = alert.cusum_triggered || alert.eprocess_triggered;
708            alert.triggered.then_some(alert)
709        });
710        self.leak_alert = leak_alert.is_some();
711        if self.leak_alert {
712            // Suspected growth is diagnostic, not proof of memory pressure.
713            // Only the independent absolute budget may degrade or drop frames.
714            alerts.push(GuardrailAlert {
715                kind: GuardrailKind::AllocationLeak,
716                severity: AlertSeverity::Warning,
717                recommended_level: DegradationLevel::Full,
718            });
719        }
720
721        if !alerts.is_empty() {
722            self.frames_with_alerts = self.frames_with_alerts.saturating_add(1);
723        }
724
725        GuardrailVerdict {
726            alerts,
727            queue_action,
728            recommended_level: max_level,
729            leak_alert,
730        }
731    }
732
733    /// Access the memory budget subsystem.
734    #[inline]
735    #[must_use]
736    pub fn memory(&self) -> &MemoryBudget {
737        &self.memory
738    }
739
740    /// Access the queue guardrails subsystem.
741    #[inline]
742    #[must_use]
743    pub fn queue(&self) -> &QueueGuardrails {
744        &self.queue
745    }
746
747    /// Total frames checked.
748    #[inline]
749    #[must_use]
750    pub fn frames_checked(&self) -> u64 {
751        self.frames_checked
752    }
753
754    /// Total frames where at least one alert fired.
755    #[inline]
756    #[must_use]
757    pub fn frames_with_alerts(&self) -> u64 {
758        self.frames_with_alerts
759    }
760
761    /// Fraction of frames that triggered alerts (0.0–1.0).
762    #[inline]
763    #[must_use]
764    pub fn alert_rate(&self) -> f64 {
765        if self.frames_checked == 0 {
766            return 0.0;
767        }
768        self.frames_with_alerts as f64 / self.frames_checked as f64
769    }
770
771    /// Capture a diagnostic snapshot.
772    #[must_use]
773    pub fn snapshot(&self) -> GuardrailSnapshot {
774        GuardrailSnapshot {
775            memory_bytes: self.memory.current_bytes(),
776            memory_peak_bytes: self.memory.peak_bytes(),
777            memory_usage_fraction: self.memory.usage_fraction(),
778            memory_soft_violations: self.memory.soft_violations(),
779            memory_hard_violations: self.memory.hard_violations(),
780            memory_emergency_violations: self.memory.emergency_violations(),
781            queue_depth: self.queue.current_depth(),
782            queue_peak_depth: self.queue.peak_depth(),
783            queue_total_drops: self.queue.total_drops(),
784            queue_total_backpressure: self.queue.total_backpressure_events(),
785            frames_checked: self.frames_checked,
786            frames_with_alerts: self.frames_with_alerts,
787            leak_e_value: self.leak.as_ref().map_or(1.0, AllocLeakDetector::e_value),
788            leak_cusum_upper: self
789                .leak
790                .as_ref()
791                .map_or(0.0, AllocLeakDetector::cusum_upper),
792            leak_mean_bytes: self.leak.as_ref().map_or(0.0, AllocLeakDetector::mean),
793            leak_alert: self.leak_alert,
794        }
795    }
796
797    /// Start a new capacity baseline after an intentional trim or emergency shed.
798    pub fn reset_leak_detector(&mut self) {
799        if let Some(detector) = self.leak.as_mut() {
800            detector.reset();
801        }
802        self.leak_alert = false;
803    }
804
805    /// Reset all tracking state (preserves configs).
806    pub fn reset(&mut self) {
807        self.memory.reset();
808        self.queue.reset();
809        self.reset_leak_detector();
810        self.frames_checked = 0;
811        self.frames_with_alerts = 0;
812    }
813}
814
815/// Diagnostic snapshot of guardrail state.
816///
817/// All fields are `Copy` — no allocations. Suitable for structured logging
818/// or debug overlay.
819#[derive(Debug, Clone, Copy, PartialEq)]
820pub struct GuardrailSnapshot {
821    /// Current e-process wealth (1 when disabled or reset).
822    pub leak_e_value: f64,
823    /// Upward CUSUM statistic (0 when disabled or reset).
824    pub leak_cusum_upper: f64,
825    /// Mean retained rendering capacity in bytes.
826    pub leak_mean_bytes: f64,
827    /// Whether the most recent frame indicated upward capacity drift.
828    pub leak_alert: bool,
829    /// Current memory usage in bytes.
830    pub memory_bytes: usize,
831    /// Peak memory usage in bytes.
832    pub memory_peak_bytes: usize,
833    /// Fraction of soft memory limit used.
834    pub memory_usage_fraction: f64,
835    /// Frames exceeding soft memory limit.
836    pub memory_soft_violations: u32,
837    /// Frames exceeding hard memory limit.
838    pub memory_hard_violations: u32,
839    /// Frames exceeding the emergency memory limit (frame shed + arena
840    /// rebuild). Kept distinct from [`Self::memory_hard_violations`]
841    /// (bd-1za0z F5).
842    pub memory_emergency_violations: u32,
843    /// Current queue depth.
844    pub queue_depth: u32,
845    /// Peak queue depth.
846    pub queue_peak_depth: u32,
847    /// Total frames dropped from queue.
848    pub queue_total_drops: u64,
849    /// Total backpressure events.
850    pub queue_total_backpressure: u64,
851    /// Total frames checked.
852    pub frames_checked: u64,
853    /// Total frames with alerts.
854    pub frames_with_alerts: u64,
855}
856
857impl GuardrailSnapshot {
858    /// Serialize to a JSONL-compatible string.
859    pub fn to_jsonl(&self) -> String {
860        format!(
861            concat!(
862                r#"{{"memory_bytes":{},"memory_peak":{},"memory_frac":{:.4},"#,
863                r#""mem_soft_violations":{},"mem_hard_violations":{},"mem_emergency_violations":{},"#,
864                r#""queue_depth":{},"queue_peak":{},"queue_drops":{},"#,
865                r#""queue_backpressure":{},"frames_checked":{},"frames_alerted":{},"#,
866                r#""leak_e_value":{:e},"leak_cusum_upper":{},"leak_mean_bytes":{},"leak_alert":{}}}"#,
867            ),
868            self.memory_bytes,
869            self.memory_peak_bytes,
870            self.memory_usage_fraction,
871            self.memory_soft_violations,
872            self.memory_hard_violations,
873            self.memory_emergency_violations,
874            self.queue_depth,
875            self.queue_peak_depth,
876            self.queue_total_drops,
877            self.queue_total_backpressure,
878            self.frames_checked,
879            self.frames_with_alerts,
880            self.leak_e_value,
881            self.leak_cusum_upper,
882            self.leak_mean_bytes,
883            self.leak_alert,
884        )
885    }
886}
887
888// =========================================================================
889// Utility: compute buffer memory
890// =========================================================================
891
892/// Size of a single Cell in bytes (compile-time constant).
893pub const CELL_SIZE_BYTES: usize = 16;
894
895/// Compute the memory footprint of a buffer with the given dimensions.
896///
897/// This accounts for the cell array only (not dirty tracking or stack metadata).
898#[inline]
899#[must_use]
900pub fn buffer_memory_bytes(width: u16, height: u16) -> usize {
901    width as usize * height as usize * CELL_SIZE_BYTES
902}
903
904// =========================================================================
905// Tests
906// =========================================================================
907
908#[cfg(test)]
909mod tests {
910    use super::*;
911
912    #[test]
913    fn guardrails_detect_allocation_drift() {
914        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
915        for i in 0..200 {
916            let bytes = 1024 * 1024 + if i % 2 == 0 { 1024 } else { 0 };
917            assert!(g.check_frame(bytes, 0).leak_alert.is_none());
918        }
919        let mut detected = false;
920        for i in 1..=100 {
921            let verdict = g.check_frame(1024 * 1024 + i * 64 * 1024, 0);
922            if verdict.leak_alert.is_some() {
923                detected = true;
924                assert!(
925                    verdict
926                        .alerts
927                        .iter()
928                        .any(|a| a.kind == GuardrailKind::AllocationLeak)
929                );
930                assert!(!verdict.is_clear());
931                assert!(!verdict.should_degrade());
932                assert!(!verdict.should_drop_frame());
933                assert!(g.snapshot().leak_alert);
934            }
935        }
936        assert!(detected, "sustained capacity growth must produce evidence");
937        assert!(g.leak.as_ref().unwrap().ledger().is_empty());
938    }
939
940    #[test]
941    fn leak_detector_reset_after_trim_suppresses_false_alert() {
942        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
943        for _ in 0..200 {
944            g.check_frame(1024 * 1024, 0);
945        }
946        assert!(g.check_frame(2 * 1024 * 1024, 0).leak_alert.is_some());
947        let checked = g.frames_checked();
948        g.reset_leak_detector();
949        assert_eq!(g.frames_checked(), checked);
950        assert!(!g.snapshot().leak_alert);
951        for _ in 0..200 {
952            assert!(g.check_frame(1024, 0).leak_alert.is_none());
953        }
954    }
955
956    #[test]
957    fn capacity_decrease_is_not_a_leak() {
958        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
959        for _ in 0..200 {
960            g.check_frame(1024 * 1024, 0);
961        }
962        for _ in 0..100 {
963            assert!(g.check_frame(1024, 0).leak_alert.is_none());
964        }
965        assert!(g.leak.as_ref().unwrap().cusum_lower() > 8.0);
966    }
967
968    #[test]
969    fn disabled_leak_detector_preserves_memory_enforcement() {
970        let mut g = FrameGuardrails::new(GuardrailsConfig {
971            leak: None,
972            ..Default::default()
973        });
974        for i in 0..200 {
975            assert!(g.check_frame(i * 1024, 0).leak_alert.is_none());
976        }
977        assert!(g.check_frame(32 * 1024 * 1024, 0).should_drop_frame());
978        g.reset_leak_detector();
979        assert!(!g.snapshot().leak_alert);
980    }
981
982    #[test]
983    fn sustained_growth_keeps_snapshot_json_finite() {
984        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
985        for i in 0..4000 {
986            let bytes = if i < 200 { 1024 } else { i * 1024 };
987            g.check_frame(bytes, 0);
988        }
989        let snapshot = g.snapshot();
990        assert!(snapshot.leak_alert);
991        assert_eq!(snapshot.leak_e_value, f64::MAX);
992        let json: serde_json::Value = serde_json::from_str(&snapshot.to_jsonl()).unwrap();
993        assert!(json["leak_e_value"].as_f64().unwrap().is_finite());
994    }
995
996    proptest::proptest! {
997        #![proptest_config(proptest::test_runner::Config::with_cases(512))]
998
999        #[test]
1000        fn proptest_no_alert_on_stationary_series(
1001            baseline in 4096usize..4 * 1024 * 1024,
1002            amplitude in 0usize..1024,
1003            phase in proptest::bool::ANY,
1004        ) {
1005            let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1006            // A bounded, balanced stationary series at different scales and phases.
1007            // This is not a universal zero-false-positive statistical claim.
1008            for i in 0..400 {
1009                let bytes = if (i % 2 == 0) == phase {
1010                    baseline + amplitude
1011                } else {
1012                    baseline - amplitude
1013                };
1014                proptest::prop_assert!(g.check_frame(bytes, 0).leak_alert.is_none());
1015            }
1016        }
1017
1018        #[test]
1019        fn proptest_no_leak_alert_on_stationary_series(
1020            baseline in 4096usize..4 * 1024 * 1024,
1021            amplitude in 0usize..1024,
1022            phase in proptest::bool::ANY,
1023        ) {
1024            let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1025            for i in 0..1_000 {
1026                let bytes = if (i % 2 == 0) == phase {
1027                    baseline + amplitude
1028                } else {
1029                    baseline - amplitude
1030                };
1031                proptest::prop_assert!(g.check_frame(bytes, 0).leak_alert.is_none());
1032            }
1033        }
1034    }
1035
1036    #[test]
1037    fn zero_and_inverted_configs_are_normalized() {
1038        // Regression: an all-zero config classified EVERY frame Emergency
1039        // (>= comparisons) — blank screen from startup; inverted watermarks
1040        // silently misclassified. new() now normalizes.
1041        let zero = MemoryBudget::new(MemoryBudgetConfig {
1042            soft_limit_bytes: 0,
1043            hard_limit_bytes: 0,
1044            emergency_limit_bytes: 0,
1045        });
1046        assert!(zero.config.soft_limit_bytes > 0);
1047        assert!(zero.config.soft_limit_bytes <= zero.config.hard_limit_bytes);
1048        assert!(zero.config.hard_limit_bytes <= zero.config.emergency_limit_bytes);
1049
1050        let inverted = MemoryBudget::new(MemoryBudgetConfig {
1051            soft_limit_bytes: 32 * 1024 * 1024,
1052            hard_limit_bytes: 8 * 1024 * 1024,
1053            emergency_limit_bytes: 16 * 1024 * 1024,
1054        });
1055        assert!(inverted.config.soft_limit_bytes <= inverted.config.hard_limit_bytes);
1056        assert!(inverted.config.hard_limit_bytes <= inverted.config.emergency_limit_bytes);
1057    }
1058
1059    // ---- MemoryBudget ----
1060
1061    #[test]
1062    fn memory_below_soft_no_alert() {
1063        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1064        assert!(mb.check(1024).is_none());
1065        assert_eq!(mb.current_bytes(), 1024);
1066    }
1067
1068    #[test]
1069    fn memory_at_soft_limit_warns() {
1070        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1071        let alert = mb.check(8 * 1024 * 1024).unwrap();
1072        assert_eq!(alert.kind, GuardrailKind::Memory);
1073        assert_eq!(alert.severity, AlertSeverity::Warning);
1074        assert_eq!(alert.recommended_level, DegradationLevel::SimpleBorders);
1075    }
1076
1077    #[test]
1078    fn memory_at_hard_limit_critical() {
1079        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1080        let alert = mb.check(16 * 1024 * 1024).unwrap();
1081        assert_eq!(alert.severity, AlertSeverity::Critical);
1082        assert_eq!(alert.recommended_level, DegradationLevel::Skeleton);
1083    }
1084
1085    #[test]
1086    fn memory_at_emergency_limit() {
1087        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1088        let alert = mb.check(32 * 1024 * 1024).unwrap();
1089        assert_eq!(alert.severity, AlertSeverity::Emergency);
1090        assert_eq!(alert.recommended_level, DegradationLevel::SkipFrame);
1091    }
1092
1093    #[test]
1094    fn memory_peak_tracking() {
1095        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1096        mb.check(1000);
1097        mb.check(5000);
1098        mb.check(3000);
1099        assert_eq!(mb.peak_bytes(), 5000);
1100        assert_eq!(mb.current_bytes(), 3000);
1101    }
1102
1103    #[test]
1104    fn memory_violation_counts() {
1105        let config = MemoryBudgetConfig {
1106            soft_limit_bytes: 100,
1107            hard_limit_bytes: 200,
1108            emergency_limit_bytes: 300,
1109        };
1110        let mut mb = MemoryBudget::new(config);
1111        mb.check(50); // no violation
1112        mb.check(150); // soft
1113        mb.check(150); // soft again
1114        mb.check(250); // hard
1115        mb.check(350); // emergency — its own tier, NOT a hard violation
1116        assert_eq!(mb.soft_violations(), 2);
1117        assert_eq!(mb.hard_violations(), 1);
1118        assert_eq!(
1119            mb.emergency_violations(),
1120            1,
1121            "emergency shedding must be counted separately from hard hits (bd-1za0z F5)"
1122        );
1123    }
1124
1125    #[test]
1126    fn memory_usage_fraction() {
1127        let config = MemoryBudgetConfig {
1128            soft_limit_bytes: 1000,
1129            hard_limit_bytes: 2000,
1130            emergency_limit_bytes: 3000,
1131        };
1132        let mut mb = MemoryBudget::new(config);
1133        mb.check(500);
1134        assert!((mb.usage_fraction() - 0.5).abs() < f64::EPSILON);
1135    }
1136
1137    #[test]
1138    fn memory_usage_fraction_zero_limit() {
1139        // The constructor normalizes zero limits to defaults (an all-zero
1140        // config used to classify every frame Emergency), so a zero-limit
1141        // budget is no longer constructible via new(); 100 bytes against
1142        // the default 8 MiB soft limit is a tiny fraction.
1143        let config = MemoryBudgetConfig {
1144            soft_limit_bytes: 0,
1145            hard_limit_bytes: 0,
1146            emergency_limit_bytes: 0,
1147        };
1148        let mut mb = MemoryBudget::new(config);
1149        mb.check(100);
1150        assert!(mb.usage_fraction() > 0.0);
1151        assert!(mb.usage_fraction() < 0.001);
1152    }
1153
1154    #[test]
1155    fn memory_reset_clears_state() {
1156        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1157        mb.check(10 * 1024 * 1024); // soft violation
1158        assert!(mb.soft_violations() > 0);
1159        mb.reset();
1160        assert_eq!(mb.peak_bytes(), 0);
1161        assert_eq!(mb.current_bytes(), 0);
1162        assert_eq!(mb.soft_violations(), 0);
1163        assert_eq!(mb.hard_violations(), 0);
1164    }
1165
1166    #[test]
1167    fn memory_config_accessors() {
1168        let config = MemoryBudgetConfig::small();
1169        let mb = MemoryBudget::new(config);
1170        assert_eq!(mb.config().soft_limit_bytes, 2 * 1024 * 1024);
1171    }
1172
1173    // ---- QueueGuardrails ----
1174
1175    #[test]
1176    fn queue_below_warn_no_alert() {
1177        let mut qg = QueueGuardrails::new(QueueConfig::default());
1178        let (alert, action) = qg.check(1);
1179        assert!(alert.is_none());
1180        assert_eq!(action, QueueAction::None);
1181    }
1182
1183    #[test]
1184    fn queue_at_warn_depth() {
1185        let mut qg = QueueGuardrails::new(QueueConfig::default());
1186        let (alert, action) = qg.check(3);
1187        assert_eq!(alert.unwrap().severity, AlertSeverity::Warning);
1188        assert_eq!(action, QueueAction::None); // warning only, no action
1189    }
1190
1191    #[test]
1192    fn queue_at_max_depth_drop_oldest() {
1193        let config = QueueConfig {
1194            drop_policy: QueueDropPolicy::DropOldest,
1195            ..QueueConfig::default()
1196        };
1197        let mut qg = QueueGuardrails::new(config);
1198        let (alert, action) = qg.check(8);
1199        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
1200        assert!(action.drops_frames());
1201    }
1202
1203    #[test]
1204    fn queue_at_max_depth_drop_newest() {
1205        let config = QueueConfig {
1206            drop_policy: QueueDropPolicy::DropNewest,
1207            ..QueueConfig::default()
1208        };
1209        let mut qg = QueueGuardrails::new(config);
1210        let (alert, action) = qg.check(8);
1211        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
1212        assert_eq!(action, QueueAction::DropNewest(5));
1213    }
1214
1215    #[test]
1216    fn queue_at_max_depth_backpressure() {
1217        let config = QueueConfig {
1218            drop_policy: QueueDropPolicy::Backpressure,
1219            ..QueueConfig::default()
1220        };
1221        let mut qg = QueueGuardrails::new(config);
1222        let (alert, action) = qg.check(8);
1223        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
1224        assert_eq!(action, QueueAction::Backpressure);
1225    }
1226
1227    #[test]
1228    fn queue_emergency_drops_to_latest() {
1229        let mut qg = QueueGuardrails::new(QueueConfig::default());
1230        let (alert, action) = qg.check(16);
1231        assert_eq!(alert.unwrap().severity, AlertSeverity::Emergency);
1232        // DropOldest at emergency should keep only 1 frame
1233        assert_eq!(action, QueueAction::DropOldest(15));
1234    }
1235
1236    #[test]
1237    fn queue_peak_tracking() {
1238        let mut qg = QueueGuardrails::new(QueueConfig::default());
1239        qg.check(2);
1240        qg.check(5);
1241        qg.check(1);
1242        assert_eq!(qg.peak_depth(), 5);
1243        assert_eq!(qg.current_depth(), 1);
1244    }
1245
1246    #[test]
1247    fn queue_drop_counting() {
1248        let mut qg = QueueGuardrails::new(QueueConfig::default());
1249        qg.check(8); // triggers drop
1250        assert!(qg.total_drops() > 0);
1251    }
1252
1253    #[test]
1254    fn queue_backpressure_counting() {
1255        let config = QueueConfig::strict();
1256        let mut qg = QueueGuardrails::new(config);
1257        qg.check(4); // max_depth for strict
1258        assert!(qg.total_backpressure_events() > 0);
1259    }
1260
1261    #[test]
1262    fn queue_reset_clears_state() {
1263        let mut qg = QueueGuardrails::new(QueueConfig::default());
1264        qg.check(10);
1265        qg.reset();
1266        assert_eq!(qg.peak_depth(), 0);
1267        assert_eq!(qg.current_depth(), 0);
1268        assert_eq!(qg.total_drops(), 0);
1269    }
1270
1271    #[test]
1272    fn queue_config_accessors() {
1273        let config = QueueConfig::relaxed();
1274        let qg = QueueGuardrails::new(config);
1275        assert_eq!(qg.config().max_depth, 16);
1276    }
1277
1278    /// CONTRACT (bd-1za0z): malformed threshold ordering is normalized at
1279    /// construction — warn <= max <= emergency, warn floored at 1.
1280    #[test]
1281    fn queue_config_normalized_at_construction() {
1282        let config = QueueConfig {
1283            warn_depth: 10,
1284            max_depth: 8,
1285            emergency_depth: 6,
1286            drop_policy: QueueDropPolicy::DropOldest,
1287        };
1288        let qg = QueueGuardrails::new(config);
1289        let cfg = qg.config();
1290        assert_eq!(cfg.warn_depth, 10);
1291        assert_eq!(cfg.max_depth, 10, "max must be raised to warn");
1292        assert_eq!(cfg.emergency_depth, 10, "emergency must be raised to max");
1293
1294        let zeroed = QueueGuardrails::new(QueueConfig {
1295            warn_depth: 0,
1296            ..QueueConfig::default()
1297        });
1298        assert_eq!(
1299            zeroed.config().warn_depth,
1300            1,
1301            "warn_depth 0 would flag an idle queue"
1302        );
1303    }
1304
1305    /// CONTRACT (bd-1za0z): collapsed thresholds (warn == max) must never
1306    /// produce a zero-excess Drop action; the critical alert still fires.
1307    #[test]
1308    fn queue_collapsed_thresholds_yield_noop_action_not_zero_drop() {
1309        let config = QueueConfig {
1310            warn_depth: 8,
1311            max_depth: 8,
1312            emergency_depth: 16,
1313            drop_policy: QueueDropPolicy::DropOldest,
1314        };
1315        let mut qg = QueueGuardrails::new(config);
1316        let (alert, action) = qg.check(8);
1317        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
1318        assert_eq!(
1319            action,
1320            QueueAction::None,
1321            "excess 0 must not be reported as a real drop action"
1322        );
1323        assert_eq!(qg.total_drops(), 0, "no-op action must not count drops");
1324    }
1325
1326    /// CONTRACT (bd-1za0z): DropNewest at emergency keeps the oldest frame
1327    /// (drops the newest excess) — policy-relative semantics, now documented
1328    /// on the config field.
1329    #[test]
1330    fn queue_emergency_drop_newest_keeps_oldest() {
1331        let config = QueueConfig {
1332            drop_policy: QueueDropPolicy::DropNewest,
1333            ..QueueConfig::default()
1334        };
1335        let mut qg = QueueGuardrails::new(config);
1336        let (alert, action) = qg.check(16);
1337        assert_eq!(alert.unwrap().severity, AlertSeverity::Emergency);
1338        assert_eq!(action, QueueAction::DropNewest(15));
1339    }
1340
1341    // ---- QueueAction ----
1342
1343    #[test]
1344    fn queue_action_drops_frames() {
1345        assert!(!QueueAction::None.drops_frames());
1346        assert!(QueueAction::DropOldest(3).drops_frames());
1347        assert!(QueueAction::DropNewest(1).drops_frames());
1348        assert!(!QueueAction::Backpressure.drops_frames());
1349    }
1350
1351    // ---- FrameGuardrails ----
1352
1353    #[test]
1354    fn guardrails_clear_when_healthy() {
1355        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1356        let v = g.check_frame(1024, 0);
1357        assert!(v.is_clear());
1358        assert_eq!(v.recommended_level, DegradationLevel::Full);
1359        assert_eq!(v.queue_action, QueueAction::None);
1360    }
1361
1362    #[test]
1363    fn guardrails_memory_alert_propagates() {
1364        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1365        let v = g.check_frame(8 * 1024 * 1024, 0);
1366        assert!(!v.is_clear());
1367        assert_eq!(v.alerts.len(), 1);
1368        assert_eq!(v.alerts[0].kind, GuardrailKind::Memory);
1369        assert!(v.should_degrade());
1370        assert!(!v.should_drop_frame());
1371    }
1372
1373    #[test]
1374    fn guardrails_queue_alert_propagates() {
1375        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1376        let v = g.check_frame(0, 8);
1377        assert!(!v.is_clear());
1378        assert!(v.alerts.iter().any(|a| a.kind == GuardrailKind::QueueDepth));
1379    }
1380
1381    #[test]
1382    fn guardrails_both_alerts_combine() {
1383        let config = GuardrailsConfig {
1384            memory: MemoryBudgetConfig {
1385                soft_limit_bytes: 100,
1386                hard_limit_bytes: 200,
1387                emergency_limit_bytes: 300,
1388            },
1389            queue: QueueConfig {
1390                warn_depth: 1,
1391                max_depth: 2,
1392                emergency_depth: 3,
1393                drop_policy: QueueDropPolicy::DropOldest,
1394            },
1395            ..Default::default()
1396        };
1397        let mut g = FrameGuardrails::new(config);
1398        let v = g.check_frame(150, 2);
1399        assert_eq!(v.alerts.len(), 2);
1400        // Should use the most aggressive recommendation
1401        assert!(v.recommended_level >= DegradationLevel::SimpleBorders);
1402    }
1403
1404    #[test]
1405    fn guardrails_emergency_recommends_skip() {
1406        let config = GuardrailsConfig {
1407            memory: MemoryBudgetConfig {
1408                soft_limit_bytes: 100,
1409                hard_limit_bytes: 200,
1410                emergency_limit_bytes: 300,
1411            },
1412            queue: QueueConfig::default(),
1413            ..Default::default()
1414        };
1415        let mut g = FrameGuardrails::new(config);
1416        let v = g.check_frame(300, 0);
1417        assert!(v.should_drop_frame());
1418    }
1419
1420    #[test]
1421    fn guardrails_frame_counting() {
1422        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1423        g.check_frame(0, 0);
1424        g.check_frame(0, 0);
1425        g.check_frame(8 * 1024 * 1024, 0); // triggers alert
1426        assert_eq!(g.frames_checked(), 3);
1427        assert_eq!(g.frames_with_alerts(), 1);
1428    }
1429
1430    #[test]
1431    fn guardrails_alert_rate() {
1432        let config = GuardrailsConfig {
1433            memory: MemoryBudgetConfig {
1434                soft_limit_bytes: 100,
1435                hard_limit_bytes: 200,
1436                emergency_limit_bytes: 300,
1437            },
1438            queue: QueueConfig::default(),
1439            ..Default::default()
1440        };
1441        let mut g = FrameGuardrails::new(config);
1442        g.check_frame(50, 0); // clear
1443        g.check_frame(150, 0); // alert
1444        g.check_frame(50, 0); // clear
1445        g.check_frame(150, 0); // alert
1446        assert!((g.alert_rate() - 0.5).abs() < f64::EPSILON);
1447    }
1448
1449    #[test]
1450    fn guardrails_alert_rate_zero_frames() {
1451        let g = FrameGuardrails::new(GuardrailsConfig::default());
1452        assert!((g.alert_rate() - 0.0).abs() < f64::EPSILON);
1453    }
1454
1455    #[test]
1456    fn guardrails_snapshot_jsonl() {
1457        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1458        g.check_frame(1024, 1);
1459        let snap = g.snapshot();
1460        let line = snap.to_jsonl();
1461        assert!(line.starts_with('{'));
1462        assert!(line.ends_with('}'));
1463        assert!(line.contains("\"memory_bytes\":1024"));
1464        assert!(line.contains("\"queue_depth\":1"));
1465        assert!(line.contains("\"leak_e_value\":1"));
1466        assert!(line.contains("\"leak_cusum_upper\":0"));
1467        assert!(line.contains("\"leak_mean_bytes\":1024"));
1468        assert!(line.contains("\"leak_alert\":false"));
1469    }
1470
1471    #[test]
1472    fn guardrail_snapshot_jsonl_has_leak_fields() {
1473        guardrails_snapshot_jsonl();
1474    }
1475
1476    #[test]
1477    fn guardrails_reset_clears_all() {
1478        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1479        g.check_frame(8 * 1024 * 1024, 5);
1480        g.reset();
1481        assert_eq!(g.frames_checked(), 0);
1482        assert_eq!(g.frames_with_alerts(), 0);
1483        assert_eq!(g.memory().peak_bytes(), 0);
1484        assert_eq!(g.queue().peak_depth(), 0);
1485    }
1486
1487    #[test]
1488    fn guardrails_subsystem_access() {
1489        let g = FrameGuardrails::new(GuardrailsConfig::default());
1490        let _ = g.memory().config();
1491        let _ = g.queue().config();
1492    }
1493
1494    // ---- GuardrailVerdict ----
1495
1496    #[test]
1497    fn verdict_max_severity_none_when_clear() {
1498        let v = GuardrailVerdict {
1499            alerts: vec![],
1500            queue_action: QueueAction::None,
1501            recommended_level: DegradationLevel::Full,
1502            leak_alert: None,
1503        };
1504        assert!(v.max_severity().is_none());
1505        assert!(v.is_clear());
1506    }
1507
1508    #[test]
1509    fn verdict_max_severity_picks_highest() {
1510        let v = GuardrailVerdict {
1511            alerts: vec![
1512                GuardrailAlert {
1513                    kind: GuardrailKind::Memory,
1514                    severity: AlertSeverity::Warning,
1515                    recommended_level: DegradationLevel::SimpleBorders,
1516                },
1517                GuardrailAlert {
1518                    kind: GuardrailKind::QueueDepth,
1519                    severity: AlertSeverity::Critical,
1520                    recommended_level: DegradationLevel::EssentialOnly,
1521                },
1522            ],
1523            queue_action: QueueAction::None,
1524            recommended_level: DegradationLevel::EssentialOnly,
1525            leak_alert: None,
1526        };
1527        assert_eq!(v.max_severity(), Some(AlertSeverity::Critical));
1528    }
1529
1530    // ---- AlertSeverity ordering ----
1531
1532    #[test]
1533    fn severity_ordering() {
1534        assert!(AlertSeverity::Warning < AlertSeverity::Critical);
1535        assert!(AlertSeverity::Critical < AlertSeverity::Emergency);
1536    }
1537
1538    // ---- Config presets ----
1539
1540    #[test]
1541    fn memory_config_small_preset() {
1542        let c = MemoryBudgetConfig::small();
1543        assert!(c.soft_limit_bytes < MemoryBudgetConfig::default().soft_limit_bytes);
1544    }
1545
1546    #[test]
1547    fn memory_config_large_preset() {
1548        let c = MemoryBudgetConfig::large();
1549        assert!(c.soft_limit_bytes > MemoryBudgetConfig::default().soft_limit_bytes);
1550    }
1551
1552    #[test]
1553    fn queue_config_strict_preset() {
1554        let c = QueueConfig::strict();
1555        assert_eq!(c.drop_policy, QueueDropPolicy::Backpressure);
1556        assert!(c.max_depth < QueueConfig::default().max_depth);
1557    }
1558
1559    #[test]
1560    fn queue_config_relaxed_preset() {
1561        let c = QueueConfig::relaxed();
1562        assert!(c.max_depth > QueueConfig::default().max_depth);
1563    }
1564
1565    // ---- buffer_memory_bytes ----
1566
1567    #[test]
1568    fn buffer_memory_typical_terminal() {
1569        // 80×24 terminal
1570        assert_eq!(buffer_memory_bytes(80, 24), 80 * 24 * 16);
1571    }
1572
1573    #[test]
1574    fn buffer_memory_zero_dimension() {
1575        assert_eq!(buffer_memory_bytes(0, 24), 0);
1576        assert_eq!(buffer_memory_bytes(80, 0), 0);
1577        assert_eq!(buffer_memory_bytes(0, 0), 0);
1578    }
1579
1580    #[test]
1581    fn buffer_memory_large_terminal() {
1582        // 300×100 terminal
1583        let bytes = buffer_memory_bytes(300, 100);
1584        assert_eq!(bytes, 300 * 100 * 16);
1585        assert_eq!(bytes, 480_000);
1586    }
1587
1588    // ---- QueueDropPolicy Default ----
1589
1590    #[test]
1591    fn queue_drop_policy_default_is_drop_oldest() {
1592        assert_eq!(QueueDropPolicy::default(), QueueDropPolicy::DropOldest);
1593    }
1594
1595    // ---- Determinism ----
1596
1597    #[test]
1598    fn guardrails_deterministic_for_same_inputs() {
1599        let config = GuardrailsConfig::default();
1600        let mut g1 = FrameGuardrails::new(config.clone());
1601        let mut g2 = FrameGuardrails::new(config);
1602
1603        let inputs = [(1024, 0), (8 * 1024 * 1024, 3), (20 * 1024 * 1024, 10)];
1604        for (mem, queue) in inputs {
1605            let v1 = g1.check_frame(mem, queue);
1606            let v2 = g2.check_frame(mem, queue);
1607            assert_eq!(v1.recommended_level, v2.recommended_level);
1608            assert_eq!(v1.alerts.len(), v2.alerts.len());
1609            assert_eq!(v1.queue_action, v2.queue_action);
1610        }
1611    }
1612}