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
1019    #[test]
1020    fn zero_and_inverted_configs_are_normalized() {
1021        // Regression: an all-zero config classified EVERY frame Emergency
1022        // (>= comparisons) — blank screen from startup; inverted watermarks
1023        // silently misclassified. new() now normalizes.
1024        let zero = MemoryBudget::new(MemoryBudgetConfig {
1025            soft_limit_bytes: 0,
1026            hard_limit_bytes: 0,
1027            emergency_limit_bytes: 0,
1028        });
1029        assert!(zero.config.soft_limit_bytes > 0);
1030        assert!(zero.config.soft_limit_bytes <= zero.config.hard_limit_bytes);
1031        assert!(zero.config.hard_limit_bytes <= zero.config.emergency_limit_bytes);
1032
1033        let inverted = MemoryBudget::new(MemoryBudgetConfig {
1034            soft_limit_bytes: 32 * 1024 * 1024,
1035            hard_limit_bytes: 8 * 1024 * 1024,
1036            emergency_limit_bytes: 16 * 1024 * 1024,
1037        });
1038        assert!(inverted.config.soft_limit_bytes <= inverted.config.hard_limit_bytes);
1039        assert!(inverted.config.hard_limit_bytes <= inverted.config.emergency_limit_bytes);
1040    }
1041
1042    // ---- MemoryBudget ----
1043
1044    #[test]
1045    fn memory_below_soft_no_alert() {
1046        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1047        assert!(mb.check(1024).is_none());
1048        assert_eq!(mb.current_bytes(), 1024);
1049    }
1050
1051    #[test]
1052    fn memory_at_soft_limit_warns() {
1053        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1054        let alert = mb.check(8 * 1024 * 1024).unwrap();
1055        assert_eq!(alert.kind, GuardrailKind::Memory);
1056        assert_eq!(alert.severity, AlertSeverity::Warning);
1057        assert_eq!(alert.recommended_level, DegradationLevel::SimpleBorders);
1058    }
1059
1060    #[test]
1061    fn memory_at_hard_limit_critical() {
1062        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1063        let alert = mb.check(16 * 1024 * 1024).unwrap();
1064        assert_eq!(alert.severity, AlertSeverity::Critical);
1065        assert_eq!(alert.recommended_level, DegradationLevel::Skeleton);
1066    }
1067
1068    #[test]
1069    fn memory_at_emergency_limit() {
1070        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1071        let alert = mb.check(32 * 1024 * 1024).unwrap();
1072        assert_eq!(alert.severity, AlertSeverity::Emergency);
1073        assert_eq!(alert.recommended_level, DegradationLevel::SkipFrame);
1074    }
1075
1076    #[test]
1077    fn memory_peak_tracking() {
1078        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1079        mb.check(1000);
1080        mb.check(5000);
1081        mb.check(3000);
1082        assert_eq!(mb.peak_bytes(), 5000);
1083        assert_eq!(mb.current_bytes(), 3000);
1084    }
1085
1086    #[test]
1087    fn memory_violation_counts() {
1088        let config = MemoryBudgetConfig {
1089            soft_limit_bytes: 100,
1090            hard_limit_bytes: 200,
1091            emergency_limit_bytes: 300,
1092        };
1093        let mut mb = MemoryBudget::new(config);
1094        mb.check(50); // no violation
1095        mb.check(150); // soft
1096        mb.check(150); // soft again
1097        mb.check(250); // hard
1098        mb.check(350); // emergency — its own tier, NOT a hard violation
1099        assert_eq!(mb.soft_violations(), 2);
1100        assert_eq!(mb.hard_violations(), 1);
1101        assert_eq!(
1102            mb.emergency_violations(),
1103            1,
1104            "emergency shedding must be counted separately from hard hits (bd-1za0z F5)"
1105        );
1106    }
1107
1108    #[test]
1109    fn memory_usage_fraction() {
1110        let config = MemoryBudgetConfig {
1111            soft_limit_bytes: 1000,
1112            hard_limit_bytes: 2000,
1113            emergency_limit_bytes: 3000,
1114        };
1115        let mut mb = MemoryBudget::new(config);
1116        mb.check(500);
1117        assert!((mb.usage_fraction() - 0.5).abs() < f64::EPSILON);
1118    }
1119
1120    #[test]
1121    fn memory_usage_fraction_zero_limit() {
1122        // The constructor normalizes zero limits to defaults (an all-zero
1123        // config used to classify every frame Emergency), so a zero-limit
1124        // budget is no longer constructible via new(); 100 bytes against
1125        // the default 8 MiB soft limit is a tiny fraction.
1126        let config = MemoryBudgetConfig {
1127            soft_limit_bytes: 0,
1128            hard_limit_bytes: 0,
1129            emergency_limit_bytes: 0,
1130        };
1131        let mut mb = MemoryBudget::new(config);
1132        mb.check(100);
1133        assert!(mb.usage_fraction() > 0.0);
1134        assert!(mb.usage_fraction() < 0.001);
1135    }
1136
1137    #[test]
1138    fn memory_reset_clears_state() {
1139        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
1140        mb.check(10 * 1024 * 1024); // soft violation
1141        assert!(mb.soft_violations() > 0);
1142        mb.reset();
1143        assert_eq!(mb.peak_bytes(), 0);
1144        assert_eq!(mb.current_bytes(), 0);
1145        assert_eq!(mb.soft_violations(), 0);
1146        assert_eq!(mb.hard_violations(), 0);
1147    }
1148
1149    #[test]
1150    fn memory_config_accessors() {
1151        let config = MemoryBudgetConfig::small();
1152        let mb = MemoryBudget::new(config);
1153        assert_eq!(mb.config().soft_limit_bytes, 2 * 1024 * 1024);
1154    }
1155
1156    // ---- QueueGuardrails ----
1157
1158    #[test]
1159    fn queue_below_warn_no_alert() {
1160        let mut qg = QueueGuardrails::new(QueueConfig::default());
1161        let (alert, action) = qg.check(1);
1162        assert!(alert.is_none());
1163        assert_eq!(action, QueueAction::None);
1164    }
1165
1166    #[test]
1167    fn queue_at_warn_depth() {
1168        let mut qg = QueueGuardrails::new(QueueConfig::default());
1169        let (alert, action) = qg.check(3);
1170        assert_eq!(alert.unwrap().severity, AlertSeverity::Warning);
1171        assert_eq!(action, QueueAction::None); // warning only, no action
1172    }
1173
1174    #[test]
1175    fn queue_at_max_depth_drop_oldest() {
1176        let config = QueueConfig {
1177            drop_policy: QueueDropPolicy::DropOldest,
1178            ..QueueConfig::default()
1179        };
1180        let mut qg = QueueGuardrails::new(config);
1181        let (alert, action) = qg.check(8);
1182        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
1183        assert!(action.drops_frames());
1184    }
1185
1186    #[test]
1187    fn queue_at_max_depth_drop_newest() {
1188        let config = QueueConfig {
1189            drop_policy: QueueDropPolicy::DropNewest,
1190            ..QueueConfig::default()
1191        };
1192        let mut qg = QueueGuardrails::new(config);
1193        let (alert, action) = qg.check(8);
1194        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
1195        assert_eq!(action, QueueAction::DropNewest(5));
1196    }
1197
1198    #[test]
1199    fn queue_at_max_depth_backpressure() {
1200        let config = QueueConfig {
1201            drop_policy: QueueDropPolicy::Backpressure,
1202            ..QueueConfig::default()
1203        };
1204        let mut qg = QueueGuardrails::new(config);
1205        let (alert, action) = qg.check(8);
1206        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
1207        assert_eq!(action, QueueAction::Backpressure);
1208    }
1209
1210    #[test]
1211    fn queue_emergency_drops_to_latest() {
1212        let mut qg = QueueGuardrails::new(QueueConfig::default());
1213        let (alert, action) = qg.check(16);
1214        assert_eq!(alert.unwrap().severity, AlertSeverity::Emergency);
1215        // DropOldest at emergency should keep only 1 frame
1216        assert_eq!(action, QueueAction::DropOldest(15));
1217    }
1218
1219    #[test]
1220    fn queue_peak_tracking() {
1221        let mut qg = QueueGuardrails::new(QueueConfig::default());
1222        qg.check(2);
1223        qg.check(5);
1224        qg.check(1);
1225        assert_eq!(qg.peak_depth(), 5);
1226        assert_eq!(qg.current_depth(), 1);
1227    }
1228
1229    #[test]
1230    fn queue_drop_counting() {
1231        let mut qg = QueueGuardrails::new(QueueConfig::default());
1232        qg.check(8); // triggers drop
1233        assert!(qg.total_drops() > 0);
1234    }
1235
1236    #[test]
1237    fn queue_backpressure_counting() {
1238        let config = QueueConfig::strict();
1239        let mut qg = QueueGuardrails::new(config);
1240        qg.check(4); // max_depth for strict
1241        assert!(qg.total_backpressure_events() > 0);
1242    }
1243
1244    #[test]
1245    fn queue_reset_clears_state() {
1246        let mut qg = QueueGuardrails::new(QueueConfig::default());
1247        qg.check(10);
1248        qg.reset();
1249        assert_eq!(qg.peak_depth(), 0);
1250        assert_eq!(qg.current_depth(), 0);
1251        assert_eq!(qg.total_drops(), 0);
1252    }
1253
1254    #[test]
1255    fn queue_config_accessors() {
1256        let config = QueueConfig::relaxed();
1257        let qg = QueueGuardrails::new(config);
1258        assert_eq!(qg.config().max_depth, 16);
1259    }
1260
1261    /// CONTRACT (bd-1za0z): malformed threshold ordering is normalized at
1262    /// construction — warn <= max <= emergency, warn floored at 1.
1263    #[test]
1264    fn queue_config_normalized_at_construction() {
1265        let config = QueueConfig {
1266            warn_depth: 10,
1267            max_depth: 8,
1268            emergency_depth: 6,
1269            drop_policy: QueueDropPolicy::DropOldest,
1270        };
1271        let qg = QueueGuardrails::new(config);
1272        let cfg = qg.config();
1273        assert_eq!(cfg.warn_depth, 10);
1274        assert_eq!(cfg.max_depth, 10, "max must be raised to warn");
1275        assert_eq!(cfg.emergency_depth, 10, "emergency must be raised to max");
1276
1277        let zeroed = QueueGuardrails::new(QueueConfig {
1278            warn_depth: 0,
1279            ..QueueConfig::default()
1280        });
1281        assert_eq!(
1282            zeroed.config().warn_depth,
1283            1,
1284            "warn_depth 0 would flag an idle queue"
1285        );
1286    }
1287
1288    /// CONTRACT (bd-1za0z): collapsed thresholds (warn == max) must never
1289    /// produce a zero-excess Drop action; the critical alert still fires.
1290    #[test]
1291    fn queue_collapsed_thresholds_yield_noop_action_not_zero_drop() {
1292        let config = QueueConfig {
1293            warn_depth: 8,
1294            max_depth: 8,
1295            emergency_depth: 16,
1296            drop_policy: QueueDropPolicy::DropOldest,
1297        };
1298        let mut qg = QueueGuardrails::new(config);
1299        let (alert, action) = qg.check(8);
1300        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
1301        assert_eq!(
1302            action,
1303            QueueAction::None,
1304            "excess 0 must not be reported as a real drop action"
1305        );
1306        assert_eq!(qg.total_drops(), 0, "no-op action must not count drops");
1307    }
1308
1309    /// CONTRACT (bd-1za0z): DropNewest at emergency keeps the oldest frame
1310    /// (drops the newest excess) — policy-relative semantics, now documented
1311    /// on the config field.
1312    #[test]
1313    fn queue_emergency_drop_newest_keeps_oldest() {
1314        let config = QueueConfig {
1315            drop_policy: QueueDropPolicy::DropNewest,
1316            ..QueueConfig::default()
1317        };
1318        let mut qg = QueueGuardrails::new(config);
1319        let (alert, action) = qg.check(16);
1320        assert_eq!(alert.unwrap().severity, AlertSeverity::Emergency);
1321        assert_eq!(action, QueueAction::DropNewest(15));
1322    }
1323
1324    // ---- QueueAction ----
1325
1326    #[test]
1327    fn queue_action_drops_frames() {
1328        assert!(!QueueAction::None.drops_frames());
1329        assert!(QueueAction::DropOldest(3).drops_frames());
1330        assert!(QueueAction::DropNewest(1).drops_frames());
1331        assert!(!QueueAction::Backpressure.drops_frames());
1332    }
1333
1334    // ---- FrameGuardrails ----
1335
1336    #[test]
1337    fn guardrails_clear_when_healthy() {
1338        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1339        let v = g.check_frame(1024, 0);
1340        assert!(v.is_clear());
1341        assert_eq!(v.recommended_level, DegradationLevel::Full);
1342        assert_eq!(v.queue_action, QueueAction::None);
1343    }
1344
1345    #[test]
1346    fn guardrails_memory_alert_propagates() {
1347        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1348        let v = g.check_frame(8 * 1024 * 1024, 0);
1349        assert!(!v.is_clear());
1350        assert_eq!(v.alerts.len(), 1);
1351        assert_eq!(v.alerts[0].kind, GuardrailKind::Memory);
1352        assert!(v.should_degrade());
1353        assert!(!v.should_drop_frame());
1354    }
1355
1356    #[test]
1357    fn guardrails_queue_alert_propagates() {
1358        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1359        let v = g.check_frame(0, 8);
1360        assert!(!v.is_clear());
1361        assert!(v.alerts.iter().any(|a| a.kind == GuardrailKind::QueueDepth));
1362    }
1363
1364    #[test]
1365    fn guardrails_both_alerts_combine() {
1366        let config = GuardrailsConfig {
1367            memory: MemoryBudgetConfig {
1368                soft_limit_bytes: 100,
1369                hard_limit_bytes: 200,
1370                emergency_limit_bytes: 300,
1371            },
1372            queue: QueueConfig {
1373                warn_depth: 1,
1374                max_depth: 2,
1375                emergency_depth: 3,
1376                drop_policy: QueueDropPolicy::DropOldest,
1377            },
1378            ..Default::default()
1379        };
1380        let mut g = FrameGuardrails::new(config);
1381        let v = g.check_frame(150, 2);
1382        assert_eq!(v.alerts.len(), 2);
1383        // Should use the most aggressive recommendation
1384        assert!(v.recommended_level >= DegradationLevel::SimpleBorders);
1385    }
1386
1387    #[test]
1388    fn guardrails_emergency_recommends_skip() {
1389        let config = GuardrailsConfig {
1390            memory: MemoryBudgetConfig {
1391                soft_limit_bytes: 100,
1392                hard_limit_bytes: 200,
1393                emergency_limit_bytes: 300,
1394            },
1395            queue: QueueConfig::default(),
1396            ..Default::default()
1397        };
1398        let mut g = FrameGuardrails::new(config);
1399        let v = g.check_frame(300, 0);
1400        assert!(v.should_drop_frame());
1401    }
1402
1403    #[test]
1404    fn guardrails_frame_counting() {
1405        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1406        g.check_frame(0, 0);
1407        g.check_frame(0, 0);
1408        g.check_frame(8 * 1024 * 1024, 0); // triggers alert
1409        assert_eq!(g.frames_checked(), 3);
1410        assert_eq!(g.frames_with_alerts(), 1);
1411    }
1412
1413    #[test]
1414    fn guardrails_alert_rate() {
1415        let config = GuardrailsConfig {
1416            memory: MemoryBudgetConfig {
1417                soft_limit_bytes: 100,
1418                hard_limit_bytes: 200,
1419                emergency_limit_bytes: 300,
1420            },
1421            queue: QueueConfig::default(),
1422            ..Default::default()
1423        };
1424        let mut g = FrameGuardrails::new(config);
1425        g.check_frame(50, 0); // clear
1426        g.check_frame(150, 0); // alert
1427        g.check_frame(50, 0); // clear
1428        g.check_frame(150, 0); // alert
1429        assert!((g.alert_rate() - 0.5).abs() < f64::EPSILON);
1430    }
1431
1432    #[test]
1433    fn guardrails_alert_rate_zero_frames() {
1434        let g = FrameGuardrails::new(GuardrailsConfig::default());
1435        assert!((g.alert_rate() - 0.0).abs() < f64::EPSILON);
1436    }
1437
1438    #[test]
1439    fn guardrails_snapshot_jsonl() {
1440        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1441        g.check_frame(1024, 1);
1442        let snap = g.snapshot();
1443        let line = snap.to_jsonl();
1444        assert!(line.starts_with('{'));
1445        assert!(line.ends_with('}'));
1446        assert!(line.contains("\"memory_bytes\":1024"));
1447        assert!(line.contains("\"queue_depth\":1"));
1448        assert!(line.contains("\"leak_e_value\":1"));
1449        assert!(line.contains("\"leak_cusum_upper\":0"));
1450        assert!(line.contains("\"leak_mean_bytes\":1024"));
1451        assert!(line.contains("\"leak_alert\":false"));
1452    }
1453
1454    #[test]
1455    fn guardrails_reset_clears_all() {
1456        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
1457        g.check_frame(8 * 1024 * 1024, 5);
1458        g.reset();
1459        assert_eq!(g.frames_checked(), 0);
1460        assert_eq!(g.frames_with_alerts(), 0);
1461        assert_eq!(g.memory().peak_bytes(), 0);
1462        assert_eq!(g.queue().peak_depth(), 0);
1463    }
1464
1465    #[test]
1466    fn guardrails_subsystem_access() {
1467        let g = FrameGuardrails::new(GuardrailsConfig::default());
1468        let _ = g.memory().config();
1469        let _ = g.queue().config();
1470    }
1471
1472    // ---- GuardrailVerdict ----
1473
1474    #[test]
1475    fn verdict_max_severity_none_when_clear() {
1476        let v = GuardrailVerdict {
1477            alerts: vec![],
1478            queue_action: QueueAction::None,
1479            recommended_level: DegradationLevel::Full,
1480            leak_alert: None,
1481        };
1482        assert!(v.max_severity().is_none());
1483        assert!(v.is_clear());
1484    }
1485
1486    #[test]
1487    fn verdict_max_severity_picks_highest() {
1488        let v = GuardrailVerdict {
1489            alerts: vec![
1490                GuardrailAlert {
1491                    kind: GuardrailKind::Memory,
1492                    severity: AlertSeverity::Warning,
1493                    recommended_level: DegradationLevel::SimpleBorders,
1494                },
1495                GuardrailAlert {
1496                    kind: GuardrailKind::QueueDepth,
1497                    severity: AlertSeverity::Critical,
1498                    recommended_level: DegradationLevel::EssentialOnly,
1499                },
1500            ],
1501            queue_action: QueueAction::None,
1502            recommended_level: DegradationLevel::EssentialOnly,
1503            leak_alert: None,
1504        };
1505        assert_eq!(v.max_severity(), Some(AlertSeverity::Critical));
1506    }
1507
1508    // ---- AlertSeverity ordering ----
1509
1510    #[test]
1511    fn severity_ordering() {
1512        assert!(AlertSeverity::Warning < AlertSeverity::Critical);
1513        assert!(AlertSeverity::Critical < AlertSeverity::Emergency);
1514    }
1515
1516    // ---- Config presets ----
1517
1518    #[test]
1519    fn memory_config_small_preset() {
1520        let c = MemoryBudgetConfig::small();
1521        assert!(c.soft_limit_bytes < MemoryBudgetConfig::default().soft_limit_bytes);
1522    }
1523
1524    #[test]
1525    fn memory_config_large_preset() {
1526        let c = MemoryBudgetConfig::large();
1527        assert!(c.soft_limit_bytes > MemoryBudgetConfig::default().soft_limit_bytes);
1528    }
1529
1530    #[test]
1531    fn queue_config_strict_preset() {
1532        let c = QueueConfig::strict();
1533        assert_eq!(c.drop_policy, QueueDropPolicy::Backpressure);
1534        assert!(c.max_depth < QueueConfig::default().max_depth);
1535    }
1536
1537    #[test]
1538    fn queue_config_relaxed_preset() {
1539        let c = QueueConfig::relaxed();
1540        assert!(c.max_depth > QueueConfig::default().max_depth);
1541    }
1542
1543    // ---- buffer_memory_bytes ----
1544
1545    #[test]
1546    fn buffer_memory_typical_terminal() {
1547        // 80×24 terminal
1548        assert_eq!(buffer_memory_bytes(80, 24), 80 * 24 * 16);
1549    }
1550
1551    #[test]
1552    fn buffer_memory_zero_dimension() {
1553        assert_eq!(buffer_memory_bytes(0, 24), 0);
1554        assert_eq!(buffer_memory_bytes(80, 0), 0);
1555        assert_eq!(buffer_memory_bytes(0, 0), 0);
1556    }
1557
1558    #[test]
1559    fn buffer_memory_large_terminal() {
1560        // 300×100 terminal
1561        let bytes = buffer_memory_bytes(300, 100);
1562        assert_eq!(bytes, 300 * 100 * 16);
1563        assert_eq!(bytes, 480_000);
1564    }
1565
1566    // ---- QueueDropPolicy Default ----
1567
1568    #[test]
1569    fn queue_drop_policy_default_is_drop_oldest() {
1570        assert_eq!(QueueDropPolicy::default(), QueueDropPolicy::DropOldest);
1571    }
1572
1573    // ---- Determinism ----
1574
1575    #[test]
1576    fn guardrails_deterministic_for_same_inputs() {
1577        let config = GuardrailsConfig::default();
1578        let mut g1 = FrameGuardrails::new(config.clone());
1579        let mut g2 = FrameGuardrails::new(config);
1580
1581        let inputs = [(1024, 0), (8 * 1024 * 1024, 3), (20 * 1024 * 1024, 10)];
1582        for (mem, queue) in inputs {
1583            let v1 = g1.check_frame(mem, queue);
1584            let v2 = g2.check_frame(mem, queue);
1585            assert_eq!(v1.recommended_level, v2.recommended_level);
1586            assert_eq!(v1.alerts.len(), v2.alerts.len());
1587            assert_eq!(v1.queue_action, v2.queue_action);
1588        }
1589    }
1590}