ftui-render 0.9.0

Render kernel: cells, buffers, diffs, and ANSI presentation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
#![forbid(unsafe_code)]

//! Frame guardrails: memory budget, queue depth limits, and unified enforcement.
//!
//! This module complements the time-based [`RenderBudget`](crate::budget::RenderBudget)
//! with three resource guardrails:
//!
//! 1. **Memory budget** — enforces hard/soft limits on total rendering memory
//!    (buffer cells, grapheme pool, arena).
//! 2. **Queue depth** — prevents unbounded frame queuing under sustained load
//!    with configurable drop policies.
//! 3. **Capacity drift** — runs [`AllocLeakDetector`] over retained rendering
//!    capacity without accumulating a per-frame ledger. Upward drift is advisory;
//!    only absolute memory and queue limits recommend degradation or frame drops.
//!
//! A unified [`FrameGuardrails`] facade combines these three guardrails into a
//! single per-frame checkpoint that returns an actionable [`GuardrailVerdict`].
//!
//! # Usage
//!
//! ```
//! use ftui_render::frame_guardrails::{
//!     FrameGuardrails, GuardrailsConfig, MemoryBudgetConfig, QueueConfig,
//! };
//! use ftui_render::budget::FrameBudgetConfig;
//!
//! let config = GuardrailsConfig::default();
//! let mut guardrails = FrameGuardrails::new(config);
//!
//! // Each frame: report current resource usage
//! let verdict = guardrails.check_frame(
//!     1_048_576,  // current memory bytes
//!     2,          // pending frames in queue
//! );
//!
//! if verdict.should_drop_frame() {
//!     // Skip this frame entirely
//! } else if verdict.should_degrade() {
//!     // Render at reduced fidelity
//! }
//! ```

use crate::alloc_budget::{AllocLeakDetector, LeakAlert, LeakDetectorConfig};
use crate::budget::DegradationLevel;

// =========================================================================
// Alerts
// =========================================================================

/// Category of guardrail that triggered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GuardrailKind {
    /// Memory usage exceeded a threshold.
    Memory,
    /// Queue depth exceeded a threshold.
    QueueDepth,
    /// Retained rendering capacity shows sustained upward drift.
    AllocationLeak,
}

/// Severity of a guardrail alert.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AlertSeverity {
    /// Approaching limit — consider reducing work.
    Warning,
    /// At or near limit — degrade immediately.
    Critical,
    /// Past hard limit — drop frames or backpressure.
    Emergency,
}

/// A single guardrail alert.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GuardrailAlert {
    /// Which guardrail triggered.
    pub kind: GuardrailKind,
    /// How severe the overage is.
    pub severity: AlertSeverity,
    /// Recommended minimum degradation level.
    pub recommended_level: DegradationLevel,
}

// =========================================================================
// Memory budget
// =========================================================================

/// Configuration for memory budget enforcement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemoryBudgetConfig {
    /// Soft limit in bytes — triggers `Warning` alert and suggests degradation.
    /// Default: 8 MiB (enough for ~524K cells at 16 bytes each, i.e. ~540×970).
    pub soft_limit_bytes: usize,
    /// Hard limit in bytes — triggers `Critical` alert with aggressive degradation.
    /// Default: 16 MiB.
    pub hard_limit_bytes: usize,
    /// Emergency limit in bytes — triggers `Emergency` alert, drop frames.
    /// Default: 32 MiB.
    pub emergency_limit_bytes: usize,
}

impl Default for MemoryBudgetConfig {
    fn default() -> Self {
        Self {
            soft_limit_bytes: 8 * 1024 * 1024,
            hard_limit_bytes: 16 * 1024 * 1024,
            emergency_limit_bytes: 32 * 1024 * 1024,
        }
    }
}

impl MemoryBudgetConfig {
    /// Create a config scaled for small terminals (e.g. 80×24).
    #[must_use]
    pub fn small() -> Self {
        Self {
            soft_limit_bytes: 2 * 1024 * 1024,
            hard_limit_bytes: 4 * 1024 * 1024,
            emergency_limit_bytes: 8 * 1024 * 1024,
        }
    }

    /// Create a config scaled for large terminals (e.g. 300×100).
    #[must_use]
    pub fn large() -> Self {
        Self {
            soft_limit_bytes: 32 * 1024 * 1024,
            hard_limit_bytes: 64 * 1024 * 1024,
            emergency_limit_bytes: 128 * 1024 * 1024,
        }
    }

    /// Return a normalized copy with sane, monotone thresholds.
    ///
    /// User-supplied configs (via `ProgramConfig`) can be zero-initialized
    /// or inverted; the classifier uses `>=` comparisons, so an all-zero
    /// config would classify EVERY frame as Emergency (blank screen from
    /// startup) and inverted watermarks silently misclassify. Zero limits
    /// fall back to the defaults; hard/emergency are raised to keep
    /// soft <= hard <= emergency.
    #[must_use]
    pub fn normalized(self) -> Self {
        let defaults = Self::default();
        let soft = if self.soft_limit_bytes == 0 {
            defaults.soft_limit_bytes
        } else {
            self.soft_limit_bytes
        };
        let hard = if self.hard_limit_bytes == 0 {
            defaults.hard_limit_bytes
        } else {
            self.hard_limit_bytes
        }
        .max(soft);
        let emergency = if self.emergency_limit_bytes == 0 {
            defaults.emergency_limit_bytes
        } else {
            self.emergency_limit_bytes
        }
        .max(hard);
        Self {
            soft_limit_bytes: soft,
            hard_limit_bytes: hard,
            emergency_limit_bytes: emergency,
        }
    }
}

/// Memory budget tracker.
///
/// Checks reported memory usage against configured thresholds and produces
/// alerts with recommended degradation levels.
#[derive(Debug, Clone)]
pub struct MemoryBudget {
    config: MemoryBudgetConfig,
    /// Peak memory observed (bytes).
    peak_bytes: usize,
    /// Last reported memory (bytes).
    current_bytes: usize,
    /// Number of frames where soft limit was exceeded.
    soft_violations: u32,
    /// Number of frames where hard limit was exceeded.
    hard_violations: u32,
    /// Number of frames where the emergency limit was exceeded.
    ///
    /// Counted separately from [`Self::hard_violations`]: emergency is a
    /// distinct tier (frame shed + arena rebuild), and conflating it with
    /// hard-limit hits made the snapshot unable to distinguish "hard limit
    /// pressure" from "emergency shedding" (bd-1za0z F5).
    emergency_violations: u32,
}

impl MemoryBudget {
    /// Create a new memory budget with the given configuration.
    #[must_use]
    pub fn new(config: MemoryBudgetConfig) -> Self {
        Self {
            // Normalize at the boundary: the classifier's >= comparisons
            // must never see zero or inverted thresholds (see
            // MemoryBudgetConfig::normalized).
            config: config.normalized(),
            peak_bytes: 0,
            current_bytes: 0,
            soft_violations: 0,
            hard_violations: 0,
            emergency_violations: 0,
        }
    }

    /// Report current memory usage and get an alert if thresholds are exceeded.
    pub fn check(&mut self, current_bytes: usize) -> Option<GuardrailAlert> {
        self.current_bytes = current_bytes;
        if current_bytes > self.peak_bytes {
            self.peak_bytes = current_bytes;
        }

        if current_bytes >= self.config.emergency_limit_bytes {
            // Emergency is its OWN tier: counting it as a hard violation
            // conflated "hard limit pressure" with "emergency shedding" in
            // the snapshot (bd-1za0z F5).
            self.emergency_violations = self.emergency_violations.saturating_add(1);
            Some(GuardrailAlert {
                kind: GuardrailKind::Memory,
                severity: AlertSeverity::Emergency,
                recommended_level: DegradationLevel::SkipFrame,
            })
        } else if current_bytes >= self.config.hard_limit_bytes {
            self.hard_violations = self.hard_violations.saturating_add(1);
            Some(GuardrailAlert {
                kind: GuardrailKind::Memory,
                severity: AlertSeverity::Critical,
                recommended_level: DegradationLevel::Skeleton,
            })
        } else if current_bytes >= self.config.soft_limit_bytes {
            self.soft_violations = self.soft_violations.saturating_add(1);
            Some(GuardrailAlert {
                kind: GuardrailKind::Memory,
                severity: AlertSeverity::Warning,
                recommended_level: DegradationLevel::SimpleBorders,
            })
        } else {
            None
        }
    }

    /// Current memory usage in bytes.
    #[inline]
    #[must_use]
    pub fn current_bytes(&self) -> usize {
        self.current_bytes
    }

    /// Peak memory usage observed since creation or last reset.
    #[inline]
    #[must_use]
    pub fn peak_bytes(&self) -> usize {
        self.peak_bytes
    }

    /// Fraction of soft limit currently used (0.0 = empty, 1.0 = at limit).
    #[inline]
    #[must_use]
    pub fn usage_fraction(&self) -> f64 {
        if self.config.soft_limit_bytes == 0 {
            return 1.0;
        }
        self.current_bytes as f64 / self.config.soft_limit_bytes as f64
    }

    /// Number of frames where the soft limit was exceeded.
    #[inline]
    #[must_use]
    pub fn soft_violations(&self) -> u32 {
        self.soft_violations
    }

    /// Number of frames where the hard limit was exceeded.
    #[inline]
    #[must_use]
    pub fn hard_violations(&self) -> u32 {
        self.hard_violations
    }

    /// Number of frames where the emergency limit was exceeded.
    #[inline]
    #[must_use]
    pub fn emergency_violations(&self) -> u32 {
        self.emergency_violations
    }

    /// Get a reference to the configuration.
    #[inline]
    #[must_use]
    pub fn config(&self) -> &MemoryBudgetConfig {
        &self.config
    }

    /// Reset tracking state (preserves config).
    pub fn reset(&mut self) {
        self.peak_bytes = 0;
        self.current_bytes = 0;
        self.soft_violations = 0;
        self.hard_violations = 0;
        self.emergency_violations = 0;
    }
}

// =========================================================================
// Queue depth guardrails
// =========================================================================

/// Policy for handling frames when queue is full.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum QueueDropPolicy {
    /// Drop the oldest pending frame (display freshest content).
    #[default]
    DropOldest,
    /// Drop the newest frame (preserve sequential ordering).
    DropNewest,
    /// Signal backpressure to the producer (don't drop, slow input).
    Backpressure,
}

/// Configuration for frame queue depth limits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueueConfig {
    /// Maximum pending frames before warning.
    /// Default: 3.
    pub warn_depth: u32,
    /// Maximum pending frames before critical action.
    /// Default: 8.
    pub max_depth: u32,
    /// Emergency depth — at this depth the queue is drained hard:
    /// `DropOldest` keeps only the latest frame, `DropNewest` keeps only the
    /// oldest, `Backpressure` signals the producer (bd-1za0z: the old
    /// "drop all but latest" wording described only the default policy).
    /// Default: 16.
    pub emergency_depth: u32,
    pub drop_policy: QueueDropPolicy,
}

impl Default for QueueConfig {
    fn default() -> Self {
        Self {
            warn_depth: 3,
            max_depth: 8,
            emergency_depth: 16,
            drop_policy: QueueDropPolicy::DropOldest,
        }
    }
}

impl QueueConfig {
    /// Strict config: small queue, backpressure policy.
    #[must_use]
    pub fn strict() -> Self {
        Self {
            warn_depth: 2,
            max_depth: 4,
            emergency_depth: 8,
            drop_policy: QueueDropPolicy::Backpressure,
        }
    }

    /// Relaxed config: larger queue, drop oldest.
    #[must_use]
    pub fn relaxed() -> Self {
        Self {
            warn_depth: 8,
            max_depth: 16,
            emergency_depth: 32,
            drop_policy: QueueDropPolicy::DropOldest,
        }
    }
}

/// Queue depth tracker.
///
/// Monitors the number of pending frames and produces alerts when
/// configured thresholds are exceeded.
#[derive(Debug, Clone)]
pub struct QueueGuardrails {
    config: QueueConfig,
    /// Peak queue depth observed.
    peak_depth: u32,
    /// Current queue depth.
    current_depth: u32,
    /// Total frames dropped due to queue overflow.
    total_drops: u64,
    /// Total backpressure events.
    total_backpressure_events: u64,
}

impl QueueGuardrails {
    /// Create a new queue guardrail with the given configuration.
    ///
    /// Thresholds are normalized at construction (same policy as
    /// `MemoryBudgetConfig`): `warn_depth` is clamped to `max_depth` and
    /// `max_depth` to `emergency_depth`. A malformed config like
    /// `warn_depth > max_depth` would otherwise produce zero-excess
    /// `DropOldest(0)` / `DropNewest(0)` actions at the critical tier —
    /// alerts that look actionable but do nothing (bd-1za0z).
    #[must_use]
    pub fn new(config: QueueConfig) -> Self {
        // Floor warn at 1: warn_depth 0 would flag an idle queue. Ordering
        // is then enforced upward so every threshold tier is reachable.
        let warn_depth = config.warn_depth.max(1);
        let max_depth = config.max_depth.max(warn_depth);
        let emergency_depth = config.emergency_depth.max(max_depth);
        Self {
            config: QueueConfig {
                warn_depth,
                max_depth,
                emergency_depth,
                drop_policy: config.drop_policy,
            },
            peak_depth: 0,
            current_depth: 0,
            total_drops: 0,
            total_backpressure_events: 0,
        }
    }

    /// Report current queue depth and get an alert if thresholds are exceeded.
    ///
    /// Returns `(alert, action)` where action indicates what the runtime should
    /// do about queued frames (if anything).
    pub fn check(&mut self, current_depth: u32) -> (Option<GuardrailAlert>, QueueAction) {
        self.current_depth = current_depth;
        if current_depth > self.peak_depth {
            self.peak_depth = current_depth;
        }

        if current_depth >= self.config.emergency_depth {
            let action = match self.config.drop_policy {
                QueueDropPolicy::DropOldest => {
                    let excess = current_depth - 1; // DropOldest: keep only the latest
                    self.total_drops = self.total_drops.saturating_add(excess as u64);
                    QueueAction::DropOldest(excess)
                }
                QueueDropPolicy::DropNewest => {
                    let excess = current_depth - 1; // DropNewest: keep only the oldest
                    self.total_drops = self.total_drops.saturating_add(excess as u64);
                    QueueAction::DropNewest(excess)
                }
                QueueDropPolicy::Backpressure => {
                    self.total_backpressure_events =
                        self.total_backpressure_events.saturating_add(1);
                    QueueAction::Backpressure
                }
            };
            (
                Some(GuardrailAlert {
                    kind: GuardrailKind::QueueDepth,
                    severity: AlertSeverity::Emergency,
                    recommended_level: DegradationLevel::SkipFrame,
                }),
                action,
            )
        } else if current_depth >= self.config.max_depth {
            let action = match self.config.drop_policy {
                QueueDropPolicy::DropOldest => {
                    let excess = current_depth.saturating_sub(self.config.warn_depth);
                    if excess == 0 {
                        // Thresholds collapsed (e.g. warn == max): the
                        // critical alert still fires, but there is nothing
                        // to drop — never emit a no-op Drop(excess=0).
                        QueueAction::None
                    } else {
                        self.total_drops = self.total_drops.saturating_add(u64::from(excess));
                        QueueAction::DropOldest(excess)
                    }
                }
                QueueDropPolicy::DropNewest => {
                    let excess = current_depth.saturating_sub(self.config.warn_depth);
                    if excess == 0 {
                        QueueAction::None
                    } else {
                        self.total_drops = self.total_drops.saturating_add(u64::from(excess));
                        QueueAction::DropNewest(excess)
                    }
                }
                QueueDropPolicy::Backpressure => {
                    self.total_backpressure_events =
                        self.total_backpressure_events.saturating_add(1);
                    QueueAction::Backpressure
                }
            };
            (
                Some(GuardrailAlert {
                    kind: GuardrailKind::QueueDepth,
                    severity: AlertSeverity::Critical,
                    recommended_level: DegradationLevel::EssentialOnly,
                }),
                action,
            )
        } else if current_depth >= self.config.warn_depth {
            (
                Some(GuardrailAlert {
                    kind: GuardrailKind::QueueDepth,
                    severity: AlertSeverity::Warning,
                    recommended_level: DegradationLevel::SimpleBorders,
                }),
                QueueAction::None,
            )
        } else {
            (None, QueueAction::None)
        }
    }

    /// Current queue depth.
    #[inline]
    #[must_use]
    pub fn current_depth(&self) -> u32 {
        self.current_depth
    }

    /// Peak queue depth observed.
    #[inline]
    #[must_use]
    pub fn peak_depth(&self) -> u32 {
        self.peak_depth
    }

    /// Total frames dropped due to queue overflow.
    #[inline]
    #[must_use]
    pub fn total_drops(&self) -> u64 {
        self.total_drops
    }

    /// Total backpressure events.
    #[inline]
    #[must_use]
    pub fn total_backpressure_events(&self) -> u64 {
        self.total_backpressure_events
    }

    /// Get a reference to the configuration.
    #[inline]
    #[must_use]
    pub fn config(&self) -> &QueueConfig {
        &self.config
    }

    /// Reset tracking state (preserves config).
    pub fn reset(&mut self) {
        self.peak_depth = 0;
        self.current_depth = 0;
        self.total_drops = 0;
        self.total_backpressure_events = 0;
    }
}

/// Action the runtime should take in response to queue depth.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueueAction {
    /// No action needed.
    None,
    /// Drop the N oldest pending frames.
    DropOldest(u32),
    /// Drop the N newest pending frames.
    DropNewest(u32),
    /// Signal backpressure to the input source.
    Backpressure,
}

impl QueueAction {
    /// Whether this action requires dropping any frames.
    #[inline]
    #[must_use]
    pub fn drops_frames(self) -> bool {
        matches!(self, Self::DropOldest(_) | Self::DropNewest(_))
    }
}

// =========================================================================
// Unified guardrails
// =========================================================================

/// Configuration for the unified frame guardrails.
#[derive(Debug, Clone)]
pub struct GuardrailsConfig {
    /// Memory budget configuration.
    pub memory: MemoryBudgetConfig,
    /// Queue depth configuration.
    pub queue: QueueConfig,
    /// Optional retained-capacity drift detector; enabled by default.
    pub leak: Option<LeakDetectorConfig>,
}

impl Default for GuardrailsConfig {
    fn default() -> Self {
        Self {
            memory: MemoryBudgetConfig::default(),
            queue: QueueConfig::default(),
            leak: Some(LeakDetectorConfig::default()),
        }
    }
}

/// Verdict from a guardrail check, combining all subsystem results.
#[derive(Debug, Clone)]
pub struct GuardrailVerdict {
    /// Alerts from all guardrails that fired (may be empty).
    pub alerts: Vec<GuardrailAlert>,
    /// Queue action recommended by queue guardrails.
    pub queue_action: QueueAction,
    /// The most aggressive degradation level recommended across all alerts.
    pub recommended_level: DegradationLevel,
    /// Upward drift evidence, present only when the detector fires.
    pub leak_alert: Option<LeakAlert>,
}

impl GuardrailVerdict {
    /// Whether any guardrail recommends dropping the current frame.
    #[inline]
    #[must_use]
    pub fn should_drop_frame(&self) -> bool {
        self.recommended_level >= DegradationLevel::SkipFrame
    }

    /// Whether any guardrail recommends degradation (but not frame skip).
    #[inline]
    #[must_use]
    pub fn should_degrade(&self) -> bool {
        self.recommended_level > DegradationLevel::Full
            && self.recommended_level < DegradationLevel::SkipFrame
    }

    /// Whether all guardrails are satisfied (no alerts).
    #[inline]
    #[must_use]
    pub fn is_clear(&self) -> bool {
        self.alerts.is_empty()
    }

    /// The highest severity among all alerts, or `None` if clear.
    #[must_use]
    pub fn max_severity(&self) -> Option<AlertSeverity> {
        self.alerts.iter().map(|a| a.severity).max()
    }
}

/// Unified memory budget, queue depth limits, and retained-capacity drift detection.
///
/// Call [`check_frame`](Self::check_frame) once per frame with current resource
/// usage. The returned [`GuardrailVerdict`] tells you what (if anything) to do.
#[derive(Debug, Clone)]
pub struct FrameGuardrails {
    memory: MemoryBudget,
    queue: QueueGuardrails,
    leak: Option<AllocLeakDetector>,
    leak_alert: bool,
    /// Total frames checked.
    frames_checked: u64,
    /// Total frames where at least one alert fired.
    frames_with_alerts: u64,
}

impl FrameGuardrails {
    /// Create a new unified guardrails instance.
    #[must_use]
    pub fn new(config: GuardrailsConfig) -> Self {
        Self {
            memory: MemoryBudget::new(config.memory),
            queue: QueueGuardrails::new(config.queue),
            leak: config.leak.map(AllocLeakDetector::new),
            leak_alert: false,
            frames_checked: 0,
            frames_with_alerts: 0,
        }
    }

    /// Check all guardrails for the current frame.
    ///
    /// `memory_bytes`: retained rendering capacity (buffer + pools + arena),
    /// not live allocator usage. A downward shift alone is not a leak.
    /// `queue_depth`: number of pending frames waiting to be rendered.
    pub fn check_frame(&mut self, memory_bytes: usize, queue_depth: u32) -> GuardrailVerdict {
        self.frames_checked = self.frames_checked.saturating_add(1);

        let mut alerts = Vec::new();
        let mut max_level = DegradationLevel::Full;

        // Memory check
        if let Some(alert) = self.memory.check(memory_bytes) {
            if alert.recommended_level > max_level {
                max_level = alert.recommended_level;
            }
            alerts.push(alert);
        }

        // Queue check
        let (queue_alert, queue_action) = self.queue.check(queue_depth);
        if let Some(alert) = queue_alert {
            if alert.recommended_level > max_level {
                max_level = alert.recommended_level;
            }
            alerts.push(alert);
        }

        let leak_alert = self.leak.as_mut().and_then(|detector| {
            let mut alert = detector.observe_unrecorded(memory_bytes as f64);
            // The general detector is two-sided; releasing capacity is not
            // an allocation leak. Keep only its upward CUSUM/e-process signal.
            alert.cusum_triggered = alert.cusum_upper > detector.cusum_threshold();
            alert.triggered = alert.cusum_triggered || alert.eprocess_triggered;
            alert.triggered.then_some(alert)
        });
        self.leak_alert = leak_alert.is_some();
        if self.leak_alert {
            // Suspected growth is diagnostic, not proof of memory pressure.
            // Only the independent absolute budget may degrade or drop frames.
            alerts.push(GuardrailAlert {
                kind: GuardrailKind::AllocationLeak,
                severity: AlertSeverity::Warning,
                recommended_level: DegradationLevel::Full,
            });
        }

        if !alerts.is_empty() {
            self.frames_with_alerts = self.frames_with_alerts.saturating_add(1);
        }

        GuardrailVerdict {
            alerts,
            queue_action,
            recommended_level: max_level,
            leak_alert,
        }
    }

    /// Access the memory budget subsystem.
    #[inline]
    #[must_use]
    pub fn memory(&self) -> &MemoryBudget {
        &self.memory
    }

    /// Access the queue guardrails subsystem.
    #[inline]
    #[must_use]
    pub fn queue(&self) -> &QueueGuardrails {
        &self.queue
    }

    /// Total frames checked.
    #[inline]
    #[must_use]
    pub fn frames_checked(&self) -> u64 {
        self.frames_checked
    }

    /// Total frames where at least one alert fired.
    #[inline]
    #[must_use]
    pub fn frames_with_alerts(&self) -> u64 {
        self.frames_with_alerts
    }

    /// Fraction of frames that triggered alerts (0.0–1.0).
    #[inline]
    #[must_use]
    pub fn alert_rate(&self) -> f64 {
        if self.frames_checked == 0 {
            return 0.0;
        }
        self.frames_with_alerts as f64 / self.frames_checked as f64
    }

    /// Capture a diagnostic snapshot.
    #[must_use]
    pub fn snapshot(&self) -> GuardrailSnapshot {
        GuardrailSnapshot {
            memory_bytes: self.memory.current_bytes(),
            memory_peak_bytes: self.memory.peak_bytes(),
            memory_usage_fraction: self.memory.usage_fraction(),
            memory_soft_violations: self.memory.soft_violations(),
            memory_hard_violations: self.memory.hard_violations(),
            memory_emergency_violations: self.memory.emergency_violations(),
            queue_depth: self.queue.current_depth(),
            queue_peak_depth: self.queue.peak_depth(),
            queue_total_drops: self.queue.total_drops(),
            queue_total_backpressure: self.queue.total_backpressure_events(),
            frames_checked: self.frames_checked,
            frames_with_alerts: self.frames_with_alerts,
            leak_e_value: self.leak.as_ref().map_or(1.0, AllocLeakDetector::e_value),
            leak_cusum_upper: self
                .leak
                .as_ref()
                .map_or(0.0, AllocLeakDetector::cusum_upper),
            leak_mean_bytes: self.leak.as_ref().map_or(0.0, AllocLeakDetector::mean),
            leak_alert: self.leak_alert,
        }
    }

    /// Start a new capacity baseline after an intentional trim or emergency shed.
    pub fn reset_leak_detector(&mut self) {
        if let Some(detector) = self.leak.as_mut() {
            detector.reset();
        }
        self.leak_alert = false;
    }

    /// Reset all tracking state (preserves configs).
    pub fn reset(&mut self) {
        self.memory.reset();
        self.queue.reset();
        self.reset_leak_detector();
        self.frames_checked = 0;
        self.frames_with_alerts = 0;
    }
}

/// Diagnostic snapshot of guardrail state.
///
/// All fields are `Copy` — no allocations. Suitable for structured logging
/// or debug overlay.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GuardrailSnapshot {
    /// Current e-process wealth (1 when disabled or reset).
    pub leak_e_value: f64,
    /// Upward CUSUM statistic (0 when disabled or reset).
    pub leak_cusum_upper: f64,
    /// Mean retained rendering capacity in bytes.
    pub leak_mean_bytes: f64,
    /// Whether the most recent frame indicated upward capacity drift.
    pub leak_alert: bool,
    /// Current memory usage in bytes.
    pub memory_bytes: usize,
    /// Peak memory usage in bytes.
    pub memory_peak_bytes: usize,
    /// Fraction of soft memory limit used.
    pub memory_usage_fraction: f64,
    /// Frames exceeding soft memory limit.
    pub memory_soft_violations: u32,
    /// Frames exceeding hard memory limit.
    pub memory_hard_violations: u32,
    /// Frames exceeding the emergency memory limit (frame shed + arena
    /// rebuild). Kept distinct from [`Self::memory_hard_violations`]
    /// (bd-1za0z F5).
    pub memory_emergency_violations: u32,
    /// Current queue depth.
    pub queue_depth: u32,
    /// Peak queue depth.
    pub queue_peak_depth: u32,
    /// Total frames dropped from queue.
    pub queue_total_drops: u64,
    /// Total backpressure events.
    pub queue_total_backpressure: u64,
    /// Total frames checked.
    pub frames_checked: u64,
    /// Total frames with alerts.
    pub frames_with_alerts: u64,
}

impl GuardrailSnapshot {
    /// Serialize to a JSONL-compatible string.
    pub fn to_jsonl(&self) -> String {
        format!(
            concat!(
                r#"{{"memory_bytes":{},"memory_peak":{},"memory_frac":{:.4},"#,
                r#""mem_soft_violations":{},"mem_hard_violations":{},"mem_emergency_violations":{},"#,
                r#""queue_depth":{},"queue_peak":{},"queue_drops":{},"#,
                r#""queue_backpressure":{},"frames_checked":{},"frames_alerted":{},"#,
                r#""leak_e_value":{:e},"leak_cusum_upper":{},"leak_mean_bytes":{},"leak_alert":{}}}"#,
            ),
            self.memory_bytes,
            self.memory_peak_bytes,
            self.memory_usage_fraction,
            self.memory_soft_violations,
            self.memory_hard_violations,
            self.memory_emergency_violations,
            self.queue_depth,
            self.queue_peak_depth,
            self.queue_total_drops,
            self.queue_total_backpressure,
            self.frames_checked,
            self.frames_with_alerts,
            self.leak_e_value,
            self.leak_cusum_upper,
            self.leak_mean_bytes,
            self.leak_alert,
        )
    }
}

// =========================================================================
// Utility: compute buffer memory
// =========================================================================

/// Size of a single Cell in bytes (compile-time constant).
pub const CELL_SIZE_BYTES: usize = 16;

/// Compute the memory footprint of a buffer with the given dimensions.
///
/// This accounts for the cell array only (not dirty tracking or stack metadata).
#[inline]
#[must_use]
pub fn buffer_memory_bytes(width: u16, height: u16) -> usize {
    width as usize * height as usize * CELL_SIZE_BYTES
}

// =========================================================================
// Tests
// =========================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn guardrails_detect_allocation_drift() {
        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
        for i in 0..200 {
            let bytes = 1024 * 1024 + if i % 2 == 0 { 1024 } else { 0 };
            assert!(g.check_frame(bytes, 0).leak_alert.is_none());
        }
        let mut detected = false;
        for i in 1..=100 {
            let verdict = g.check_frame(1024 * 1024 + i * 64 * 1024, 0);
            if verdict.leak_alert.is_some() {
                detected = true;
                assert!(
                    verdict
                        .alerts
                        .iter()
                        .any(|a| a.kind == GuardrailKind::AllocationLeak)
                );
                assert!(!verdict.is_clear());
                assert!(!verdict.should_degrade());
                assert!(!verdict.should_drop_frame());
                assert!(g.snapshot().leak_alert);
            }
        }
        assert!(detected, "sustained capacity growth must produce evidence");
        assert!(g.leak.as_ref().unwrap().ledger().is_empty());
    }

    #[test]
    fn leak_detector_reset_after_trim_suppresses_false_alert() {
        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
        for _ in 0..200 {
            g.check_frame(1024 * 1024, 0);
        }
        assert!(g.check_frame(2 * 1024 * 1024, 0).leak_alert.is_some());
        let checked = g.frames_checked();
        g.reset_leak_detector();
        assert_eq!(g.frames_checked(), checked);
        assert!(!g.snapshot().leak_alert);
        for _ in 0..200 {
            assert!(g.check_frame(1024, 0).leak_alert.is_none());
        }
    }

    #[test]
    fn capacity_decrease_is_not_a_leak() {
        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
        for _ in 0..200 {
            g.check_frame(1024 * 1024, 0);
        }
        for _ in 0..100 {
            assert!(g.check_frame(1024, 0).leak_alert.is_none());
        }
        assert!(g.leak.as_ref().unwrap().cusum_lower() > 8.0);
    }

    #[test]
    fn disabled_leak_detector_preserves_memory_enforcement() {
        let mut g = FrameGuardrails::new(GuardrailsConfig {
            leak: None,
            ..Default::default()
        });
        for i in 0..200 {
            assert!(g.check_frame(i * 1024, 0).leak_alert.is_none());
        }
        assert!(g.check_frame(32 * 1024 * 1024, 0).should_drop_frame());
        g.reset_leak_detector();
        assert!(!g.snapshot().leak_alert);
    }

    #[test]
    fn sustained_growth_keeps_snapshot_json_finite() {
        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
        for i in 0..4000 {
            let bytes = if i < 200 { 1024 } else { i * 1024 };
            g.check_frame(bytes, 0);
        }
        let snapshot = g.snapshot();
        assert!(snapshot.leak_alert);
        assert_eq!(snapshot.leak_e_value, f64::MAX);
        let json: serde_json::Value = serde_json::from_str(&snapshot.to_jsonl()).unwrap();
        assert!(json["leak_e_value"].as_f64().unwrap().is_finite());
    }

    proptest::proptest! {
        #![proptest_config(proptest::test_runner::Config::with_cases(512))]

        #[test]
        fn proptest_no_alert_on_stationary_series(
            baseline in 4096usize..4 * 1024 * 1024,
            amplitude in 0usize..1024,
            phase in proptest::bool::ANY,
        ) {
            let mut g = FrameGuardrails::new(GuardrailsConfig::default());
            // A bounded, balanced stationary series at different scales and phases.
            // This is not a universal zero-false-positive statistical claim.
            for i in 0..400 {
                let bytes = if (i % 2 == 0) == phase {
                    baseline + amplitude
                } else {
                    baseline - amplitude
                };
                proptest::prop_assert!(g.check_frame(bytes, 0).leak_alert.is_none());
            }
        }
    }

    #[test]
    fn zero_and_inverted_configs_are_normalized() {
        // Regression: an all-zero config classified EVERY frame Emergency
        // (>= comparisons) — blank screen from startup; inverted watermarks
        // silently misclassified. new() now normalizes.
        let zero = MemoryBudget::new(MemoryBudgetConfig {
            soft_limit_bytes: 0,
            hard_limit_bytes: 0,
            emergency_limit_bytes: 0,
        });
        assert!(zero.config.soft_limit_bytes > 0);
        assert!(zero.config.soft_limit_bytes <= zero.config.hard_limit_bytes);
        assert!(zero.config.hard_limit_bytes <= zero.config.emergency_limit_bytes);

        let inverted = MemoryBudget::new(MemoryBudgetConfig {
            soft_limit_bytes: 32 * 1024 * 1024,
            hard_limit_bytes: 8 * 1024 * 1024,
            emergency_limit_bytes: 16 * 1024 * 1024,
        });
        assert!(inverted.config.soft_limit_bytes <= inverted.config.hard_limit_bytes);
        assert!(inverted.config.hard_limit_bytes <= inverted.config.emergency_limit_bytes);
    }

    // ---- MemoryBudget ----

    #[test]
    fn memory_below_soft_no_alert() {
        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
        assert!(mb.check(1024).is_none());
        assert_eq!(mb.current_bytes(), 1024);
    }

    #[test]
    fn memory_at_soft_limit_warns() {
        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
        let alert = mb.check(8 * 1024 * 1024).unwrap();
        assert_eq!(alert.kind, GuardrailKind::Memory);
        assert_eq!(alert.severity, AlertSeverity::Warning);
        assert_eq!(alert.recommended_level, DegradationLevel::SimpleBorders);
    }

    #[test]
    fn memory_at_hard_limit_critical() {
        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
        let alert = mb.check(16 * 1024 * 1024).unwrap();
        assert_eq!(alert.severity, AlertSeverity::Critical);
        assert_eq!(alert.recommended_level, DegradationLevel::Skeleton);
    }

    #[test]
    fn memory_at_emergency_limit() {
        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
        let alert = mb.check(32 * 1024 * 1024).unwrap();
        assert_eq!(alert.severity, AlertSeverity::Emergency);
        assert_eq!(alert.recommended_level, DegradationLevel::SkipFrame);
    }

    #[test]
    fn memory_peak_tracking() {
        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
        mb.check(1000);
        mb.check(5000);
        mb.check(3000);
        assert_eq!(mb.peak_bytes(), 5000);
        assert_eq!(mb.current_bytes(), 3000);
    }

    #[test]
    fn memory_violation_counts() {
        let config = MemoryBudgetConfig {
            soft_limit_bytes: 100,
            hard_limit_bytes: 200,
            emergency_limit_bytes: 300,
        };
        let mut mb = MemoryBudget::new(config);
        mb.check(50); // no violation
        mb.check(150); // soft
        mb.check(150); // soft again
        mb.check(250); // hard
        mb.check(350); // emergency — its own tier, NOT a hard violation
        assert_eq!(mb.soft_violations(), 2);
        assert_eq!(mb.hard_violations(), 1);
        assert_eq!(
            mb.emergency_violations(),
            1,
            "emergency shedding must be counted separately from hard hits (bd-1za0z F5)"
        );
    }

    #[test]
    fn memory_usage_fraction() {
        let config = MemoryBudgetConfig {
            soft_limit_bytes: 1000,
            hard_limit_bytes: 2000,
            emergency_limit_bytes: 3000,
        };
        let mut mb = MemoryBudget::new(config);
        mb.check(500);
        assert!((mb.usage_fraction() - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn memory_usage_fraction_zero_limit() {
        // The constructor normalizes zero limits to defaults (an all-zero
        // config used to classify every frame Emergency), so a zero-limit
        // budget is no longer constructible via new(); 100 bytes against
        // the default 8 MiB soft limit is a tiny fraction.
        let config = MemoryBudgetConfig {
            soft_limit_bytes: 0,
            hard_limit_bytes: 0,
            emergency_limit_bytes: 0,
        };
        let mut mb = MemoryBudget::new(config);
        mb.check(100);
        assert!(mb.usage_fraction() > 0.0);
        assert!(mb.usage_fraction() < 0.001);
    }

    #[test]
    fn memory_reset_clears_state() {
        let mut mb = MemoryBudget::new(MemoryBudgetConfig::default());
        mb.check(10 * 1024 * 1024); // soft violation
        assert!(mb.soft_violations() > 0);
        mb.reset();
        assert_eq!(mb.peak_bytes(), 0);
        assert_eq!(mb.current_bytes(), 0);
        assert_eq!(mb.soft_violations(), 0);
        assert_eq!(mb.hard_violations(), 0);
    }

    #[test]
    fn memory_config_accessors() {
        let config = MemoryBudgetConfig::small();
        let mb = MemoryBudget::new(config);
        assert_eq!(mb.config().soft_limit_bytes, 2 * 1024 * 1024);
    }

    // ---- QueueGuardrails ----

    #[test]
    fn queue_below_warn_no_alert() {
        let mut qg = QueueGuardrails::new(QueueConfig::default());
        let (alert, action) = qg.check(1);
        assert!(alert.is_none());
        assert_eq!(action, QueueAction::None);
    }

    #[test]
    fn queue_at_warn_depth() {
        let mut qg = QueueGuardrails::new(QueueConfig::default());
        let (alert, action) = qg.check(3);
        assert_eq!(alert.unwrap().severity, AlertSeverity::Warning);
        assert_eq!(action, QueueAction::None); // warning only, no action
    }

    #[test]
    fn queue_at_max_depth_drop_oldest() {
        let config = QueueConfig {
            drop_policy: QueueDropPolicy::DropOldest,
            ..QueueConfig::default()
        };
        let mut qg = QueueGuardrails::new(config);
        let (alert, action) = qg.check(8);
        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
        assert!(action.drops_frames());
    }

    #[test]
    fn queue_at_max_depth_drop_newest() {
        let config = QueueConfig {
            drop_policy: QueueDropPolicy::DropNewest,
            ..QueueConfig::default()
        };
        let mut qg = QueueGuardrails::new(config);
        let (alert, action) = qg.check(8);
        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
        assert_eq!(action, QueueAction::DropNewest(5));
    }

    #[test]
    fn queue_at_max_depth_backpressure() {
        let config = QueueConfig {
            drop_policy: QueueDropPolicy::Backpressure,
            ..QueueConfig::default()
        };
        let mut qg = QueueGuardrails::new(config);
        let (alert, action) = qg.check(8);
        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
        assert_eq!(action, QueueAction::Backpressure);
    }

    #[test]
    fn queue_emergency_drops_to_latest() {
        let mut qg = QueueGuardrails::new(QueueConfig::default());
        let (alert, action) = qg.check(16);
        assert_eq!(alert.unwrap().severity, AlertSeverity::Emergency);
        // DropOldest at emergency should keep only 1 frame
        assert_eq!(action, QueueAction::DropOldest(15));
    }

    #[test]
    fn queue_peak_tracking() {
        let mut qg = QueueGuardrails::new(QueueConfig::default());
        qg.check(2);
        qg.check(5);
        qg.check(1);
        assert_eq!(qg.peak_depth(), 5);
        assert_eq!(qg.current_depth(), 1);
    }

    #[test]
    fn queue_drop_counting() {
        let mut qg = QueueGuardrails::new(QueueConfig::default());
        qg.check(8); // triggers drop
        assert!(qg.total_drops() > 0);
    }

    #[test]
    fn queue_backpressure_counting() {
        let config = QueueConfig::strict();
        let mut qg = QueueGuardrails::new(config);
        qg.check(4); // max_depth for strict
        assert!(qg.total_backpressure_events() > 0);
    }

    #[test]
    fn queue_reset_clears_state() {
        let mut qg = QueueGuardrails::new(QueueConfig::default());
        qg.check(10);
        qg.reset();
        assert_eq!(qg.peak_depth(), 0);
        assert_eq!(qg.current_depth(), 0);
        assert_eq!(qg.total_drops(), 0);
    }

    #[test]
    fn queue_config_accessors() {
        let config = QueueConfig::relaxed();
        let qg = QueueGuardrails::new(config);
        assert_eq!(qg.config().max_depth, 16);
    }

    /// CONTRACT (bd-1za0z): malformed threshold ordering is normalized at
    /// construction — warn <= max <= emergency, warn floored at 1.
    #[test]
    fn queue_config_normalized_at_construction() {
        let config = QueueConfig {
            warn_depth: 10,
            max_depth: 8,
            emergency_depth: 6,
            drop_policy: QueueDropPolicy::DropOldest,
        };
        let qg = QueueGuardrails::new(config);
        let cfg = qg.config();
        assert_eq!(cfg.warn_depth, 10);
        assert_eq!(cfg.max_depth, 10, "max must be raised to warn");
        assert_eq!(cfg.emergency_depth, 10, "emergency must be raised to max");

        let zeroed = QueueGuardrails::new(QueueConfig {
            warn_depth: 0,
            ..QueueConfig::default()
        });
        assert_eq!(
            zeroed.config().warn_depth,
            1,
            "warn_depth 0 would flag an idle queue"
        );
    }

    /// CONTRACT (bd-1za0z): collapsed thresholds (warn == max) must never
    /// produce a zero-excess Drop action; the critical alert still fires.
    #[test]
    fn queue_collapsed_thresholds_yield_noop_action_not_zero_drop() {
        let config = QueueConfig {
            warn_depth: 8,
            max_depth: 8,
            emergency_depth: 16,
            drop_policy: QueueDropPolicy::DropOldest,
        };
        let mut qg = QueueGuardrails::new(config);
        let (alert, action) = qg.check(8);
        assert_eq!(alert.unwrap().severity, AlertSeverity::Critical);
        assert_eq!(
            action,
            QueueAction::None,
            "excess 0 must not be reported as a real drop action"
        );
        assert_eq!(qg.total_drops(), 0, "no-op action must not count drops");
    }

    /// CONTRACT (bd-1za0z): DropNewest at emergency keeps the oldest frame
    /// (drops the newest excess) — policy-relative semantics, now documented
    /// on the config field.
    #[test]
    fn queue_emergency_drop_newest_keeps_oldest() {
        let config = QueueConfig {
            drop_policy: QueueDropPolicy::DropNewest,
            ..QueueConfig::default()
        };
        let mut qg = QueueGuardrails::new(config);
        let (alert, action) = qg.check(16);
        assert_eq!(alert.unwrap().severity, AlertSeverity::Emergency);
        assert_eq!(action, QueueAction::DropNewest(15));
    }

    // ---- QueueAction ----

    #[test]
    fn queue_action_drops_frames() {
        assert!(!QueueAction::None.drops_frames());
        assert!(QueueAction::DropOldest(3).drops_frames());
        assert!(QueueAction::DropNewest(1).drops_frames());
        assert!(!QueueAction::Backpressure.drops_frames());
    }

    // ---- FrameGuardrails ----

    #[test]
    fn guardrails_clear_when_healthy() {
        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
        let v = g.check_frame(1024, 0);
        assert!(v.is_clear());
        assert_eq!(v.recommended_level, DegradationLevel::Full);
        assert_eq!(v.queue_action, QueueAction::None);
    }

    #[test]
    fn guardrails_memory_alert_propagates() {
        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
        let v = g.check_frame(8 * 1024 * 1024, 0);
        assert!(!v.is_clear());
        assert_eq!(v.alerts.len(), 1);
        assert_eq!(v.alerts[0].kind, GuardrailKind::Memory);
        assert!(v.should_degrade());
        assert!(!v.should_drop_frame());
    }

    #[test]
    fn guardrails_queue_alert_propagates() {
        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
        let v = g.check_frame(0, 8);
        assert!(!v.is_clear());
        assert!(v.alerts.iter().any(|a| a.kind == GuardrailKind::QueueDepth));
    }

    #[test]
    fn guardrails_both_alerts_combine() {
        let config = GuardrailsConfig {
            memory: MemoryBudgetConfig {
                soft_limit_bytes: 100,
                hard_limit_bytes: 200,
                emergency_limit_bytes: 300,
            },
            queue: QueueConfig {
                warn_depth: 1,
                max_depth: 2,
                emergency_depth: 3,
                drop_policy: QueueDropPolicy::DropOldest,
            },
            ..Default::default()
        };
        let mut g = FrameGuardrails::new(config);
        let v = g.check_frame(150, 2);
        assert_eq!(v.alerts.len(), 2);
        // Should use the most aggressive recommendation
        assert!(v.recommended_level >= DegradationLevel::SimpleBorders);
    }

    #[test]
    fn guardrails_emergency_recommends_skip() {
        let config = GuardrailsConfig {
            memory: MemoryBudgetConfig {
                soft_limit_bytes: 100,
                hard_limit_bytes: 200,
                emergency_limit_bytes: 300,
            },
            queue: QueueConfig::default(),
            ..Default::default()
        };
        let mut g = FrameGuardrails::new(config);
        let v = g.check_frame(300, 0);
        assert!(v.should_drop_frame());
    }

    #[test]
    fn guardrails_frame_counting() {
        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
        g.check_frame(0, 0);
        g.check_frame(0, 0);
        g.check_frame(8 * 1024 * 1024, 0); // triggers alert
        assert_eq!(g.frames_checked(), 3);
        assert_eq!(g.frames_with_alerts(), 1);
    }

    #[test]
    fn guardrails_alert_rate() {
        let config = GuardrailsConfig {
            memory: MemoryBudgetConfig {
                soft_limit_bytes: 100,
                hard_limit_bytes: 200,
                emergency_limit_bytes: 300,
            },
            queue: QueueConfig::default(),
            ..Default::default()
        };
        let mut g = FrameGuardrails::new(config);
        g.check_frame(50, 0); // clear
        g.check_frame(150, 0); // alert
        g.check_frame(50, 0); // clear
        g.check_frame(150, 0); // alert
        assert!((g.alert_rate() - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn guardrails_alert_rate_zero_frames() {
        let g = FrameGuardrails::new(GuardrailsConfig::default());
        assert!((g.alert_rate() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn guardrails_snapshot_jsonl() {
        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
        g.check_frame(1024, 1);
        let snap = g.snapshot();
        let line = snap.to_jsonl();
        assert!(line.starts_with('{'));
        assert!(line.ends_with('}'));
        assert!(line.contains("\"memory_bytes\":1024"));
        assert!(line.contains("\"queue_depth\":1"));
        assert!(line.contains("\"leak_e_value\":1"));
        assert!(line.contains("\"leak_cusum_upper\":0"));
        assert!(line.contains("\"leak_mean_bytes\":1024"));
        assert!(line.contains("\"leak_alert\":false"));
    }

    #[test]
    fn guardrails_reset_clears_all() {
        let mut g = FrameGuardrails::new(GuardrailsConfig::default());
        g.check_frame(8 * 1024 * 1024, 5);
        g.reset();
        assert_eq!(g.frames_checked(), 0);
        assert_eq!(g.frames_with_alerts(), 0);
        assert_eq!(g.memory().peak_bytes(), 0);
        assert_eq!(g.queue().peak_depth(), 0);
    }

    #[test]
    fn guardrails_subsystem_access() {
        let g = FrameGuardrails::new(GuardrailsConfig::default());
        let _ = g.memory().config();
        let _ = g.queue().config();
    }

    // ---- GuardrailVerdict ----

    #[test]
    fn verdict_max_severity_none_when_clear() {
        let v = GuardrailVerdict {
            alerts: vec![],
            queue_action: QueueAction::None,
            recommended_level: DegradationLevel::Full,
            leak_alert: None,
        };
        assert!(v.max_severity().is_none());
        assert!(v.is_clear());
    }

    #[test]
    fn verdict_max_severity_picks_highest() {
        let v = GuardrailVerdict {
            alerts: vec![
                GuardrailAlert {
                    kind: GuardrailKind::Memory,
                    severity: AlertSeverity::Warning,
                    recommended_level: DegradationLevel::SimpleBorders,
                },
                GuardrailAlert {
                    kind: GuardrailKind::QueueDepth,
                    severity: AlertSeverity::Critical,
                    recommended_level: DegradationLevel::EssentialOnly,
                },
            ],
            queue_action: QueueAction::None,
            recommended_level: DegradationLevel::EssentialOnly,
            leak_alert: None,
        };
        assert_eq!(v.max_severity(), Some(AlertSeverity::Critical));
    }

    // ---- AlertSeverity ordering ----

    #[test]
    fn severity_ordering() {
        assert!(AlertSeverity::Warning < AlertSeverity::Critical);
        assert!(AlertSeverity::Critical < AlertSeverity::Emergency);
    }

    // ---- Config presets ----

    #[test]
    fn memory_config_small_preset() {
        let c = MemoryBudgetConfig::small();
        assert!(c.soft_limit_bytes < MemoryBudgetConfig::default().soft_limit_bytes);
    }

    #[test]
    fn memory_config_large_preset() {
        let c = MemoryBudgetConfig::large();
        assert!(c.soft_limit_bytes > MemoryBudgetConfig::default().soft_limit_bytes);
    }

    #[test]
    fn queue_config_strict_preset() {
        let c = QueueConfig::strict();
        assert_eq!(c.drop_policy, QueueDropPolicy::Backpressure);
        assert!(c.max_depth < QueueConfig::default().max_depth);
    }

    #[test]
    fn queue_config_relaxed_preset() {
        let c = QueueConfig::relaxed();
        assert!(c.max_depth > QueueConfig::default().max_depth);
    }

    // ---- buffer_memory_bytes ----

    #[test]
    fn buffer_memory_typical_terminal() {
        // 80×24 terminal
        assert_eq!(buffer_memory_bytes(80, 24), 80 * 24 * 16);
    }

    #[test]
    fn buffer_memory_zero_dimension() {
        assert_eq!(buffer_memory_bytes(0, 24), 0);
        assert_eq!(buffer_memory_bytes(80, 0), 0);
        assert_eq!(buffer_memory_bytes(0, 0), 0);
    }

    #[test]
    fn buffer_memory_large_terminal() {
        // 300×100 terminal
        let bytes = buffer_memory_bytes(300, 100);
        assert_eq!(bytes, 300 * 100 * 16);
        assert_eq!(bytes, 480_000);
    }

    // ---- QueueDropPolicy Default ----

    #[test]
    fn queue_drop_policy_default_is_drop_oldest() {
        assert_eq!(QueueDropPolicy::default(), QueueDropPolicy::DropOldest);
    }

    // ---- Determinism ----

    #[test]
    fn guardrails_deterministic_for_same_inputs() {
        let config = GuardrailsConfig::default();
        let mut g1 = FrameGuardrails::new(config.clone());
        let mut g2 = FrameGuardrails::new(config);

        let inputs = [(1024, 0), (8 * 1024 * 1024, 3), (20 * 1024 * 1024, 10)];
        for (mem, queue) in inputs {
            let v1 = g1.check_frame(mem, queue);
            let v2 = g2.check_frame(mem, queue);
            assert_eq!(v1.recommended_level, v2.recommended_level);
            assert_eq!(v1.alerts.len(), v2.alerts.len());
            assert_eq!(v1.queue_action, v2.queue_action);
        }
    }
}