euv-performance 0.48.0

Reproducible CPU, layout, rasterization, and allocation benchmarks for the cross-platform euv runtime.
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
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
use super::*;

/// Computes the nearest-rank percentile from a sorted non-empty slice of microsecond samples.
///
/// # Arguments
///
/// - `&[f64]` - Ascending-sorted sample slice in microseconds.
/// - `f64` - Target quantile in `[0.0, 1.0]`.
///
/// # Returns
///
/// - `f64` - Nearest-rank sample value in microseconds (`0.0` if empty).
#[must_use]
fn nearest_rank_percentile(sorted: &[f64], quantile: f64) -> f64 {
    if sorted.is_empty() {
        return 0.0;
    }
    let clamped: f64 = quantile.clamp(0.0, 1.0);
    let rank: usize = ((sorted.len() as f64) * clamped).ceil() as usize;
    let idx: usize = rank.saturating_sub(1).min(sorted.len() - 1);
    sorted[idx]
}

/// Aggregates a completed `FrameMeasureAccum` into a `LatencyDistribution` with `p99.9`, 240/360/480Hz budgets, allocations, and real layout counters.
///
/// # Arguments
///
/// - `&FrameMeasureAccum` - Completed per-scenario frame measurement accumulator.
///
/// # Returns
///
/// - `LatencyDistribution` - Computed percentile, budget-miss, allocation, and layout/paint statistics.
#[must_use]
pub(crate) fn summarize_accumulated_latency(accum: &FrameMeasureAccum) -> LatencyDistribution {
    let FrameMeasureAccum {
        samples_us,
        dirty_ratios,
        full_redraw_count,
        alloc_count_total,
        free_count_total,
        bytes_allocated_total,
        max_allocs_per_frame,
        max_bytes_per_frame,
        peak_live_bytes,
        layout_invalidations,
        layout_passes,
        layout_changed_passes,
        layout_changed_nodes_total,
        draw_commands_total,
        pixels_shaded_total,
    } = accum;
    let iterations: usize = samples_us.len();
    if iterations == 0 {
        return LatencyDistribution {
            iterations: 0,
            full_redraw_count: *full_redraw_count,
            alloc_count_total: *alloc_count_total,
            free_count_total: *free_count_total,
            bytes_allocated_total: *bytes_allocated_total,
            max_allocs_per_frame: *max_allocs_per_frame,
            max_bytes_per_frame: *max_bytes_per_frame,
            peak_live_bytes: *peak_live_bytes,
            layout_invalidations: *layout_invalidations,
            layout_passes: *layout_passes,
            layout_changed_passes: *layout_changed_passes,
            layout_changed_nodes_total: *layout_changed_nodes_total,
            draw_commands_total: *draw_commands_total,
            pixels_shaded_total: *pixels_shaded_total,
            ..LatencyDistribution::default()
        };
    }
    let mut sorted: Vec<f64> = samples_us.clone();
    sorted.sort_by(f64::total_cmp);
    let p50_us: f64 = nearest_rank_percentile(&sorted, 0.50);
    let p95_us: f64 = nearest_rank_percentile(&sorted, 0.95);
    let p99_us: f64 = nearest_rank_percentile(&sorted, 0.99);
    let p99_9_us: f64 = nearest_rank_percentile(&sorted, 0.999);
    let max_us: f64 = *sorted.last().unwrap_or(&0.0);
    let mut sum_us: f64 = 0.0;
    let mut over_480: usize = 0;
    let mut over_360: usize = 0;
    let mut over_240: usize = 0;
    let mut over_144: usize = 0;
    let mut over_60: usize = 0;
    for &sample in samples_us.iter() {
        sum_us += sample;
        if sample > BUDGET_480HZ_US {
            over_480 += 1;
        }
        if sample > BUDGET_360HZ_US {
            over_360 += 1;
        }
        if sample > BUDGET_240HZ_US {
            over_240 += 1;
        }
        if sample > BUDGET_144HZ_US {
            over_144 += 1;
        }
        if sample > BUDGET_60HZ_US {
            over_60 += 1;
        }
    }
    let iters_f64: f64 = iterations as f64;
    let mean_us: f64 = sum_us / iters_f64;
    let mut var_sum: f64 = 0.0;
    for &sample in samples_us.iter() {
        let diff: f64 = sample - mean_us;
        var_sum += diff * diff;
    }
    let jitter_us: f64 = (var_sum / iters_f64).sqrt();
    let missed_240hz_pct: f64 = ((over_240 as f64) / iters_f64) * 100.0;
    let missed_360hz_pct: f64 = ((over_360 as f64) / iters_f64) * 100.0;
    let missed_480hz_pct: f64 = ((over_480 as f64) / iters_f64) * 100.0;
    let effective_fps: f64 = if mean_us > 1e-6 {
        1_000_000.0 / mean_us
    } else {
        0.0
    };
    let mean_dirty_area_ratio: f64 = if dirty_ratios.is_empty() {
        0.0
    } else {
        let mut ratio_sum: f64 = 0.0;
        for &ratio in dirty_ratios.iter() {
            ratio_sum += ratio as f64;
        }
        ratio_sum / (dirty_ratios.len() as f64)
    };
    let mean_allocs_per_frame: f64 = (*alloc_count_total as f64) / iters_f64;
    let mean_bytes_per_frame: f64 = (*bytes_allocated_total as f64) / iters_f64;
    LatencyDistribution {
        iterations,
        p50_us,
        p95_us,
        p99_us,
        p99_9_us,
        max_us,
        mean_us,
        jitter_us,
        over_2_08ms_count: over_480,
        over_2_78ms_count: over_360,
        over_4_17ms_count: over_240,
        over_6_94ms_count: over_144,
        over_16_67ms_count: over_60,
        missed_240hz_pct,
        missed_360hz_pct,
        missed_480hz_pct,
        effective_fps,
        mean_dirty_area_ratio,
        full_redraw_count: *full_redraw_count,
        alloc_count_total: *alloc_count_total,
        free_count_total: *free_count_total,
        bytes_allocated_total: *bytes_allocated_total,
        mean_allocs_per_frame,
        mean_bytes_per_frame,
        max_allocs_per_frame: *max_allocs_per_frame,
        max_bytes_per_frame: *max_bytes_per_frame,
        peak_live_bytes: *peak_live_bytes,
        layout_invalidations: *layout_invalidations,
        layout_passes: *layout_passes,
        layout_changed_passes: *layout_changed_passes,
        layout_changed_nodes_total: *layout_changed_nodes_total,
        draw_commands_total: *draw_commands_total,
        pixels_shaded_total: *pixels_shaded_total,
    }
}

/// Computes percentage reduction from `baseline` to `candidate` (`> 0.0` when `candidate < baseline`).
///
/// # Arguments
///
/// - `f64` - Baseline measurement.
/// - `f64` - Candidate measurement.
///
/// # Returns
///
/// - `f64` - Percentage reduction in `(-inf, 100.0]`.
#[must_use]
fn reduction_pct(baseline: f64, candidate: f64) -> f64 {
    if baseline <= 0.0 {
        return 0.0;
    }
    ((baseline - candidate) / baseline) * 100.0
}

/// Builds a deterministic 1280x720 dense dashboard app for the partial-layout-damage A/B benchmark.
///
/// # Arguments
///
/// - `bool` - Whether `App::set_partial_layout_damage` is enabled.
///
/// # Returns
///
/// - `Option<(App, Vec<(NodeId, NodeId)>)>` - Initialized app and `(badge_box, value_text)` handles for each row.
#[must_use]
fn build_partial_row_ab_app(partial_enabled: bool) -> Option<(App, Vec<(NodeId, NodeId)>)> {
    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
    let p: ThemePalette = tokens.get_palette();
    let g: ThemeGeometry = tokens.get_geometry();
    let mut win: WindowConfig = WindowConfig::default();
    win.set_size(1280, 720).set_render(RenderConfig::software());
    let mut cfg: AppConfig = AppConfig::default();
    cfg.set_window(win);
    let mut app: App = App::headless(cfg).ok()?;
    app.set_partial_layout_damage(partial_enabled);
    app.set_telemetry_enabled(true);
    let mut row_handles: Vec<(NodeId, NodeId)> = Vec::with_capacity(24);
    let _: NodeId = app.mount(|| {
        let mut ctx: Context = current_context();
        let root_style: Style = Style::default()
            .column()
            .width(Length::Px(1280.0))
            .height(Length::Px(720.0))
            .padding(Edges::all(SPACE_MD))
            .gap(SPACE_SM)
            .background(p.get_background());
        let root: NodeId = ctx.view(root_style);
        let header_style: Style = Style::default()
            .row()
            .width(Length::Percent(100.0))
            .height(Length::Px(56.0))
            .padding(Edges::symmetric(SPACE_XS, SPACE_MD))
            .align(AlignItems::Center)
            .justify(JustifyContent::SpaceBetween)
            .background(p.get_card())
            .border(g.get_border_width(), p.get_border())
            .radius(g.get_radius_md());
        let header: NodeId = ctx.view(header_style);
        let title_node: NodeId = ctx.text(
            format!("{BENCH_TITLE} — Partial Layout A/B Matrix"),
            Style::default()
                .font_size(16.0)
                .font_weight(FontWeight::Bold)
                .color(p.get_foreground()),
        );
        let subtitle_node: NodeId = ctx.text(
            BENCH_SUBTITLE.to_string(),
            Style::default()
                .font_size(12.0)
                .color(p.get_muted_foreground()),
        );
        ctx.append(header, title_node);
        ctx.append(header, subtitle_node);
        ctx.append(root, header);
        let grid_style: Style = Style::default()
            .grid(2)
            .width(Length::Percent(100.0))
            .gap(SPACE_SM);
        let grid: NodeId = ctx.view(grid_style);
        for idx in 0..24usize {
            let row_card_style: Style = Style::default()
                .row()
                .width(Length::Px(612.0))
                .height(Length::Px(46.0))
                .padding(Edges::symmetric(SPACE_XS, SPACE_MD))
                .align(AlignItems::Center)
                .justify(JustifyContent::SpaceBetween)
                .overflow(Overflow::Hidden)
                .background(p.get_card())
                .border(g.get_border_width(), p.get_border())
                .radius(g.get_radius_sm());
            let card: NodeId = ctx.view(row_card_style);
            let label_node: NodeId = ctx.text(
                format!("Worker Lane #{idx:02} — Telemetry Stream"),
                Style::default().font_size(13.0).color(p.get_foreground()),
            );
            let right_cluster: NodeId = ctx.view(
                Style::default()
                    .row()
                    .width(Length::Px(220.0))
                    .height(Length::Px(30.0))
                    .align(AlignItems::Center)
                    .justify(JustifyContent::End)
                    .gap(SPACE_SM),
            );
            let badge_box: NodeId = ctx.view(
                Style::default()
                    .row()
                    .width(Length::Px(72.0))
                    .height(Length::Px(24.0))
                    .align(AlignItems::Center)
                    .justify(JustifyContent::Center)
                    .background(p.get_primary())
                    .radius(g.get_radius_sm()),
            );
            let badge_txt: NodeId = ctx.text(
                BENCH_BADGE.to_string(),
                Style::default()
                    .font_size(11.0)
                    .font_weight(FontWeight::Bold)
                    .color(p.get_primary_foreground()),
            );
            ctx.append(badge_box, badge_txt);
            let value_node: NodeId = ctx.text(
                format!("v=0000.{idx:02}"),
                Style::default().font_size(13.0).color(p.get_foreground()),
            );
            ctx.append(right_cluster, badge_box);
            ctx.append(right_cluster, value_node);
            ctx.append(card, label_node);
            ctx.append(card, right_cluster);
            ctx.append(grid, card);
            row_handles.push((badge_box, value_node));
        }
        ctx.append(root, grid);
        root
    });
    let _: FrameStats = app.step_frame().ok()?;
    Some((app, row_handles))
}

/// Applies one deterministic single-row leaf mutation (badge resize + value text update) and measures `step_frame` + allocations.
///
/// # Arguments
///
/// - `&mut App` - Target headless application instance.
/// - `(NodeId, NodeId)` - `(badge_box, value_text)` handles of the mutated leaf row.
/// - `usize` - Monotonic iteration index.
///
/// # Returns
///
/// - `RowMutationStep` - Measured latency, framebuffer hash, telemetry, and allocation delta for this step.
fn step_single_row_mutation(
    app: &mut App,
    handles: (NodeId, NodeId),
    step: usize,
) -> RowMutationStep {
    let (badge_box, value_node): (NodeId, NodeId) = handles;
    let next_badge_w: f32 = 64.0 + ((step % 5) as f32) * 8.0;
    let next_val: String = format!("v={:04}.{:02}", step + 1, (step * 7) % 100);
    app.get_scene().with_write(
        |tree: &mut SceneTree| {
            let _: bool = tree.mutate_style(badge_box, |st: &mut Style| {
                let _: &mut LayoutStyle = st.get_mut_layout().set_width(Length::Px(next_badge_w));
            });
            tree.set_text(value_node, next_val);
        },
        (),
    );
    let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
    let started: Instant = Instant::now();
    let frame_hash: u64 = match app.step_frame() {
        Ok(stats) => stats.get_frame_hash(),
        Err(_) => 0,
    };
    let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
    let alloc_delta: AllocationSnapshot = snapshot_raw_alloc_counters().delta_since(alloc_before);
    let telemetry: FrameTelemetry = app.last_frame_telemetry();
    RowMutationStep {
        elapsed_us,
        frame_hash,
        telemetry,
        alloc_delta,
    }
}

/// Runs interleaved A/B single-row leaf updates comparing `partial_layout_damage = false` vs `true` with bit-exact RGBA parity verification.
///
/// # Arguments
///
/// - `usize` - Number of interleaved single-row update frames per arm.
///
/// # Returns
///
/// - `(StressMatrixEntry, PartialDamageAbSummary)` - Matrix entry (candidate partial-damage latency) and structured A/B summary.
#[must_use]
pub fn stress_partial_single_row_update_ab(
    iterations: usize,
) -> (StressMatrixEntry, PartialDamageAbSummary) {
    reset_reactive_runtime();
    let count: usize = iterations.max(1);
    let Some((mut app_full, rows_full)) = build_partial_row_ab_app(false) else {
        let empty: LatencyDistribution = LatencyDistribution::default();
        let summary: PartialDamageAbSummary = PartialDamageAbSummary {
            name: STRESS_PARTIAL_ROW_AB_NAME.to_string(),
            baseline_full_redraw: empty,
            candidate_partial_damage: empty,
            p50_speedup_pct: 0.0,
            p95_speedup_pct: 0.0,
            p99_speedup_pct: 0.0,
            dirty_area_ratio_drop_pct: 0.0,
            bit_exact_parity: false,
            verified_steps: 0,
            detail: String::from(STRESS_INIT_FAILED),
        };
        let entry: StressMatrixEntry = StressMatrixEntry::new(
            STRESS_PARTIAL_ROW_AB_NAME.to_string(),
            empty,
            String::from(STRESS_INIT_FAILED),
        );
        return (entry, summary);
    };
    let Some((mut app_partial, rows_partial)) = build_partial_row_ab_app(true) else {
        let empty: LatencyDistribution = LatencyDistribution::default();
        let summary: PartialDamageAbSummary = PartialDamageAbSummary {
            name: STRESS_PARTIAL_ROW_AB_NAME.to_string(),
            baseline_full_redraw: empty,
            candidate_partial_damage: empty,
            p50_speedup_pct: 0.0,
            p95_speedup_pct: 0.0,
            p99_speedup_pct: 0.0,
            dirty_area_ratio_drop_pct: 0.0,
            bit_exact_parity: false,
            verified_steps: 0,
            detail: String::from(STRESS_INIT_FAILED),
        };
        let entry: StressMatrixEntry = StressMatrixEntry::new(
            STRESS_PARTIAL_ROW_AB_NAME.to_string(),
            empty,
            String::from(STRESS_INIT_FAILED),
        );
        return (entry, summary);
    };
    let mut full_accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let mut partial_accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let layout_before_full: LayoutTelemetry =
        app_full.last_frame_telemetry().get_layout_telemetry();
    let layout_before_partial: LayoutTelemetry =
        app_partial.last_frame_telemetry().get_layout_telemetry();
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    let mut parity_ok: bool = true;
    for step in 0..count {
        let row_idx: usize = step % rows_full.len();
        let (full_res, partial_res): (RowMutationStep, RowMutationStep) = if step % 2 == 0 {
            let res_a: RowMutationStep =
                step_single_row_mutation(&mut app_full, rows_full[row_idx], step);
            let res_b: RowMutationStep =
                step_single_row_mutation(&mut app_partial, rows_partial[row_idx], step);
            (res_a, res_b)
        } else {
            let res_b: RowMutationStep =
                step_single_row_mutation(&mut app_partial, rows_partial[row_idx], step);
            let res_a: RowMutationStep =
                step_single_row_mutation(&mut app_full, rows_full[row_idx], step);
            (res_a, res_b)
        };
        full_accum.record_frame(full_res.elapsed_us, full_res.alloc_delta);
        full_accum.record_frame_telemetry(&full_res.telemetry);
        partial_accum.record_frame(partial_res.elapsed_us, partial_res.alloc_delta);
        partial_accum.record_frame_telemetry(&partial_res.telemetry);
        if full_res.frame_hash == 0 || full_res.frame_hash != partial_res.frame_hash {
            parity_ok = false;
        }
    }
    drop(alloc_guard);
    full_accum.set_layout_delta(
        layout_before_full,
        app_full.last_frame_telemetry().get_layout_telemetry(),
    );
    partial_accum.set_layout_delta(
        layout_before_partial,
        app_partial.last_frame_telemetry().get_layout_telemetry(),
    );
    if let (Some(fb_a), Some(fb_b)) = (
        app_full.get_renderer().framebuffer(),
        app_partial.get_renderer().framebuffer(),
    ) && (fb_a.get_width() != fb_b.get_width()
        || fb_a.get_height() != fb_b.get_height()
        || fb_a.get_pixels() != fb_b.get_pixels())
    {
        parity_ok = false;
    }
    let baseline: LatencyDistribution = full_accum.finish();
    let candidate: LatencyDistribution = partial_accum.finish();
    let p50_pct: f64 = reduction_pct(baseline.get_p50_us(), candidate.get_p50_us());
    let p95_pct: f64 = reduction_pct(baseline.get_p95_us(), candidate.get_p95_us());
    let p99_pct: f64 = reduction_pct(baseline.get_p99_us(), candidate.get_p99_us());
    let dirty_drop_pct: f64 = reduction_pct(
        baseline.get_mean_dirty_area_ratio(),
        candidate.get_mean_dirty_area_ratio(),
    );
    let detail: String = format!(
        "1280x720 parity={parity_ok} p50={:.1}us->{:.1}us ({:+.1}%) p95={:+.1}% p99={:+.1}% dirty={:.3}->{:.4} ({:+.1}% drop) full_redraws={}->{} allocs={:.1}/f bytes={:.0}B/f",
        baseline.get_p50_us(),
        candidate.get_p50_us(),
        p50_pct,
        p95_pct,
        p99_pct,
        baseline.get_mean_dirty_area_ratio(),
        candidate.get_mean_dirty_area_ratio(),
        dirty_drop_pct,
        baseline.get_full_redraw_count(),
        candidate.get_full_redraw_count(),
        candidate.get_mean_allocs_per_frame(),
        candidate.get_mean_bytes_per_frame(),
    );
    let summary: PartialDamageAbSummary = PartialDamageAbSummary {
        name: STRESS_PARTIAL_ROW_AB_NAME.to_string(),
        baseline_full_redraw: baseline,
        candidate_partial_damage: candidate,
        p50_speedup_pct: p50_pct,
        p95_speedup_pct: p95_pct,
        p99_speedup_pct: p99_pct,
        dirty_area_ratio_drop_pct: dirty_drop_pct,
        bit_exact_parity: parity_ok,
        verified_steps: count,
        detail: detail.clone(),
    };
    let entry: StressMatrixEntry =
        StressMatrixEntry::new(STRESS_PARTIAL_ROW_AB_NAME.to_string(), candidate, detail);
    (entry, summary)
}

/// Stress-tests 100,000-row `EuvVirtualList` high-frequency scrolling and records tail latency and allocation distributions.
///
/// # Arguments
///
/// - `usize` - Number of high-frequency scroll frames to measure.
///
/// # Returns
///
/// - `StressMatrixEntry` - Per-frame tail latencies, over-budget counts, allocations, and damage ratio.
#[must_use]
pub fn stress_virtual_list_scroll_tail(iterations: usize) -> StressMatrixEntry {
    reset_reactive_runtime();
    let count: usize = iterations.max(1);
    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
    let p: ThemePalette = tokens.get_palette();
    let g: ThemeGeometry = tokens.get_geometry();
    let mut win: WindowConfig = WindowConfig::default();
    win.set_size(400, 720).set_render(RenderConfig::software());
    let mut cfg: AppConfig = AppConfig::default();
    cfg.set_window(win);
    let Ok(mut app) = App::headless(cfg) else {
        return StressMatrixEntry::new(
            STRESS_VIRTUAL_LIST_TAIL_NAME.to_string(),
            LatencyDistribution::default(),
            String::from(STRESS_INIT_FAILED),
        );
    };
    app.set_telemetry_enabled(true);
    let scroll_y: Signal<f32> = Signal::new(0.0);
    let _: NodeId = app.mount(|| {
        let vlist: EuvVirtualList =
            EuvVirtualList::new(100_000, 36.0, scroll_y, tokens).viewport_height(680.0);
        vlist.mount_pooled(
            move || -> (NodeId, NodeId) {
                let mut label_node: NodeId = NodeId::default();
                let mut row_label: String = String::with_capacity(32);
                row_label.push_str(BENCH_ROW_LABEL);
                let row_node: NodeId = view! {
                    row {
                        style: {
                            width: Length::Percent(100.0)
                            height: Length::Px(36.0)
                            padding: Edges::symmetric(SPACE_XS, SPACE_MD)
                            align: AlignItems::Center
                            justify: JustifyContent::SpaceBetween
                            border: (g.get_border_width(), p.get_border())
                        }
                        text {
                            node_ref: label_node
                            style: {
                                width: Length::Px(220.0)
                                height: Length::Px(18.0)
                                font_size: 13.0
                                color: p.get_foreground()
                            }
                            { row_label }
                        }
                    }
                };
                (row_node, label_node)
            },
            |label_node: &mut NodeId, idx: usize, tree: &mut SceneTree| {
                tree.mutate_text(*label_node, |buf: &mut String| {
                    buf.clear();
                    if write!(buf, "{BENCH_ROW_LABEL} #{idx:06}").is_err() {}
                });
            },
        )
    });
    for warm in 0..6usize {
        if warm > 0 {
            let _: bool = scroll_y.set_if_changed((warm as f32) * 72.0);
        }
        let _: Result<FrameStats, PlatformError> = app.step_frame();
    }
    let _: bool = scroll_y.set_if_changed(0.0);
    let _: Result<FrameStats, PlatformError> = app.step_frame();
    let mut accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let layout_before: LayoutTelemetry = app.last_frame_telemetry().get_layout_telemetry();
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    let mut last_shaded: usize = 0;
    for step in 1..=count {
        let delta: f32 = if step % 20 == 0 { 1_440.0 } else { 72.0 };
        let next_y: f32 = (scroll_y.get_untracked() + delta) % 3_500_000.0;
        let _: bool = scroll_y.set_if_changed(next_y);
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        if let Ok(stats) = app.step_frame() {
            last_shaded = stats.get_pixels_shaded();
        }
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        let tel: FrameTelemetry = app.last_frame_telemetry();
        accum.record_frame(elapsed_us, alloc_delta);
        accum.record_frame_telemetry(&tel);
    }
    drop(alloc_guard);
    accum.set_layout_delta(
        layout_before,
        app.last_frame_telemetry().get_layout_telemetry(),
    );
    let latency: LatencyDistribution = accum.finish();
    let detail: String = format!(
        "rows=100000 scroll_y={:.0}px shaded={last_shaded} dirty={:.3} full_redraws={} allocs={:.1}/f bytes={:.0}B/f",
        scroll_y.get_untracked(),
        latency.get_mean_dirty_area_ratio(),
        latency.get_full_redraw_count(),
        latency.get_mean_allocs_per_frame(),
        latency.get_mean_bytes_per_frame(),
    );
    StressMatrixEntry::new(STRESS_VIRTUAL_LIST_TAIL_NAME.to_string(), latency, detail)
}

/// Stress-tests continuous window resize reflow bursts across mobile, tablet, and desktop viewports while asserting zero stale bounds.
///
/// # Arguments
///
/// - `usize` - Number of continuous resize-reflow frames to measure.
///
/// # Returns
///
/// - `StressMatrixEntry` - Per-frame reflow latencies, stale-bounds count, allocations, and layout telemetry.
#[must_use]
pub fn stress_window_resize_reflow(iterations: usize) -> StressMatrixEntry {
    reset_reactive_runtime();
    let count: usize = iterations.max(1);
    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
    let p: ThemePalette = tokens.get_palette();
    let g: ThemeGeometry = tokens.get_geometry();
    let mut win: WindowConfig = WindowConfig::default();
    win.set_size(800, 600).set_render(RenderConfig::software());
    let mut cfg: AppConfig = AppConfig::default();
    cfg.set_window(win);
    let Ok(mut app) = App::headless(cfg) else {
        return StressMatrixEntry::new(
            STRESS_WINDOW_RESIZE_NAME.to_string(),
            LatencyDistribution::default(),
            String::from(STRESS_INIT_FAILED),
        );
    };
    app.set_telemetry_enabled(true);
    let shell_node: NodeId = app.mount(|| {
        view! {
            column {
                style: {
                    width: Length::Percent(100.0)
                    height: Length::Percent(100.0)
                    padding: Edges::all(SPACE_MD)
                    gap: SPACE_SM
                    overflow: Overflow::Hidden
                    background: p.get_background()
                }
                EuvHeader {
                    title: BENCH_TITLE.to_string()
                    subtitle: BENCH_SUBTITLE.to_string()
                    tokens: tokens
                }
                grid {
                    style: {
                        columns: 3
                        width: Length::Percent(100.0)
                        gap: SPACE_SM
                    }
                    for idx in 0..12usize {
                        column {
                            style: {
                                width: Length::Percent(100.0)
                                padding: Edges::all(SPACE_SM)
                                gap: SPACE_XS
                                overflow: Overflow::Hidden
                                background: p.get_card()
                                border: (g.get_border_width(), p.get_border())
                                radius: g.get_radius_md()
                            }
                            text {
                                style: {
                                    width: Length::Percent(100.0)
                                    font_size: 13.0
                                    color: p.get_foreground()
                                }
                                { format!("{BENCH_CELL_LABEL} #{idx:02} — Responsive Card") }
                            }
                            text {
                                style: {
                                    width: Length::Percent(100.0)
                                    font_size: 11.0
                                    color: p.get_muted_foreground()
                                }
                                { BENCH_CARD_WRAP_COPY }
                            }
                        }
                    }
                }
            }
        }
    });
    let wid: WindowId = app.get_window_state().get_id();
    let _: Result<FrameStats, PlatformError> = app.step_frame();
    let presets: [(u32, u32); 6] = [
        (390, 780),
        (540, 720),
        (768, 900),
        (1024, 720),
        (1280, 720),
        (960, 640),
    ];
    let mut accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let layout_before: LayoutTelemetry = app.last_frame_telemetry().get_layout_telemetry();
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    let mut stale_bounds_count: usize = 0;
    for step in 0..count {
        let (base_w, base_h): (u32, u32) = presets[step % presets.len()];
        let jitter: u32 = ((step / presets.len()) as u32) * 12;
        let next_w: u32 = base_w + (jitter % 96);
        let next_h: u32 = base_h + (jitter % 64);
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        app.dispatch_window_event(WindowEvent::Resized(wid, next_w, next_h, 1.0));
        let _: Result<FrameStats, PlatformError> = app.step_frame();
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        let tel: FrameTelemetry = app.last_frame_telemetry();
        accum.record_frame(elapsed_us, alloc_delta);
        accum.record_frame_telemetry(&tel);
        let bounds: Rect = app.get_scene().with_read(
            |tree: &SceneTree| {
                tree.get_node(shell_node)
                    .map(|node: &SceneNode| node.get_layout_box().get_bounds())
                    .unwrap_or_default()
            },
            Rect::default(),
        );
        if (bounds.get_width() - (next_w as f32)).abs() > 1.0
            || (bounds.get_height() - (next_h as f32)).abs() > 1.0
        {
            stale_bounds_count += 1;
        }
    }
    drop(alloc_guard);
    accum.set_layout_delta(
        layout_before,
        app.last_frame_telemetry().get_layout_telemetry(),
    );
    let latency: LatencyDistribution = accum.finish();
    let detail: String = format!(
        "stale_bounds={stale_bounds_count} dirty={:.3} full_redraws={} allocs={:.1}/f bytes={:.0}B/f",
        latency.get_mean_dirty_area_ratio(),
        latency.get_full_redraw_count(),
        latency.get_mean_allocs_per_frame(),
        latency.get_mean_bytes_per_frame(),
    );
    StressMatrixEntry::new(STRESS_WINDOW_RESIZE_NAME.to_string(), latency, detail)
}

/// Stress-tests §06 `TerminalRenderer` full-sync, 1-cell incremental ANSI diff bytes, and 0-byte idle flush throughput.
///
/// # Arguments
///
/// - `usize` - Number of incremental 1-cell diff frames and idle flush checks to measure.
///
/// # Returns
///
/// - `StressMatrixEntry` - Incremental diff latency distribution plus full-sync and idle-flush telemetry.
#[must_use]
pub fn stress_terminal_tui_diff(iterations: usize) -> StressMatrixEntry {
    let count: usize = iterations.max(1);
    let mut tree: SceneTree = SceneTree::default();
    let root: NodeId = tree.get_root();
    let container: NodeId = tree.create_view(Style::default().column());
    let header: NodeId = tree.create_text(
        String::from(STRESS_TUI_HEADER),
        Style::default()
            .font_weight(FontWeight::Bold)
            .color(Color::rgb(96, 165, 250)),
    );
    tree.append_child(container, header);
    for idx in 0..24usize {
        let row_txt: NodeId = tree.create_text(
            format!("Service #{idx:02}  status=OK  latency=120us  queue=0"),
            Style::default().color(Color::rgb(226, 232, 240)),
        );
        tree.append_child(container, row_txt);
    }
    let counter_node: NodeId = tree.create_text(
        String::from(STRESS_TUI_TICK_ZERO),
        Style::default().color(Color::rgb(52, 211, 153)),
    );
    tree.append_child(container, counter_node);
    tree.append_child(root, container);
    let mut renderer: TerminalRenderer = TerminalRenderer::default();
    let full_started: Instant = Instant::now();
    let (_full_payload, full_stats): (String, TerminalDiffStats) =
        renderer.render_tree(&tree, 120, 40, TerminalRenderMode::InteractiveTui);
    let full_sync_us: f64 = (full_started.elapsed().as_nanos() as f64) / 1_000.0;
    let mut diff_accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let mut idle_accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    let mut diff_bytes_total: usize = 0;
    let mut max_changed_cells: usize = 0;
    for step in 0..count {
        let digit: usize = (step + 1) % 10;
        tree.set_text(counter_node, format!("tick={digit}"));
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        let (_diff_payload, stats): (&str, TerminalDiffStats) =
            renderer.render_tree_borrowed(&tree, 120, 40, TerminalRenderMode::InteractiveTui);
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        diff_accum.record_frame(elapsed_us, alloc_delta);
        diff_bytes_total += stats.get_output_bytes();
        max_changed_cells = max_changed_cells.max(stats.get_changed_cells());
    }
    let mut idle_bytes_total: usize = 0;
    let mut idle_frames_ok: usize = 0;
    for _ in 0..count {
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        let (idle_payload, idle_stats): (&str, TerminalDiffStats) =
            renderer.render_tree_borrowed(&tree, 120, 40, TerminalRenderMode::InteractiveTui);
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        idle_accum.record_frame(elapsed_us, alloc_delta);
        idle_bytes_total += idle_payload.len();
        if idle_stats.get_is_idle() && idle_stats.get_output_bytes() == 0 {
            idle_frames_ok += 1;
        }
    }
    drop(alloc_guard);
    let diff_latency: LatencyDistribution = diff_accum.finish();
    let idle_latency: LatencyDistribution = idle_accum.finish();
    let avg_diff_bytes: f64 = (diff_bytes_total as f64) / (count as f64);
    let detail: String = format!(
        "120x40 full_sync={}B ({:.1}us) diff_avg={:.1}B max_cells={max_changed_cells} idle_p50={:.1}us idle_bytes={idle_bytes_total} idle_ok={idle_frames_ok}/{count} allocs={:.1}/f bytes={:.0}B/f",
        full_stats.get_output_bytes(),
        full_sync_us,
        avg_diff_bytes,
        idle_latency.get_p50_us(),
        diff_latency.get_mean_allocs_per_frame(),
        diff_latency.get_mean_bytes_per_frame(),
    );
    StressMatrixEntry::new(
        STRESS_TERMINAL_TUI_DIFF_NAME.to_string(),
        diff_latency,
        detail,
    )
}

/// Stress-tests continuous 240Hz/360Hz/480Hz smooth scrolling over a rich multi-card showcase page with zero relayout.
///
/// # Arguments
///
/// - `usize` - Number of continuous high-refresh scroll frames to measure.
///
/// # Returns
///
/// - `StressMatrixEntry` - Tail latencies (`p99.9`), jitter, 240/360/480Hz miss percentages, allocations, and composite-only telemetry.
#[must_use]
pub fn stress_scroll_240hz_stability(iterations: usize) -> StressMatrixEntry {
    reset_reactive_runtime();
    let count: usize = iterations.max(1);
    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
    let p: ThemePalette = tokens.get_palette();
    let g: ThemeGeometry = tokens.get_geometry();
    let mut win: WindowConfig = WindowConfig::default();
    win.set_size(1280, 720).set_render(RenderConfig::hardware());
    let mut cfg: AppConfig = AppConfig::default();
    cfg.set_window(win);
    let backend: Box<dyn PlatformBackend> = Box::new(
        HeadlessPlatform::emulating(PlatformKind::MacOs, 1.0, SafeAreaInsets::default())
            .with_refresh_rate_hz(480.0),
    );
    let Ok(mut app) = App::with_platform(cfg, backend) else {
        return StressMatrixEntry::new(
            STRESS_SCROLL_240HZ_NAME.to_string(),
            LatencyDistribution::default(),
            String::from(STRESS_INIT_FAILED),
        );
    };
    app.set_telemetry_enabled(true);
    let mut scroll_id: NodeId = NodeId::default();
    let _: NodeId = app.mount(|| {
        let mut ctx: Context = current_context();
        let root: NodeId = ctx.view(
            Style::default()
                .column()
                .width(Length::Px(1280.0))
                .height(Length::Px(720.0))
                .background(p.get_background()),
        );
        let header: NodeId = ctx.view(
            Style::default()
                .row()
                .width(Length::Percent(100.0))
                .height(Length::Px(56.0))
                .padding(Edges::symmetric(SPACE_XS, SPACE_MD))
                .align(AlignItems::Center)
                .justify(JustifyContent::SpaceBetween)
                .background(p.get_card())
                .border(g.get_border_width(), p.get_border()),
        );
        let title_node: NodeId = ctx.text(
            format!("{BENCH_TITLE} — 240Hz/360Hz/480Hz Scroll Stability"),
            Style::default()
                .font_size(15.0)
                .font_weight(FontWeight::Bold)
                .color(p.get_foreground()),
        );
        ctx.append(header, title_node);
        ctx.append(root, header);
        let scroller: NodeId = ctx.view(
            Style::default()
                .column()
                .width(Length::Px(1280.0))
                .height(Length::Px(664.0))
                .padding(Edges::all(SPACE_MD))
                .gap(SPACE_SM)
                .overflow(Overflow::Scroll),
        );
        scroll_id = scroller;
        for idx in 0..80usize {
            let card: NodeId = ctx.view(
                Style::default()
                    .column()
                    .width(Length::Px(1248.0))
                    .height(Length::Px(82.0))
                    .padding(Edges::symmetric(SPACE_SM, SPACE_MD))
                    .gap(SPACE_XS)
                    .overflow(Overflow::Hidden)
                    .background(p.get_card())
                    .border(g.get_border_width(), p.get_border())
                    .radius(g.get_radius_md()),
            );
            let top_row: NodeId = ctx.view(
                Style::default()
                    .row()
                    .width(Length::Percent(100.0))
                    .align(AlignItems::Center)
                    .justify(JustifyContent::SpaceBetween),
            );
            let card_title: NodeId = ctx.text(
                format!("{STRESS_SCROLL_CARD_TITLE} #{idx:02}"),
                Style::default()
                    .font_size(14.0)
                    .font_weight(FontWeight::SemiBold)
                    .color(p.get_foreground()),
            );
            let badge: NodeId = ctx.text(
                format!("lane={idx:02} | 480Hz"),
                Style::default()
                    .font_size(11.0)
                    .font_weight(FontWeight::Bold)
                    .color(p.get_primary()),
            );
            let card_desc: NodeId = ctx.text(
                STRESS_SCROLL_CARD_COPY.to_string(),
                Style::default()
                    .width(Length::Percent(100.0))
                    .font_size(12.0)
                    .color(p.get_muted_foreground()),
            );
            ctx.append(top_row, card_title);
            ctx.append(top_row, badge);
            ctx.append(card, top_row);
            ctx.append(card, card_desc);
            ctx.append(scroller, card);
        }
        ctx.append(root, scroller);
        root
    });
    let wid: WindowId = app.get_window_state().get_id();
    let _: Result<FrameStats, PlatformError> = app.step_frame();
    app.dispatch_window_event(WindowEvent::PointerMove(
        wid,
        PointerEvent::mouse(640.0, 360.0),
    ));
    let _: Result<FrameStats, PlatformError> = app.step_frame();
    let mut accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let layout_before: LayoutTelemetry = app.last_frame_telemetry().get_layout_telemetry();
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    let mut layout_nodes_total: usize = 0;
    let mut composite_only_frames: usize = 0;
    let mut unique_positions: usize = 0;
    let mut prev_scroll_y: f32 = -1.0;
    for step in 0..count {
        if step.is_multiple_of(4) {
            let dir: f32 = if (step / 60).is_multiple_of(2) {
                96.0
            } else {
                -96.0
            };
            app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, dir)));
        }
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        let tel: FrameTelemetry = app.last_frame_telemetry();
        accum.record_frame(elapsed_us, alloc_delta);
        accum.record_frame_telemetry(&tel);
        layout_nodes_total += tel.get_layout_nodes();
        if tel.get_composite_only() {
            composite_only_frames += 1;
        }
        let cur_y: f32 = app.get_scene().with_read(
            |tree: &SceneTree| {
                tree.get_node(scroll_id)
                    .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
                    .unwrap_or(0.0)
            },
            0.0,
        );
        if (cur_y - prev_scroll_y).abs() > 0.01 {
            unique_positions += 1;
            prev_scroll_y = cur_y;
        }
    }
    drop(alloc_guard);
    accum.set_layout_delta(
        layout_before,
        app.last_frame_telemetry().get_layout_telemetry(),
    );
    let latency: LatencyDistribution = accum.finish();
    let detail: String = format!(
        "1280x720 cards=80 jitter={:.1}us miss240={:.2}% miss360={:.2}% miss480={:.2}% fps={:.0} layout_nodes={layout_nodes_total} composite_only={composite_only_frames}/{count} unique_y={unique_positions} allocs={:.1}/f bytes={:.0}B/f",
        latency.get_jitter_us(),
        latency.get_missed_240hz_pct(),
        latency.get_missed_360hz_pct(),
        latency.get_missed_480hz_pct(),
        latency.get_effective_fps(),
        latency.get_mean_allocs_per_frame(),
        latency.get_mean_bytes_per_frame(),
    );
    StressMatrixEntry::new(STRESS_SCROLL_240HZ_NAME.to_string(), latency, detail)
}

/// Stress-tests steady-state idle/overlay UI animation at 480Hz cadence measuring tail latency and heap allocations per frame.
///
/// # Arguments
///
/// - `usize` - Number of 480Hz animated UI frames to measure.
///
/// # Returns
///
/// - `StressMatrixEntry` - Tail latencies (`p99.9`), 240/360/480Hz miss rates, and steady-state allocation counts.
#[must_use]
pub fn stress_idle_anim_480hz_stability(iterations: usize) -> StressMatrixEntry {
    reset_reactive_runtime();
    let count: usize = iterations.max(1);
    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
    let p: ThemePalette = tokens.get_palette();
    let g: ThemeGeometry = tokens.get_geometry();
    let mut win: WindowConfig = WindowConfig::default();
    win.set_size(1280, 720).set_render(RenderConfig::hardware());
    let mut cfg: AppConfig = AppConfig::default();
    cfg.set_window(win);
    let backend: Box<dyn PlatformBackend> = Box::new(
        HeadlessPlatform::emulating(PlatformKind::MacOs, 1.0, SafeAreaInsets::default())
            .with_refresh_rate_hz(480.0),
    );
    let Ok(mut app) = App::with_platform(cfg, backend) else {
        return StressMatrixEntry::new(
            STRESS_IDLE_ANIM_480HZ_NAME.to_string(),
            LatencyDistribution::default(),
            String::from(STRESS_INIT_FAILED),
        );
    };
    app.set_telemetry_enabled(true);
    let mut pulse_node: NodeId = NodeId::default();
    let _: NodeId = app.mount(|| {
        view! {
            column {
                style: {
                    width: Length::Percent(100.0)
                    height: Length::Percent(100.0)
                    padding: Edges::all(SPACE_MD)
                    gap: SPACE_SM
                    overflow: Overflow::Hidden
                    background: p.get_background()
                }
                EuvHeader {
                    title: STRESS_IDLE_ANIM_TITLE.to_string()
                    subtitle: BENCH_SUBTITLE.to_string()
                    tokens: tokens
                }
                view {
                    node_ref: pulse_node
                    style: {
                        width: Length::Percent(100.0)
                        height: Length::Px(14.0)
                        radius: 7.0
                        background: p.get_primary()
                    }
                }
                grid {
                    style: {
                        columns: 4
                        width: Length::Percent(100.0)
                        gap: SPACE_SM
                    }
                    for idx in 0..8usize {
                        column {
                            style: {
                                width: Length::Percent(100.0)
                                padding: Edges::all(SPACE_SM)
                                gap: SPACE_XS
                                overflow: Overflow::Hidden
                                background: p.get_card()
                                border: (g.get_border_width(), p.get_border())
                                radius: g.get_radius_md()
                            }
                            text {
                                style: {
                                    width: Length::Percent(100.0)
                                    font_size: 13.0
                                    color: p.get_foreground()
                                }
                                { format!("{BENCH_TITLE} #{idx}") }
                            }
                            EuvProgress {
                                value: ((idx as f32) + 1.0) * 0.11
                                tokens: tokens
                            }
                        }
                    }
                }
            }
        }
    });
    for _ in 0..2usize {
        let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 480.0);
    }
    let mut accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let layout_before: LayoutTelemetry = app.last_frame_telemetry().get_layout_telemetry();
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    for step in 0..count {
        let phase: f32 = ((step as f32) * 0.08).sin().mul_add(0.25, 0.75);
        app.get_scene().with_write(
            |tree: &mut SceneTree| {
                let _: bool = tree.mutate_style(pulse_node, |st: &mut Style| {
                    let _: &mut PaintStyle = st.get_mut_paint().set_opacity(phase);
                });
            },
            (),
        );
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 480.0);
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        let tel: FrameTelemetry = app.last_frame_telemetry();
        accum.record_frame(elapsed_us, alloc_delta);
        accum.record_frame_telemetry(&tel);
    }
    drop(alloc_guard);
    accum.set_layout_delta(
        layout_before,
        app.last_frame_telemetry().get_layout_telemetry(),
    );
    let latency: LatencyDistribution = accum.finish();
    let detail: String = format!(
        "1280x720 anim_480hz jitter={:.1}us miss240={:.2}% miss360={:.2}% miss480={:.2}% fps={:.0} allocs={:.1}/f bytes={:.0}B/f",
        latency.get_jitter_us(),
        latency.get_missed_240hz_pct(),
        latency.get_missed_360hz_pct(),
        latency.get_missed_480hz_pct(),
        latency.get_effective_fps(),
        latency.get_mean_allocs_per_frame(),
        latency.get_mean_bytes_per_frame(),
    );
    StressMatrixEntry::new(STRESS_IDLE_ANIM_480HZ_NAME.to_string(), latency, detail)
}

/// Stress-tests continuous 480Hz pointer movement and hit-testing across an interactive multi-card scene.
///
/// # Arguments
///
/// - `usize` - Number of 480Hz pointer-move frames to measure.
///
/// # Returns
///
/// - `StressMatrixEntry` - Tail latencies (`p99.9`), hit counts, 240/360/480Hz miss rates, and steady-state allocations.
#[must_use]
pub fn stress_pointer_move_480hz_stability(iterations: usize) -> StressMatrixEntry {
    reset_reactive_runtime();
    let count: usize = iterations.max(1);
    let tokens: ThemeTokens = ThemeTokens::resolve(DesignScheme::Shadcn, ThemeMode::Light);
    let p: ThemePalette = tokens.get_palette();
    let g: ThemeGeometry = tokens.get_geometry();
    let mut win: WindowConfig = WindowConfig::default();
    win.set_size(1280, 720).set_render(RenderConfig::hardware());
    let mut cfg: AppConfig = AppConfig::default();
    cfg.set_window(win);
    let backend: Box<dyn PlatformBackend> = Box::new(
        HeadlessPlatform::emulating(PlatformKind::MacOs, 1.0, SafeAreaInsets::default())
            .with_refresh_rate_hz(480.0),
    );
    let Ok(mut app) = App::with_platform(cfg, backend) else {
        return StressMatrixEntry::new(
            STRESS_POINTER_MOVE_480HZ_NAME.to_string(),
            LatencyDistribution::default(),
            String::from(STRESS_INIT_FAILED),
        );
    };
    app.set_telemetry_enabled(true);
    let _: NodeId = app.mount(|| {
        view! {
            grid {
                style: {
                    columns: 5
                    width: Length::Percent(100.0)
                    height: Length::Percent(100.0)
                    padding: Edges::all(SPACE_SM)
                    gap: SPACE_XS
                    overflow: Overflow::Hidden
                    background: p.get_background()
                }
                for idx in 0..40usize {
                    column {
                        style: {
                            width: Length::Percent(100.0)
                            height: Length::Px(76.0)
                            padding: Edges::all(SPACE_XS)
                            gap: 2.0
                            overflow: Overflow::Hidden
                            cursor: CursorIcon::Pointer
                            background: p.get_card()
                            border: (g.get_border_width(), p.get_border())
                            radius: g.get_radius_sm()
                        }
                        text {
                            style: {
                                width: Length::Percent(100.0)
                                font_size: 12.0
                                color: p.get_foreground()
                            }
                            { format!("{STRESS_POINTER_CARD_TITLE} #{idx:02}") }
                        }
                    }
                }
            }
        }
    });
    let wid: WindowId = app.get_window_state().get_id();
    for _ in 0..2usize {
        let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 480.0);
    }
    let mut accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let layout_before: LayoutTelemetry = app.last_frame_telemetry().get_layout_telemetry();
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    let mut hits: usize = 0;
    for step in 0..count {
        let px: f32 = 80.0 + ((step * 29) % 1120) as f32;
        let py: f32 = 40.0 + ((step * 17) % 640) as f32;
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(px, py)));
        let found: bool = app.get_scene().with_read(
            |tree: &SceneTree| hit_test(tree, Point::new(px, py)).is_some(),
            false,
        );
        let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 480.0);
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        if found {
            hits += 1;
        }
        let tel: FrameTelemetry = app.last_frame_telemetry();
        accum.record_frame(elapsed_us, alloc_delta);
        accum.record_frame_telemetry(&tel);
    }
    drop(alloc_guard);
    accum.set_layout_delta(
        layout_before,
        app.last_frame_telemetry().get_layout_telemetry(),
    );
    let latency: LatencyDistribution = accum.finish();
    let detail: String = format!(
        "1280x720 cards=40 hits={hits}/{count} jitter={:.1}us miss240={:.2}% miss360={:.2}% miss480={:.2}% fps={:.0} allocs={:.1}/f bytes={:.0}B/f",
        latency.get_jitter_us(),
        latency.get_missed_240hz_pct(),
        latency.get_missed_360hz_pct(),
        latency.get_missed_480hz_pct(),
        latency.get_effective_fps(),
        latency.get_mean_allocs_per_frame(),
        latency.get_mean_bytes_per_frame(),
    );
    StressMatrixEntry::new(STRESS_POINTER_MOVE_480HZ_NAME.to_string(), latency, detail)
}

/// Stress-tests 2D physics arena game scene at 240Hz+ interpolated cadence decoupled from 60Hz fixed simulation.
///
/// # Arguments
///
/// - `usize` - Number of 240Hz interpolated frames to measure.
///
/// # Returns
///
/// - `StressMatrixEntry` - Tail latencies (`p99.9`), jitter, 240/360/480Hz miss percentages, allocations, and effective FPS.
#[must_use]
pub fn stress_game2d_240hz_stability(iterations: usize) -> StressMatrixEntry {
    reset_reactive_runtime();
    let count: usize = iterations.max(1);
    let mut win: WindowConfig = WindowConfig::default();
    win.set_size(800, 520).set_render(RenderConfig::hardware());
    let mut cfg: AppConfig = AppConfig::default();
    cfg.set_window(win);
    let backend: Box<dyn PlatformBackend> = Box::new(
        HeadlessPlatform::emulating(PlatformKind::MacOs, 1.0, SafeAreaInsets::default())
            .with_refresh_rate_hz(240.0),
    );
    let Ok(mut app) = App::with_platform(cfg, backend) else {
        return StressMatrixEntry::new(
            STRESS_GAME2D_240HZ_NAME.to_string(),
            LatencyDistribution::default(),
            String::from(STRESS_INIT_FAILED),
        );
    };
    app.set_telemetry_enabled(true);
    let host: GameEngineHost = GameEngineHost::new(BenchGame2dScene::new_arena(), 1.0 / 60.0);
    app.attach_game_host(host.clone());
    let mount_host: GameEngineHost = host.clone();
    let _: NodeId = app.mount(move || {
        mount_host.mount_viewport(
            Style::default()
                .width(Length::Px(800.0))
                .height(Length::Px(520.0)),
        )
    });
    for _ in 0..8usize {
        let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
    }
    let mut accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let layout_before: LayoutTelemetry = app.last_frame_telemetry().get_layout_telemetry();
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    for _ in 0..count {
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        let tel: FrameTelemetry = app.last_frame_telemetry();
        accum.record_frame(elapsed_us, alloc_delta);
        accum.record_frame_telemetry(&tel);
    }
    drop(alloc_guard);
    accum.set_layout_delta(
        layout_before,
        app.last_frame_telemetry().get_layout_telemetry(),
    );
    let latency: LatencyDistribution = accum.finish();
    let detail: String = format!(
        "800x520 ent=40 jitter={:.1}us miss240={:.2}% miss360={:.2}% miss480={:.2}% fps={:.0} allocs={:.1}/f bytes={:.0}B/f",
        latency.get_jitter_us(),
        latency.get_missed_240hz_pct(),
        latency.get_missed_360hz_pct(),
        latency.get_missed_480hz_pct(),
        latency.get_effective_fps(),
        latency.get_mean_allocs_per_frame(),
        latency.get_mean_bytes_per_frame(),
    );
    StressMatrixEntry::new(STRESS_GAME2D_240HZ_NAME.to_string(), latency, detail)
}

/// Stress-tests sustained animated 2D game physics + HUD + `FramePacingController` at 480Hz cadence.
///
/// # Arguments
///
/// - `usize` - Number of 480Hz VSync-paced frames to measure.
///
/// # Returns
///
/// - `StressMatrixEntry` - Tail latencies (`p99.9`), 240/360/480Hz miss rates, pacing stats, and allocations.
#[must_use]
pub fn stress_game2d_480hz_pacing(iterations: usize) -> StressMatrixEntry {
    reset_reactive_runtime();
    let count: usize = iterations.max(1);
    let mut win: WindowConfig = WindowConfig::default();
    win.set_size(800, 520).set_render(RenderConfig::hardware());
    let mut cfg: AppConfig = AppConfig::default();
    cfg.set_window(win);
    let backend: Box<dyn PlatformBackend> = Box::new(
        HeadlessPlatform::emulating(PlatformKind::MacOs, 1.0, SafeAreaInsets::default())
            .with_refresh_rate_hz(480.0),
    );
    let Ok(mut app) = App::with_platform(cfg, backend) else {
        return StressMatrixEntry::new(
            STRESS_GAME2D_480HZ_PACING_NAME.to_string(),
            LatencyDistribution::default(),
            String::from(STRESS_INIT_FAILED),
        );
    };
    app.set_telemetry_enabled(true);
    let host: GameEngineHost = GameEngineHost::new(BenchGame2dScene::new_arena(), 1.0 / 60.0);
    app.attach_game_host(host.clone());
    let mount_host: GameEngineHost = host.clone();
    let _: NodeId = app.mount(move || {
        mount_host.mount_viewport(
            Style::default()
                .width(Length::Px(800.0))
                .height(Length::Px(520.0)),
        )
    });
    let mut pacing: FramePacingController = FramePacingController::new(480.0, true, None, 1);
    let mut ts_ns: u64 = STRESS_PERIOD_480HZ_NS;
    for _ in 0..16usize {
        let decision: PacingDecision = pacing.evaluate(FramePacingTrigger::Vsync, ts_ns);
        let _: Result<FrameStats, PlatformError> =
            app.step_game_frame(decision.get_sim_dt_secs().max(1.0 / 480.0));
        pacing.notify_present_completed();
        ts_ns = ts_ns.saturating_add(STRESS_PERIOD_480HZ_NS);
    }
    let mut accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let layout_before: LayoutTelemetry = app.last_frame_telemetry().get_layout_telemetry();
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    for _ in 0..count {
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        let decision: PacingDecision = pacing.evaluate(FramePacingTrigger::Vsync, ts_ns);
        if decision.get_should_step_sim() || decision.get_should_render() {
            let dt: f32 = decision.get_sim_dt_secs().max(1.0 / 480.0);
            let _: Result<FrameStats, PlatformError> = app.step_game_frame(dt);
            pacing.notify_present_completed();
        }
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        let tel: FrameTelemetry = app.last_frame_telemetry();
        accum.record_frame(elapsed_us, alloc_delta);
        accum.record_frame_telemetry(&tel);
        ts_ns = ts_ns.saturating_add(STRESS_PERIOD_480HZ_NS);
    }
    drop(alloc_guard);
    accum.set_layout_delta(
        layout_before,
        app.last_frame_telemetry().get_layout_telemetry(),
    );
    let latency: LatencyDistribution = accum.finish();
    let p_stats: FramePacingStats = pacing.get_stats();
    let detail: String = format!(
        "800x520 ent=40 paced480hz submitted={} missed_vsyncs={} jitter={:.1}us miss240={:.2}% miss360={:.2}% miss480={:.2}% fps={:.0} allocs={:.1}/f bytes={:.0}B/f",
        p_stats.get_frames_submitted(),
        p_stats.get_missed_vsync_intervals(),
        latency.get_jitter_us(),
        latency.get_missed_240hz_pct(),
        latency.get_missed_360hz_pct(),
        latency.get_missed_480hz_pct(),
        latency.get_effective_fps(),
        latency.get_mean_allocs_per_frame(),
        latency.get_mean_bytes_per_frame(),
    );
    StressMatrixEntry::new(STRESS_GAME2D_480HZ_PACING_NAME.to_string(), latency, detail)
}

/// Stress-tests 3D PBR + BVH ray-traced open-world scene at 240Hz interpolated cadence on the full-fidelity CPU reference path with bit-exact parity check.
///
/// # Arguments
///
/// - `usize` - Number of 240Hz interpolated 3D frames to measure.
///
/// # Returns
///
/// - `StressMatrixEntry` - Tail latencies (`p99.9`), jitter, 240/360/480Hz miss percentages, ray count, allocations, and parity flag.
#[must_use]
pub fn stress_game3d_240hz_stability(iterations: usize) -> StressMatrixEntry {
    let count: usize = iterations.max(1);
    let mut world: World3D = World3D::create_open_world_city();
    world.ensure_bvh();
    let mut renderer: Renderer3D = Renderer3D::default();
    let mut ref_renderer: Renderer3D = Renderer3D::default();
    let cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::Cinematic);
    let pool: RenderBufferPool = RenderBufferPool::with_capacity(3);
    let actions: ActionMap = ActionMap::default();
    let mut input: InputState = InputState::new();
    input.ingest(&WindowEvent::KeyDown(
        WindowId::new(1),
        KeyEvent::new(KeyCode::Character('w'), Modifiers::default(), false),
    ));
    let init_snap: World3DSnapshot =
        World3DSnapshot::capture(&world, 0, true, Vec::new(), Vec::new());
    let mut snapshots: DoubleBufferedSnapshot<World3DSnapshot> =
        DoubleBufferedSnapshot::new(init_snap);
    world.step_simulation(1.0 / 60.0, &input, &actions);
    world.ensure_bvh();
    snapshots.commit(World3DSnapshot::capture(
        &world,
        1,
        false,
        Vec::new(),
        Vec::new(),
    ));
    let mut display_list: DisplayList = DisplayList::default();
    let dst_rect: Rect = Rect::new(0.0, 0.0, 800.0, 450.0);
    pool.preallocate(800, 450);
    for warm_i in 1..=3u64 {
        display_list.reset(Size::new(800.0, 450.0), 1.0);
        if let Some(warm_lease) = renderer.render_world_interpolated_into_pool(
            &mut world,
            &snapshots,
            0.5,
            (800, 450),
            &cfg,
            (&pool, warm_i),
        ) {
            let mut game_ctx: GameRenderContext<'_> =
                GameRenderContext::new(dst_rect, &mut display_list);
            game_ctx.blit_pooled_frame(dst_rect, &warm_lease);
            warm_lease.submit_in_flight();
            let _: usize = pool.retire_fence(warm_i);
        }
    }
    let mut accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    let mut total_rays: usize = 0;
    let mut sim_ticks: u64 = 1;
    let mut fence_id: u64 = 3;
    for step in 0..count {
        if step.is_multiple_of(4) {
            sim_ticks += 1;
            world.step_simulation(1.0 / 60.0, &input, &actions);
            world.ensure_bvh();
            snapshots.capture_into(|dst: &mut World3DSnapshot| {
                dst.capture_into(&world, sim_ticks, false, &[], &[]);
            });
        }
        let alpha: f32 = ((step % 4) as f32) * 0.25;
        fence_id += 1;
        display_list.reset(Size::new(800.0, 450.0), 1.0);
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        let lease_opt: Option<PooledFrameLease> = renderer.render_world_interpolated_into_pool(
            &mut world,
            &snapshots,
            alpha,
            (800, 450),
            &cfg,
            (&pool, fence_id),
        );
        if let Some(lease) = lease_opt {
            let mut game_ctx: GameRenderContext<'_> =
                GameRenderContext::new(dst_rect, &mut display_list);
            game_ctx.blit_pooled_frame(dst_rect, &lease);
            lease.submit_in_flight();
            let _: usize = pool.retire_fence(fence_id);
        }
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        accum.record_frame(elapsed_us, alloc_delta);
        accum.record_paint_counts(display_list.len(), 800 * 450);
        total_rays += renderer.get_last_stats().get_rays_traced();
    }
    drop(alloc_guard);
    let mut ref_world: World3D = world.clone();
    let mut parity_renderer: Renderer3D = Renderer3D::default();
    let parity_ok: bool = match (
        parity_renderer.render_world_interpolated_into_pool(
            &mut world,
            &snapshots,
            0.5,
            (800, 450),
            &cfg,
            (&pool, fence_id + 1000),
        ),
        ref_renderer.render_world_interpolated_into_pool(
            &mut ref_world,
            &snapshots,
            0.5,
            (800, 450),
            &cfg,
            (&pool, fence_id + 1001),
        ),
    ) {
        (Some(la), Some(lb)) => {
            let eq: bool = la.as_slice() == lb.as_slice();
            la.release_now();
            lb.release_now();
            eq
        }
        _ => false,
    };
    let latency: LatencyDistribution = accum.finish();
    let pool_stats: RenderBufferPoolStats = pool.stats();
    let avg_rays: usize = total_rays / count;
    let detail: String = format!(
        "800x450 Cinematic+GI jitter={:.1}us miss240={:.2}% miss360={:.2}% miss480={:.2}% fps={:.0} rays={avg_rays} pool_reuse={} allocs={} frame_allocs={:.1}/f bytes={:.0}B/f parity={parity_ok}",
        latency.get_jitter_us(),
        latency.get_missed_240hz_pct(),
        latency.get_missed_360hz_pct(),
        latency.get_missed_480hz_pct(),
        latency.get_effective_fps(),
        pool_stats.get_reuse_hits(),
        pool_stats.get_backing_allocations(),
        latency.get_mean_allocs_per_frame(),
        latency.get_mean_bytes_per_frame(),
    );
    StressMatrixEntry::new(STRESS_GAME3D_240HZ_CPU_NAME.to_string(), latency, detail)
}

/// Stress-tests 3D game GPU direct-draw and `GpuCompositeTarget` HUD-overlay path at 240Hz/360Hz/480Hz with zero CPU RGBA upload bytes.
///
/// # Arguments
///
/// - `usize` - Number of high-refresh interpolated frames to measure.
///
/// # Returns
///
/// - `StressMatrixEntry` - Tail latencies (`p99.9`), jitter, 240/360/480Hz miss percentages, allocations, and zero-readback GPU telemetry.
#[must_use]
pub fn stress_game3d_240hz_stability_gpu(iterations: usize) -> StressMatrixEntry {
    reset_reactive_runtime();
    let count: usize = iterations.max(1);
    let mut win: WindowConfig = WindowConfig::default();
    win.set_size(800, 450)
        .set_render(RenderConfig::hardware_direct());
    let mut cfg: AppConfig = AppConfig::default();
    cfg.set_window(win);
    let backend: Box<dyn PlatformBackend> = Box::new(
        HeadlessPlatform::emulating(PlatformKind::MacOs, 1.0, SafeAreaInsets::default())
            .with_refresh_rate_hz(480.0),
    );
    let Ok(mut app) = App::with_platform(cfg, backend) else {
        return StressMatrixEntry::new(
            STRESS_GAME3D_240HZ_GPU_NAME.to_string(),
            LatencyDistribution::default(),
            String::from(STRESS_INIT_FAILED),
        );
    };
    app.set_telemetry_enabled(true);
    let host: GameEngineHost = GameEngineHost::new(BenchGame3dGpuScene::new_gpu_city(), 1.0 / 60.0);
    app.attach_game_host(host.clone());
    let mount_host: GameEngineHost = host.clone();
    let _: NodeId = app.mount(move || {
        mount_host.mount_viewport(
            Style::default()
                .width(Length::Px(800.0))
                .height(Length::Px(450.0)),
        )
    });
    let wid: WindowId = app.get_window_state().get_id();
    app.dispatch_window_event(WindowEvent::KeyDown(
        wid,
        KeyEvent::new(KeyCode::Character('w'), Modifiers::default(), false),
    ));
    for _ in 0..8usize {
        let _: Result<FrameStats, PlatformError> = app.step_game_frame(1.0 / 240.0);
    }
    let mut accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let layout_before: LayoutTelemetry = app.last_frame_telemetry().get_layout_telemetry();
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    let mut cpu_upload_bytes_total: usize = 0;
    let mut gpu_direct_frames: usize = 0;
    for _ in 0..count {
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        if let Ok(stats) = app.step_game_frame(1.0 / 240.0) {
            cpu_upload_bytes_total += stats.get_cpu_rgba_upload_bytes();
            if stats.get_gpu_direct_draw() {
                gpu_direct_frames += 1;
            }
        }
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        let tel: FrameTelemetry = app.last_frame_telemetry();
        accum.record_frame(elapsed_us, alloc_delta);
        accum.record_frame_telemetry(&tel);
    }
    drop(alloc_guard);
    accum.set_layout_delta(
        layout_before,
        app.last_frame_telemetry().get_layout_telemetry(),
    );
    let latency: LatencyDistribution = accum.finish();
    let detail: String = format!(
        "800x450 GpuDirectComposite [headless_simulation/submission_proxy] jitter={:.1}us miss240={:.2}% miss360={:.2}% miss480={:.2}% fps={:.0} cpu_rgba_bytes={cpu_upload_bytes_total} gpu_direct={gpu_direct_frames}/{count} allocs={:.1}/f bytes={:.0}B/f",
        latency.get_jitter_us(),
        latency.get_missed_240hz_pct(),
        latency.get_missed_360hz_pct(),
        latency.get_missed_480hz_pct(),
        latency.get_effective_fps(),
        latency.get_mean_allocs_per_frame(),
        latency.get_mean_bytes_per_frame(),
    );
    StressMatrixEntry::new(STRESS_GAME3D_240HZ_GPU_NAME.to_string(), latency, detail)
}

/// Stress-tests sustained animated 3D open-world city + HUD overlay + pooled blit + `FramePacingController` at 480Hz cadence.
///
/// # Arguments
///
/// - `usize` - Number of 480Hz VSync-paced 3D+HUD+blit frames to measure.
///
/// # Returns
///
/// - `StressMatrixEntry` - Tail latencies (`p99.9`), 240/360/480Hz miss rates, HUD/ray/pacing telemetry, and steady-state allocations.
#[must_use]
pub fn stress_game3d_480hz_city_hud_pacing(iterations: usize) -> StressMatrixEntry {
    let count: usize = iterations.max(1);
    let mut world: World3D = World3D::create_open_world_city();
    world.ensure_bvh();
    let mut renderer: Renderer3D = Renderer3D::default();
    let cfg: RenderQualityConfig = RenderQualityConfig::from_preset(QualityPreset::Cinematic);
    let pool: RenderBufferPool = RenderBufferPool::with_capacity(3);
    let actions: ActionMap = ActionMap::default();
    let mut input: InputState = InputState::new();
    let wid: WindowId = WindowId::new(1);
    input.ingest(&WindowEvent::KeyDown(
        wid,
        KeyEvent::new(KeyCode::Character('w'), Modifiers::default(), false),
    ));
    let init_snap: World3DSnapshot =
        World3DSnapshot::capture(&world, 0, true, Vec::new(), Vec::new());
    let mut snapshots: DoubleBufferedSnapshot<World3DSnapshot> =
        DoubleBufferedSnapshot::new(init_snap);
    world.step_simulation(1.0 / 60.0, &input, &actions);
    world.ensure_bvh();
    snapshots.commit(World3DSnapshot::capture(
        &world,
        1,
        false,
        Vec::new(),
        Vec::new(),
    ));
    let mut display_list: DisplayList = DisplayList::default();
    let dst_rect: Rect = Rect::new(0.0, 0.0, 800.0, 450.0);
    pool.preallocate(800, 450);
    let mut pacing: FramePacingController = FramePacingController::new(480.0, true, None, 2);
    let mut ts_ns: u64 = STRESS_PERIOD_480HZ_NS;
    let mut fence_id: u64 = 0;
    let mut hud_text_buf: String = String::with_capacity(96);
    for warm_i in 1..=4u64 {
        let _: PacingDecision = pacing.evaluate(FramePacingTrigger::Vsync, ts_ns);
        fence_id = warm_i;
        display_list.reset(Size::new(800.0, 450.0), 1.0);
        if let Some(warm_lease) = renderer.render_world_interpolated_into_pool(
            &mut world,
            &snapshots,
            0.5,
            (800, 450),
            &cfg,
            (&pool, fence_id),
        ) {
            let mut game_ctx: GameRenderContext<'_> =
                GameRenderContext::new(dst_rect, &mut display_list);
            game_ctx.blit_pooled_frame(dst_rect, &warm_lease);
            game_ctx.fill_rounded_rect(
                Rect::new(12.0, 12.0, 360.0, 28.0),
                Color::rgba(15, 23, 42, 215),
                6.0,
            );
            hud_text_buf.clear();
            let _: core::fmt::Result = write!(
                hud_text_buf,
                "{STRESS_GAME3D_HUD_PREFIX} | 480Hz Paced | a=0.500 | F0000"
            );
            game_ctx.draw_text_str(
                Point::new(20.0, 18.0),
                hud_text_buf.as_str(),
                12.0,
                Color::hex(0xE2E8F0),
            );
            warm_lease.submit_in_flight();
            let _: usize = pool.retire_fence(fence_id);
        }
        pacing.notify_present_completed();
        ts_ns = ts_ns.saturating_add(STRESS_PERIOD_480HZ_NS);
    }
    let mut accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(count);
    let alloc_guard: AllocationScopeGuard = AllocationScopeGuard::enter();
    let mut total_rays: usize = 0;
    let mut hud_cmds_total: usize = 0;
    let mut sim_ticks: u64 = 1;
    for step in 0..count {
        if step.is_multiple_of(8) {
            let phase: usize = (step / 24) % 4;
            match phase {
                0 => {
                    input.ingest(&WindowEvent::KeyUp(
                        wid,
                        KeyEvent::new(KeyCode::Character('d'), Modifiers::default(), false),
                    ));
                    input.ingest(&WindowEvent::KeyDown(
                        wid,
                        KeyEvent::new(KeyCode::Character('a'), Modifiers::default(), false),
                    ));
                }
                2 => {
                    input.ingest(&WindowEvent::KeyUp(
                        wid,
                        KeyEvent::new(KeyCode::Character('a'), Modifiers::default(), false),
                    ));
                    input.ingest(&WindowEvent::KeyDown(
                        wid,
                        KeyEvent::new(KeyCode::Character('d'), Modifiers::default(), false),
                    ));
                }
                _ => {
                    input.ingest(&WindowEvent::KeyUp(
                        wid,
                        KeyEvent::new(KeyCode::Character('a'), Modifiers::default(), false),
                    ));
                    input.ingest(&WindowEvent::KeyUp(
                        wid,
                        KeyEvent::new(KeyCode::Character('d'), Modifiers::default(), false),
                    ));
                }
            }
            sim_ticks += 1;
            world.step_simulation(1.0 / 60.0, &input, &actions);
            world.ensure_bvh();
            snapshots.capture_into(|dst: &mut World3DSnapshot| {
                dst.capture_into(&world, sim_ticks, false, &[], &[]);
            });
        }
        let alpha: f32 = ((step % 8) as f32) * 0.125;
        fence_id += 1;
        display_list.reset(Size::new(800.0, 450.0), 1.0);
        let alloc_before: RawAllocCounters = snapshot_raw_alloc_counters();
        let started: Instant = Instant::now();
        let decision: PacingDecision = pacing.evaluate(FramePacingTrigger::Vsync, ts_ns);
        if decision.get_should_render() {
            let lease_opt: Option<PooledFrameLease> = renderer.render_world_interpolated_into_pool(
                &mut world,
                &snapshots,
                alpha,
                (800, 450),
                &cfg,
                (&pool, fence_id),
            );
            if let Some(lease) = lease_opt {
                let mut game_ctx: GameRenderContext<'_> =
                    GameRenderContext::new(dst_rect, &mut display_list);
                game_ctx.blit_pooled_frame(dst_rect, &lease);
                game_ctx.fill_rounded_rect(
                    Rect::new(12.0, 12.0, 360.0, 28.0),
                    Color::rgba(15, 23, 42, 215),
                    6.0,
                );
                hud_text_buf.clear();
                let _: core::fmt::Result = write!(
                    hud_text_buf,
                    "{STRESS_GAME3D_HUD_PREFIX} | 480Hz Paced | a={alpha:.3} | F{step}"
                );
                game_ctx.draw_text_str(
                    Point::new(20.0, 18.0),
                    hud_text_buf.as_str(),
                    12.0,
                    Color::hex(0xE2E8F0),
                );
                lease.submit_in_flight();
                let _: usize = pool.retire_fence(fence_id);
            }
            pacing.notify_present_completed();
        }
        let elapsed_us: f64 = (started.elapsed().as_nanos() as f64) / 1_000.0;
        let alloc_delta: AllocationSnapshot =
            snapshot_raw_alloc_counters().delta_since(alloc_before);
        accum.record_frame(elapsed_us, alloc_delta);
        hud_cmds_total += display_list.len();
        accum.record_paint_counts(display_list.len(), 800 * 450);
        total_rays += renderer.get_last_stats().get_rays_traced();
        ts_ns = ts_ns.saturating_add(STRESS_PERIOD_480HZ_NS);
    }
    drop(alloc_guard);
    let latency: LatencyDistribution = accum.finish();
    let pool_stats: RenderBufferPoolStats = pool.stats();
    let p_stats: FramePacingStats = pacing.get_stats();
    let avg_rays: usize = total_rays / count;
    let detail: String = format!(
        "800x450 City+HUD+Blit+Pacing480Hz submitted={} missed_vsyncs={} rays={avg_rays} hud_cmds={hud_cmds_total} pool_reuse={} jitter={:.1}us miss240={:.2}% miss360={:.2}% miss480={:.2}% fps={:.0} allocs={:.1}/f bytes={:.0}B/f",
        p_stats.get_frames_submitted(),
        p_stats.get_missed_vsync_intervals(),
        pool_stats.get_reuse_hits(),
        latency.get_jitter_us(),
        latency.get_missed_240hz_pct(),
        latency.get_missed_360hz_pct(),
        latency.get_missed_480hz_pct(),
        latency.get_effective_fps(),
        latency.get_mean_allocs_per_frame(),
        latency.get_mean_bytes_per_frame(),
    );
    StressMatrixEntry::new(
        STRESS_GAME3D_480HZ_CITY_HUD_NAME.to_string(),
        latency,
        detail,
    )
}

/// Runs the stage-attributed cold-start TTFF benchmark as a stress-matrix entry and structured stage report.
///
/// # Arguments
///
/// - `usize` - Number of independent cold-start iterations to execute.
///
/// # Returns
///
/// - `(StressMatrixEntry, ColdStartTtffReport)` - Matrix entry and complete per-stage TTFF report.
#[must_use]
pub fn stress_cold_start_ttff(iterations: usize) -> (StressMatrixEntry, ColdStartTtffReport) {
    let report: ColdStartTtffReport = run_cold_start_ttff_report(iterations);
    let mut accum: FrameMeasureAccum = FrameMeasureAccum::with_capacity(report.get_iterations());
    for run in report.get_runs().iter() {
        let total_us: f64 = run.get_total_ttff_ms() * 1_000.0;
        let alloc_snap: AllocationSnapshot = AllocationSnapshot::new(
            run.get_alloc_count(),
            0,
            run.get_bytes_allocated(),
            0,
            0,
            0,
            run.get_bytes_allocated(),
        );
        accum.record_frame(total_us, alloc_snap);
        accum.record_paint_counts(run.get_paint_commands(), 0);
    }
    let latency: LatencyDistribution = accum.finish();
    let med: ColdStartTtffStages = report.get_median();
    let detail: String = format!(
        "1280x720 init={:.2}ms font={:.2}ms mount={:.2}ms layout={:.2}ms paint={:.2}ms present={:.2}ms total_p50={:.2}ms total_p95={:.2}ms nodes={} cmds={} batches={} allocs={} bytes={}",
        med.get_app_renderer_init_ms(),
        med.get_font_ready_ms(),
        med.get_initial_mount_ms(),
        med.get_first_layout_ms(),
        med.get_first_paint_ms(),
        med.get_first_present_ms(),
        med.get_total_ttff_ms(),
        report.get_p95_total_ttff_ms(),
        med.get_layout_nodes(),
        med.get_paint_commands(),
        med.get_draw_batches(),
        med.get_alloc_count(),
        med.get_bytes_allocated(),
    );
    let entry: StressMatrixEntry =
        StressMatrixEntry::new(STRESS_COLD_START_TTFF_NAME.to_string(), latency, detail);
    (entry, report)
}

/// Runs all §03/§08 stress-test verification matrix scenarios with default production iteration counts.
///
/// # Returns
///
/// - `StressMatrixReport` - Complete tail-latency, 240/360/480Hz, allocation, TTFF, and A/B parity verification report.
#[must_use]
pub fn run_stress_matrix() -> StressMatrixReport {
    run_filtered_stress_matrix(None)
}

/// Returns `true` when `name` matches optional substring `filter`.
///
/// # Arguments
///
/// - `&str` - Canonical scenario identifier.
/// - `Option<&str>` - Optional substring filter.
///
/// # Returns
///
/// - `bool` - Whether the scenario should execute.
#[must_use]
fn matches_stress_filter(name: &str, filter: Option<&str>) -> bool {
    filter
        .map(|substr: &str| name.contains(substr))
        .unwrap_or(true)
}

/// Runs §03/§08 stress-test verification matrix scenarios whose canonical names contain `filter` (or all scenarios when `None`).
///
/// # Arguments
///
/// - `Option<&str>` - Optional substring filter matching scenario names.
///
/// # Returns
///
/// - `StressMatrixReport` - Filtered tail-latency, allocation, TTFF, and A/B parity verification report.
#[must_use]
pub fn run_filtered_stress_matrix(filter: Option<&str>) -> StressMatrixReport {
    let mut entries: Vec<StressMatrixEntry> = Vec::with_capacity(13);
    let mut partial_damage_ab: Option<PartialDamageAbSummary> = None;
    let mut cold_start_ttff: Option<ColdStartTtffReport> = None;
    if matches_stress_filter(STRESS_PARTIAL_ROW_AB_NAME, filter) {
        let (entry, summary): (StressMatrixEntry, PartialDamageAbSummary) =
            stress_partial_single_row_update_ab(STRESS_PARTIAL_DEFAULT_ITERS);
        entries.push(entry);
        partial_damage_ab = Some(summary);
    }
    if matches_stress_filter(STRESS_VIRTUAL_LIST_TAIL_NAME, filter) {
        entries.push(stress_virtual_list_scroll_tail(
            STRESS_VLIST_TAIL_DEFAULT_ITERS,
        ));
    }
    if matches_stress_filter(STRESS_WINDOW_RESIZE_NAME, filter) {
        entries.push(stress_window_resize_reflow(STRESS_RESIZE_DEFAULT_ITERS));
    }
    if matches_stress_filter(STRESS_TERMINAL_TUI_DIFF_NAME, filter) {
        entries.push(stress_terminal_tui_diff(STRESS_TERMINAL_DEFAULT_ITERS));
    }
    if matches_stress_filter(STRESS_SCROLL_240HZ_NAME, filter) {
        entries.push(stress_scroll_240hz_stability(
            STRESS_SCROLL_240HZ_DEFAULT_ITERS,
        ));
    }
    if matches_stress_filter(STRESS_IDLE_ANIM_480HZ_NAME, filter) {
        entries.push(stress_idle_anim_480hz_stability(
            STRESS_IDLE_ANIM_480HZ_DEFAULT_ITERS,
        ));
    }
    if matches_stress_filter(STRESS_POINTER_MOVE_480HZ_NAME, filter) {
        entries.push(stress_pointer_move_480hz_stability(
            STRESS_POINTER_MOVE_480HZ_DEFAULT_ITERS,
        ));
    }
    if matches_stress_filter(STRESS_GAME2D_240HZ_NAME, filter) {
        entries.push(stress_game2d_240hz_stability(
            STRESS_GAME2D_240HZ_DEFAULT_ITERS,
        ));
    }
    if matches_stress_filter(STRESS_GAME2D_480HZ_PACING_NAME, filter) {
        entries.push(stress_game2d_480hz_pacing(
            STRESS_GAME2D_480HZ_PACING_DEFAULT_ITERS,
        ));
    }
    if matches_stress_filter(STRESS_GAME3D_240HZ_CPU_NAME, filter) {
        entries.push(stress_game3d_240hz_stability(
            STRESS_GAME3D_240HZ_CPU_DEFAULT_ITERS,
        ));
    }
    if matches_stress_filter(STRESS_GAME3D_240HZ_GPU_NAME, filter) {
        entries.push(stress_game3d_240hz_stability_gpu(
            STRESS_GAME3D_240HZ_GPU_DEFAULT_ITERS,
        ));
    }
    if matches_stress_filter(STRESS_GAME3D_480HZ_CITY_HUD_NAME, filter) {
        entries.push(stress_game3d_480hz_city_hud_pacing(
            STRESS_GAME3D_480HZ_CITY_HUD_DEFAULT_ITERS,
        ));
    }
    if matches_stress_filter(STRESS_COLD_START_TTFF_NAME, filter) {
        let (entry, ttff): (StressMatrixEntry, ColdStartTtffReport) =
            stress_cold_start_ttff(STRESS_TTFF_DEFAULT_ITERS);
        entries.push(entry);
        cold_start_ttff = Some(ttff);
    }
    let mut report: StressMatrixReport = StressMatrixReport::new(entries, partial_damage_ab);
    if let Some(ttff) = cold_start_ttff {
        report = report.with_cold_start_ttff(ttff);
    }
    report
}

/// Formats a `StressMatrixReport` into a human-readable terminal table showing tail percentiles (`p99.9`), 240/360/480Hz budgets, allocations, TTFF, and A/B parity.
///
/// # Arguments
///
/// - `&StressMatrixReport` - Completed stress-matrix report.
///
/// # Returns
///
/// - `String` - Aligned human-readable summary table.
#[must_use]
pub fn format_stress_matrix_report(report: &StressMatrixReport) -> String {
    let mut out: String = String::from(STRESS_REPORT_HEADER);
    for entry in report.get_entries().iter() {
        let lat: LatencyDistribution = entry.get_latency();
        out.push_str(&format!(
            "{:36} n={:4} p50={:8.1}us p95={:8.1}us p99={:8.1}us p99.9={:8.1}us max={:8.1}us >2.08ms={:3} >2.78ms={:3} >4.17ms={:3} >6.94ms={:3} >16.67ms={:3} allocs={:6.1}/f ({:8.0}B/f)  {}\n",
            entry.get_name(),
            lat.get_iterations(),
            lat.get_p50_us(),
            lat.get_p95_us(),
            lat.get_p99_us(),
            lat.get_p99_9_us(),
            lat.get_max_us(),
            lat.get_over_2_08ms_count(),
            lat.get_over_2_78ms_count(),
            lat.get_over_4_17ms_count(),
            lat.get_over_6_94ms_count(),
            lat.get_over_16_67ms_count(),
            lat.get_mean_allocs_per_frame(),
            lat.get_mean_bytes_per_frame(),
            entry.get_detail(),
        ));
    }
    if let Some(ab) = report.partial_damage_ab() {
        let base: LatencyDistribution = ab.get_baseline_full_redraw();
        let cand: LatencyDistribution = ab.get_candidate_partial_damage();
        out.push_str(&format!(
            "\nA/B Partial-Layout Damage Parity ({})\n  full_redraw:    p50={:8.1}us p95={:8.1}us p99={:8.1}us p99.9={:8.1}us dirty={:.4} full_redraws={} allocs={:.1}/f\n  partial_damage: p50={:8.1}us p95={:8.1}us p99={:8.1}us p99.9={:8.1}us dirty={:.4} full_redraws={} allocs={:.1}/f\n  delta:          p50={:+.1}% p95={:+.1}% p99={:+.1}% dirty_drop={:+.1}% bit_exact_parity={} steps={}\n",
            ab.get_name(),
            base.get_p50_us(),
            base.get_p95_us(),
            base.get_p99_us(),
            base.get_p99_9_us(),
            base.get_mean_dirty_area_ratio(),
            base.get_full_redraw_count(),
            base.get_mean_allocs_per_frame(),
            cand.get_p50_us(),
            cand.get_p95_us(),
            cand.get_p99_us(),
            cand.get_p99_9_us(),
            cand.get_mean_dirty_area_ratio(),
            cand.get_full_redraw_count(),
            cand.get_mean_allocs_per_frame(),
            ab.get_p50_speedup_pct(),
            ab.get_p95_speedup_pct(),
            ab.get_p99_speedup_pct(),
            ab.get_dirty_area_ratio_drop_pct(),
            ab.get_bit_exact_parity(),
            ab.get_verified_steps(),
        ));
    }
    if let Some(ttff) = report.cold_start_ttff() {
        out.push('\n');
        out.push_str(&format_cold_start_ttff_report(ttff));
    }
    out
}

/// Serializes a `StressMatrixReport` to pretty-printed JSON.
///
/// # Arguments
///
/// - `&StressMatrixReport` - Completed stress-matrix report.
///
/// # Returns
///
/// - `String` - Pretty-printed JSON payload.
#[must_use]
pub fn stress_matrix_to_json(report: &StressMatrixReport) -> String {
    to_string_pretty(report).unwrap_or_default()
}