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
use super::*;
/// Wire-label and mode conversion helpers for `RenderBackendCandidate`.
impl RenderBackendCandidate {
/// Returns the canonical snake_case wire label for this candidate.
///
/// # Arguments
///
/// - `&Self` - Candidate reference.
///
/// # Returns
///
/// - `&'static str` - Canonical candidate label.
#[must_use]
pub const fn as_str(&self) -> &'static str {
match *self {
Self::GpuDirect => CANDIDATE_LABEL_GPU_DIRECT,
Self::GpuUpload => CANDIDATE_LABEL_GPU_UPLOAD,
Self::Hybrid => CANDIDATE_LABEL_HYBRID,
Self::Software => CANDIDATE_LABEL_SOFTWARE,
Self::Terminal => CANDIDATE_LABEL_TERMINAL,
}
}
/// Maps this adaptive candidate to the corresponding concrete `RenderMode`.
///
/// # Arguments
///
/// - `&Self` - Candidate reference.
///
/// # Returns
///
/// - `RenderMode` - Concrete render mode.
#[must_use]
pub const fn to_render_mode(&self) -> RenderMode {
match *self {
Self::GpuDirect | Self::GpuUpload => RenderMode::Hardware,
Self::Hybrid => RenderMode::Hybrid,
Self::Software | Self::Terminal => RenderMode::Software,
}
}
/// Returns `true` when this candidate executes direct GPU rendering with zero CPU mirror.
///
/// # Arguments
///
/// - `&Self` - Candidate reference.
///
/// # Returns
///
/// - `bool` - `true` only for `GpuDirect`.
#[must_use]
pub const fn is_direct_gpu(&self) -> bool {
matches!(*self, Self::GpuDirect)
}
}
/// Wire-label helpers for `AdaptiveSwitchMode`.
impl AdaptiveSwitchMode {
/// Returns the canonical snake_case wire label for this rollout switch mode.
///
/// # Arguments
///
/// - `&Self` - Switch mode reference.
///
/// # Returns
///
/// - `&'static str` - Canonical switch mode label.
#[must_use]
pub const fn as_str(&self) -> &'static str {
match *self {
Self::RecommendOnly => SWITCH_MODE_RECOMMEND_ONLY,
Self::AutoSwitch => SWITCH_MODE_AUTO_SWITCH,
}
}
}
/// Wire-label helpers for `FaultEventKind`.
impl FaultEventKind {
/// Returns the canonical snake_case wire label for this fault kind.
///
/// # Arguments
///
/// - `&Self` - Fault kind reference.
///
/// # Returns
///
/// - `&'static str` - Canonical fault label.
#[must_use]
pub const fn as_str(&self) -> &'static str {
match *self {
Self::DeviceLost => FAULT_LABEL_DEVICE_LOST,
Self::SurfaceDestroyed => FAULT_LABEL_SURFACE_DESTROYED,
Self::DriverSuspended => FAULT_LABEL_DRIVER_SUSPENDED,
Self::ThermalThrottled => FAULT_LABEL_THERMAL_THROTTLED,
}
}
}
/// Default strict baseline requiring full visual equivalence across every quality invariant.
impl Default for VisualEquivalenceContract {
/// Creates the canonical strict visual-equivalence contract with all invariants enabled.
///
/// # Returns
///
/// - `Self` - Strict visual-equivalence baseline.
fn default() -> Self {
Self::strict()
}
}
/// Strict contract constructors and equivalence checks for `VisualEquivalenceContract`.
impl VisualEquivalenceContract {
/// Creates a visual-equivalence contract where fonts, layout, color, AA, shadow, blur, visible tiles, and media quality are all invariant.
///
/// # Returns
///
/// - `Self` - Strict visual-equivalence contract.
#[must_use]
pub const fn strict() -> Self {
Self {
fonts_identical: true,
layout_identical: true,
color_identical: true,
antialiasing_identical: true,
shadows_identical: true,
blur_identical: true,
visible_tiles_identical: true,
media_quality_identical: true,
}
}
/// Validates that `candidate` satisfies every invariant required by `self`.
///
/// # Arguments
///
/// - `&Self` - Required baseline contract.
/// - `&Self` - Candidate visual contract.
///
/// # Returns
///
/// - `Result<(), VisualEquivalenceFailure>` - `Ok(())` when visually equivalent, or the first violated invariant.
pub const fn check_equivalence(
&self,
candidate: &Self,
) -> Result<(), VisualEquivalenceFailure> {
let Self {
fonts_identical,
layout_identical,
color_identical,
antialiasing_identical,
shadows_identical,
blur_identical,
visible_tiles_identical,
media_quality_identical,
} = *self;
if fonts_identical && !candidate.fonts_identical {
return Err(VisualEquivalenceFailure::FontMismatch);
}
if layout_identical && !candidate.layout_identical {
return Err(VisualEquivalenceFailure::LayoutMismatch);
}
if color_identical && !candidate.color_identical {
return Err(VisualEquivalenceFailure::ColorSpaceMismatch);
}
if antialiasing_identical && !candidate.antialiasing_identical {
return Err(VisualEquivalenceFailure::AntialiasingMismatch);
}
if shadows_identical && !candidate.shadows_identical {
return Err(VisualEquivalenceFailure::ShadowMismatch);
}
if blur_identical && !candidate.blur_identical {
return Err(VisualEquivalenceFailure::BackdropBlurMismatch);
}
if visible_tiles_identical && !candidate.visible_tiles_identical {
return Err(VisualEquivalenceFailure::VisibleTileMismatch);
}
if media_quality_identical && !candidate.media_quality_identical {
return Err(VisualEquivalenceFailure::MediaQualityMismatch);
}
Ok(())
}
/// Returns `true` when `candidate` satisfies all required visual invariants.
///
/// # Arguments
///
/// - `&Self` - Required baseline contract.
/// - `&Self` - Candidate visual contract.
///
/// # Returns
///
/// - `bool` - `true` when visually equivalent.
#[must_use]
pub const fn is_equivalent(&self, candidate: &Self) -> bool {
self.check_equivalence(candidate).is_ok()
}
}
/// Constructors and gate checks for `CandidateCapabilities`.
impl CandidateCapabilities {
/// Creates a supported visually-equivalent candidate capability declaration.
///
/// # Arguments
///
/// - `RenderBackendCandidate` - Candidate kind.
/// - `GraphicsBackend` - Underlying graphics backend.
/// - `bool` - Whether warmup work must execute on UI/render thread.
///
/// # Returns
///
/// - `Self` - Verified visually-equivalent candidate capabilities.
#[must_use]
pub const fn supported_equivalent(
candidate: RenderBackendCandidate,
graphics_backend: GraphicsBackend,
requires_ui_thread_warmup: bool,
) -> Self {
Self {
candidate,
supported: true,
visual_contract: VisualEquivalenceContract::strict(),
requires_ui_thread_warmup,
is_simulated_profile: false,
direct_gpu_verified_on_device: matches!(candidate, RenderBackendCandidate::GpuDirect),
graphics_backend,
}
}
/// Evaluates whether this candidate passes platform support, device honesty, and visual-equivalence gates.
///
/// # Arguments
///
/// - `&Self` - Candidate capability record.
/// - `&VisualEquivalenceContract` - Required baseline contract.
///
/// # Returns
///
/// - `Result<(), VisualEquivalenceFailure>` - `Ok(())` when eligible, or exact disqualification reason.
pub fn passes_gate(
&self,
baseline: &VisualEquivalenceContract,
) -> Result<(), VisualEquivalenceFailure> {
if !self.get_supported() {
return Err(VisualEquivalenceFailure::BackendUnsupported);
}
if self.get_candidate() == RenderBackendCandidate::GpuDirect
&& self.get_is_simulated_profile()
&& !self.get_direct_gpu_verified_on_device()
{
return Err(VisualEquivalenceFailure::UnverifiedSimulatedGpu);
}
let contract: VisualEquivalenceContract = self.get_visual_contract();
baseline.check_equivalence(&contract)
}
}
/// Default host capability profile for headless software execution.
impl Default for HostCapabilityProfile {
/// Creates a deterministic single-channel software host profile.
///
/// # Returns
///
/// - `Self` - Default headless host profile.
fn default() -> Self {
Self::from_platform(
PlatformKind::Headless,
PlatformCapabilities::for_platform(PlatformKind::Headless),
)
}
}
/// Platform capability synthesis and gate helpers for `HostCapabilityProfile`.
impl HostCapabilityProfile {
/// Builds a truthful `HostCapabilityProfile` from `platform` and `capabilities`.
///
/// # Arguments
///
/// - `PlatformKind` - Target execution platform.
/// - `PlatformCapabilities` - Reported hardware capabilities.
///
/// # Returns
///
/// - `Self` - Host capability profile with visual-equivalence baseline.
#[must_use]
pub fn from_platform(platform: PlatformKind, capabilities: PlatformCapabilities) -> Self {
let baseline_contract: VisualEquivalenceContract = VisualEquivalenceContract::strict();
if matches!(
platform,
PlatformKind::Terminal
| PlatformKind::TerminalCli
| PlatformKind::MiniApp
| PlatformKind::QuickApp
) {
let (cand, backend): (RenderBackendCandidate, GraphicsBackend) =
if matches!(platform, PlatformKind::Terminal | PlatformKind::TerminalCli) {
(RenderBackendCandidate::Terminal, GraphicsBackend::Headless)
} else {
(RenderBackendCandidate::Software, GraphicsBackend::Canvas2d)
};
return Self {
platform,
candidates: vec![CandidateCapabilities::supported_equivalent(
cand, backend, true,
)],
single_channel_only: true,
baseline_contract,
};
}
let default_gpu: GraphicsBackend = platform.default_graphics_backend();
let sw_backend: GraphicsBackend = if platform == PlatformKind::Web {
GraphicsBackend::Canvas2d
} else {
GraphicsBackend::SoftwareCpu
};
let mut candidates: Vec<CandidateCapabilities> = Vec::new();
if capabilities.get_hardware_gpu() {
let ui_thread_req: bool = matches!(
platform,
PlatformKind::Web | PlatformKind::MacOs | PlatformKind::Ios | PlatformKind::IpadOs
);
candidates.push(CandidateCapabilities::supported_equivalent(
RenderBackendCandidate::GpuDirect,
default_gpu,
ui_thread_req,
));
candidates.push(CandidateCapabilities::supported_equivalent(
RenderBackendCandidate::GpuUpload,
default_gpu,
ui_thread_req,
));
candidates.push(CandidateCapabilities::supported_equivalent(
RenderBackendCandidate::Hybrid,
default_gpu,
ui_thread_req,
));
}
candidates.push(CandidateCapabilities::supported_equivalent(
RenderBackendCandidate::Software,
sw_backend,
false,
));
let single_channel_only: bool = candidates.len() <= 1;
Self {
platform,
candidates,
single_channel_only,
baseline_contract,
}
}
/// Creates a single-channel host profile locked strictly to `candidate` with probing permanently disabled.
///
/// # Arguments
///
/// - `PlatformKind` - Target platform.
/// - `RenderBackendCandidate` - Sole supported channel.
/// - `GraphicsBackend` - Graphics backend bound to that channel.
///
/// # Returns
///
/// - `Self` - Single-channel locked profile.
#[must_use]
pub fn single_channel(
platform: PlatformKind,
candidate: RenderBackendCandidate,
backend: GraphicsBackend,
) -> Self {
Self {
platform,
candidates: vec![CandidateCapabilities::supported_equivalent(
candidate, backend, true,
)],
single_channel_only: true,
baseline_contract: VisualEquivalenceContract::strict(),
}
}
/// Converts host-declared `HostChannelCapabilities` (HarmonyOS, Wearables, MiniApps, QuickApps) into a unified `HostCapabilityProfile` enforcing single-channel locking and simulated-profile honesty.
///
/// # Arguments
///
/// - `PlatformKind` - Target execution platform.
/// - `&HostChannelCapabilities` - Host-declared channel capability matrix.
///
/// # Returns
///
/// - `Self` - Unified capability profile ready for `AdaptiveRenderRouter`.
#[must_use]
pub fn from_host_channel_capabilities(
platform: PlatformKind,
caps: &HostChannelCapabilities,
) -> Self {
let gate: HostVisualEquivalenceGate = caps.get_visual_equivalence();
let visual_contract: VisualEquivalenceContract = VisualEquivalenceContract {
fonts_identical: gate.get_fonts_equivalent(),
layout_identical: gate.get_layout_equivalent(),
color_identical: gate.get_color_equivalent(),
antialiasing_identical: gate.get_aa_equivalent(),
shadows_identical: gate.get_shadow_equivalent(),
blur_identical: gate.get_blur_equivalent(),
visible_tiles_identical: gate.get_visible_tiles_equivalent(),
media_quality_identical: gate.get_media_quality_equivalent(),
};
let is_sim: bool = caps.get_simulated_profile();
let verified_gpu: bool = !is_sim && caps.get_direct_gpu_verified_on_device();
let default_gpu: GraphicsBackend = platform.default_graphics_backend();
let mut candidates: Vec<CandidateCapabilities> = Vec::new();
for channel in caps.get_supported_channels() {
let (candidate, graphics_backend): (RenderBackendCandidate, GraphicsBackend) =
match *channel {
HostRenderChannel::GpuDirect => {
(RenderBackendCandidate::GpuDirect, default_gpu)
}
HostRenderChannel::GpuUpload => {
(RenderBackendCandidate::GpuUpload, default_gpu)
}
HostRenderChannel::SoftwareBuffer => (
RenderBackendCandidate::Software,
GraphicsBackend::SoftwareCpu,
),
HostRenderChannel::Canvas2d => {
(RenderBackendCandidate::Software, GraphicsBackend::Canvas2d)
}
HostRenderChannel::WebGl | HostRenderChannel::WebGl2 => {
(RenderBackendCandidate::GpuUpload, GraphicsBackend::WebGl2)
}
};
let direct_verified: bool =
candidate == RenderBackendCandidate::GpuDirect && verified_gpu;
candidates.push(CandidateCapabilities {
candidate,
supported: true,
visual_contract,
requires_ui_thread_warmup: true,
is_simulated_profile: is_sim,
direct_gpu_verified_on_device: direct_verified,
graphics_backend,
});
}
let single_channel_only: bool = caps.get_supported_channels().len() <= 1;
Self {
platform,
candidates,
single_channel_only,
baseline_contract: VisualEquivalenceContract::strict(),
}
}
/// Returns `true` when this host exposes at most one eligible rendering channel and MUST NOT probe others.
///
/// # Arguments
///
/// - `&Self` - Host profile reference.
///
/// # Returns
///
/// - `bool` - `true` for single-channel hosts.
#[must_use]
pub fn is_single_channel(&self) -> bool {
if self.get_single_channel_only() {
return true;
}
let eligible: usize = self
.get_candidates()
.iter()
.filter(|cap: &&CandidateCapabilities| {
cap.passes_gate(&self.get_baseline_contract()).is_ok()
})
.count();
eligible <= 1
}
/// Evaluates whether `candidate` passes this host's capability and visual-equivalence gate.
///
/// # Arguments
///
/// - `&Self` - Host profile reference.
/// - `RenderBackendCandidate` - Candidate to verify.
///
/// # Returns
///
/// - `Result<(), VisualEquivalenceFailure>` - `Ok(())` if eligible, or exact failure reason.
pub fn candidate_passes_gate(
&self,
candidate: RenderBackendCandidate,
) -> Result<(), VisualEquivalenceFailure> {
let baseline: VisualEquivalenceContract = self.get_baseline_contract();
let found: Option<&CandidateCapabilities> = self
.get_candidates()
.iter()
.find(|cap: &&CandidateCapabilities| cap.get_candidate() == candidate);
match found {
Some(cap) => cap.passes_gate(&baseline),
None => Err(VisualEquivalenceFailure::BackendUnsupported),
}
}
/// Returns the first eligible visually-equivalent candidate matching priority order (`GpuDirect` first, excluding `exclude`).
///
/// # Arguments
///
/// - `&Self` - Host profile reference.
/// - `Option<RenderBackendCandidate>` - Optional candidate to skip (e.g., a failed startup or faulted backend).
///
/// # Returns
///
/// - `RenderBackendCandidate` - Highest-priority eligible fallback candidate.
#[must_use]
pub fn best_available_candidate(
&self,
exclude: Option<RenderBackendCandidate>,
) -> RenderBackendCandidate {
let priority: [RenderBackendCandidate; 5] = [
RenderBackendCandidate::GpuDirect,
RenderBackendCandidate::GpuUpload,
RenderBackendCandidate::Software,
RenderBackendCandidate::Hybrid,
RenderBackendCandidate::Terminal,
];
for cand in priority {
if Some(cand) == exclude {
continue;
}
if self.candidate_passes_gate(cand).is_ok() {
return cand;
}
}
if self.get_platform() == PlatformKind::Terminal {
RenderBackendCandidate::Terminal
} else {
RenderBackendCandidate::Software
}
}
/// Resolves the concrete `GraphicsBackend` declared for `candidate` on this host.
///
/// # Arguments
///
/// - `&Self` - Host profile reference.
/// - `RenderBackendCandidate` - Target candidate.
///
/// # Returns
///
/// - `GraphicsBackend` - Declared graphics backend.
#[must_use]
pub fn graphics_backend_for(&self, candidate: RenderBackendCandidate) -> GraphicsBackend {
if let Some(cap) = self
.get_candidates()
.iter()
.find(|cap: &&CandidateCapabilities| cap.get_candidate() == candidate)
{
return cap.get_graphics_backend();
}
match candidate {
RenderBackendCandidate::Software => GraphicsBackend::SoftwareCpu,
RenderBackendCandidate::Terminal => GraphicsBackend::Headless,
RenderBackendCandidate::GpuDirect
| RenderBackendCandidate::GpuUpload
| RenderBackendCandidate::Hybrid => self.get_platform().default_graphics_backend(),
}
}
}
/// Default bounded `WinnerCache`.
impl Default for WinnerCache {
/// Creates an empty `WinnerCache` with `DEFAULT_WINNER_CACHE_CAPACITY`.
///
/// # Returns
///
/// - `Self` - Empty bounded winner cache.
fn default() -> Self {
Self::with_capacity(DEFAULT_WINNER_CACHE_CAPACITY)
}
}
/// Lookup, recording, and environment invalidation helpers for `WinnerCache`.
impl WinnerCache {
/// Creates an empty `WinnerCache` retaining up to `max_entries` verified records.
///
/// # Arguments
///
/// - `usize` - Maximum entry capacity (clamped to `>= 1`).
///
/// # Returns
///
/// - `Self` - Empty bounded winner cache.
#[must_use]
pub fn with_capacity(max_entries: usize) -> Self {
let cap: usize = max_entries.max(1);
Self {
entries: HashMap::with_capacity(cap),
max_entries: cap,
}
}
/// Looks up a previously verified startup winner matching exact `(device_id, driver_version, display_mode_hz, build_id, scene_profile)`.
///
/// # Arguments
///
/// - `&Self` - Cache reference.
/// - `&WinnerCacheKey` - Composite environment and scene key.
///
/// # Returns
///
/// - `Option<WinnerCacheEntry>` - Cached verified winner if present.
#[must_use]
pub fn lookup(&self, key: &WinnerCacheKey) -> Option<WinnerCacheEntry> {
self.get_entries().get(key).copied()
}
/// Stores a verified winner entry, evicting the oldest record if the cache is full.
///
/// # Arguments
///
/// - `&Self` - Mutable cache reference.
/// - `WinnerCacheKey` - Composite environment and scene key.
/// - `WinnerCacheEntry` - Verified winner metrics.
pub fn record(&mut self, key: WinnerCacheKey, entry: WinnerCacheEntry) {
let limit: usize = self.get_max_entries();
if !self.get_entries().contains_key(&key) && self.get_entries().len() >= limit {
let oldest_key: Option<WinnerCacheKey> = self
.get_entries()
.iter()
.min_by_key(|(_, val): &(&WinnerCacheKey, &WinnerCacheEntry)| {
val.get_verified_at_ms()
})
.map(|(k, _): (&WinnerCacheKey, &WinnerCacheEntry)| k.clone());
if let Some(evict) = oldest_key {
let _: Option<WinnerCacheEntry> = self.get_mut_entries().remove(&evict);
}
}
let _: Option<WinnerCacheEntry> = self.get_mut_entries().insert(key, entry);
}
/// Invalidates every cached entry for `device_id` whose driver version, display mode, or build ID no longer matches.
///
/// # Arguments
///
/// - `&Self` - Mutable cache reference.
/// - `&str` - Active device identifier.
/// - `&str` - Current graphics driver version.
/// - `u32` - Current display mode in millihertz.
/// - `&str` - Current build identifier.
///
/// # Returns
///
/// - `usize` - Number of invalidated stale entries removed.
pub fn invalidate_stale_environment(
&mut self,
device_id: &str,
driver_version: &str,
display_mode_hz_millihz: u32,
build_id: &str,
) -> usize {
let before: usize = self.get_entries().len();
self.get_mut_entries()
.retain(|k: &WinnerCacheKey, _: &mut WinnerCacheEntry| {
if k.get_device_id().as_str() != device_id {
return true;
}
k.get_driver_version().as_str() == driver_version
&& k.get_display_mode_hz_millihz() == display_mode_hz_millihz
&& k.get_build_id().as_str() == build_id
});
before.saturating_sub(self.get_entries().len())
}
/// Returns the number of cached verified winner entries.
///
/// # Arguments
///
/// - `&Self` - Cache reference.
///
/// # Returns
///
/// - `usize` - Entry count.
#[must_use]
pub fn len(&self) -> usize {
self.get_entries().len()
}
/// Returns `true` when no verified winners are cached.
///
/// # Arguments
///
/// - `&Self` - Cache reference.
///
/// # Returns
///
/// - `bool` - `true` when empty.
#[must_use]
pub fn is_empty(&self) -> bool {
self.get_entries().is_empty()
}
}
/// Default pre-allocated `BoundedTelemetryQueue`.
impl Default for BoundedTelemetryQueue {
/// Creates a pre-allocated ring queue with `DEFAULT_TELEMETRY_QUEUE_CAPACITY` slots.
///
/// # Returns
///
/// - `Self` - Pre-allocated telemetry queue.
fn default() -> Self {
Self::with_capacity(DEFAULT_TELEMETRY_QUEUE_CAPACITY)
}
}
/// Zero-allocation hot-path push and low-frequency aggregation helpers for `BoundedTelemetryQueue`.
impl BoundedTelemetryQueue {
/// Pre-allocates a fixed-capacity ring buffer (`>= 1`) so subsequent `push` calls perform zero heap allocation.
///
/// # Arguments
///
/// - `usize` - Fixed slot capacity.
///
/// # Returns
///
/// - `Self` - Ready ring queue.
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
let cap: usize = capacity.max(1);
let slots: Vec<TelemetrySample> = vec![TelemetrySample::default(); cap];
Self {
slots,
head: 0,
len: 0,
capacity: cap,
dropped_oldest_count: 0,
}
}
/// Pushes `sample` without blocking or heap allocation, overwriting the oldest sample when full.
///
/// # Arguments
///
/// - `&Self` - Mutable telemetry queue.
/// - `TelemetrySample` - Sample capturing reused callback/present timestamps.
///
/// # Returns
///
/// - `bool` - `true` when stored without dropping; `false` when the oldest sample was evicted.
pub fn push(&mut self, sample: TelemetrySample) -> bool {
let cap: usize = self.get_capacity();
let len: usize = self.get_len();
let head: usize = self.get_head();
if len < cap {
let tail: usize = (head + len) % cap;
self.get_mut_slots()[tail] = sample;
self.set_len(len + 1);
true
} else {
self.get_mut_slots()[head] = sample;
self.set_head((head + 1) % cap);
let next_drops: u64 = self.get_dropped_oldest_count().saturating_add(1);
self.set_dropped_oldest_count(next_drops);
false
}
}
/// Drains all currently queued samples in FIFO order into `out` and resets the ring cursor.
///
/// # Arguments
///
/// - `&Self` - Mutable telemetry queue.
/// - `&mut Vec<TelemetrySample>` - Destination vector.
///
/// # Returns
///
/// - `usize` - Number of samples drained.
pub fn drain_into(&mut self, out: &mut Vec<TelemetrySample>) -> usize {
let count: usize = self.get_len();
let head: usize = self.get_head();
let cap: usize = self.get_capacity();
for offset in 0..count {
let idx: usize = (head + offset) % cap;
out.push(self.get_slots()[idx]);
}
self.set_head(0);
self.set_len(0);
count
}
/// Aggregates all queued samples in a single low-frequency batch without pixel readback or GPU wait.
///
/// # Arguments
///
/// - `&Self` - Mutable telemetry queue.
///
/// # Returns
///
/// - `AggregatedTelemetryWindow` - Aggregated presentation interval and latency percentiles.
pub fn aggregate_and_drain(&mut self) -> AggregatedTelemetryWindow {
let mut drained: Vec<TelemetrySample> = Vec::with_capacity(self.get_len());
let count: usize = self.drain_into(&mut drained);
if count == 0 {
return AggregatedTelemetryWindow::default();
}
let mut present_intervals: Vec<f64> = Vec::with_capacity(count);
let mut input_latencies: Vec<f64> = Vec::new();
let mut presented: u64 = 0;
let mut skipped: u64 = 0;
let mut failed: u64 = 0;
let mut missed: u64 = 0;
let mut compositor_hits: u64 = 0;
let last_sample: TelemetrySample = drained[count - 1];
for sample in drained.iter() {
match sample.get_present_outcome() {
SurfacePresentOutcome::Submitted => {
presented = presented.saturating_add(1);
if sample.get_missed_deadline() {
missed = missed.saturating_add(1);
}
if sample.get_present_interval_ms() > 0.0 {
present_intervals.push(sample.get_present_interval_ms());
}
if sample.get_present_timing_source() == PresentTimingSource::CompositorMeasured
{
compositor_hits = compositor_hits.saturating_add(1);
}
}
SurfacePresentOutcome::SkippedUnchanged => {
skipped = skipped.saturating_add(1);
}
SurfacePresentOutcome::Failed => {
failed = failed.saturating_add(1);
}
}
if sample.get_input_latency_measured() {
input_latencies.push(sample.get_input_to_present_ms());
}
}
present_intervals.sort_by(|a: &f64, b: &f64| a.total_cmp(b));
input_latencies.sort_by(|a: &f64, b: &f64| a.total_cmp(b));
AggregatedTelemetryWindow {
sample_count: count as u64,
presented_frames: presented,
skipped_unchanged_frames: skipped,
failed_frames: failed,
missed_deadline_frames: missed,
present_p50_ms: sorted_percentile_f64(&present_intervals, 0.50),
present_p95_ms: sorted_percentile_f64(&present_intervals, 0.95),
present_p99_ms: sorted_percentile_f64(&present_intervals, 0.99),
input_to_present_p95_ms: sorted_percentile_f64(&input_latencies, 0.95),
has_input_latency: !input_latencies.is_empty(),
has_compositor_timing: compositor_hits > 0 && compositor_hits == presented,
scene_profile: last_sample.get_scene_profile(),
display_mode_hz: last_sample.get_display_mode_hz(),
candidate: last_sample.get_candidate(),
}
}
}
/// Constructors and builders for `CandidateScore`.
impl CandidateScore {
/// Creates a comparable `CandidateScore` for `(candidate, scene_profile, display_mode_hz_millihz)` and latency metrics `(missed_ratio, p95_ms, p99_ms, input_to_present_ms)`.
///
/// # Arguments
///
/// - `RenderBackendCandidate` - Candidate backend being scored.
/// - `SceneProfile` - Active workload scene profile.
/// - `u32` - Display refresh mode in millihertz.
/// - `(f64, f64, f64, f64)` - Tuple `(missed_frame_ratio, p95_frame_ms, p99_frame_ms, input_to_present_ms)`.
/// - `u64` - Number of real presented frames backing this score.
///
/// # Returns
///
/// - `Self` - Comparable candidate score (`hybrid_net_gain_ms` defaults to `0.0`).
#[must_use]
pub const fn from_metrics(
candidate: RenderBackendCandidate,
scene_profile: SceneProfile,
display_mode_hz_millihz: u32,
latency: (f64, f64, f64, f64),
sample_count: u64,
) -> Self {
let (missed_frame_ratio, p95_frame_ms, p99_frame_ms, input_to_present_ms): (
f64,
f64,
f64,
f64,
) = latency;
Self {
candidate,
scene_profile,
display_mode_hz_millihz,
missed_frame_ratio,
p95_frame_ms,
p99_frame_ms,
input_to_present_ms,
hybrid_net_gain_ms: 0.0,
sample_count,
}
}
/// Attaches the measured sparse-effect `Hybrid` net gain in milliseconds over pure GPU and pure CPU.
///
/// # Arguments
///
/// - `Self` - Base candidate score.
/// - `f64` - Net gain in milliseconds (`<= 0.0` disqualifies `Hybrid`).
///
/// # Returns
///
/// - `Self` - Updated candidate score.
#[must_use]
pub fn with_hybrid_net_gain_ms(mut self, net_gain_ms: f64) -> Self {
self.set_hybrid_net_gain_ms(net_gain_ms);
self
}
}
/// Default budget-sliced warmup and deferred-release settings for `HandoffBudgetConfig`.
impl Default for HandoffBudgetConfig {
/// Creates the default handoff budget configuration.
///
/// # Returns
///
/// - `Self` - Default `HandoffBudgetConfig`.
fn default() -> Self {
Self {
warmup_steps_required: DEFAULT_HANDOFF_WARMUP_STEPS,
per_frame_budget_ms: DEFAULT_HANDOFF_PER_FRAME_BUDGET_MS,
max_warmup_timeout_ms: DEFAULT_HANDOFF_TIMEOUT_MS,
post_commit_fence_frames: DEFAULT_POST_COMMIT_FENCE_FRAMES,
}
}
}
/// Invariance checks for `RuntimeStateSnapshot`.
impl RuntimeStateSnapshot {
/// Verifies that scroll, gesture, focus, page state, animation timeline, and target refresh rate are completely preserved.
///
/// # Arguments
///
/// - `&Self` - Pre-switch runtime state snapshot.
/// - `&Self` - Post-switch runtime state snapshot.
///
/// # Returns
///
/// - `bool` - `true` when zero user/animation state was reset and target refresh rate did not drop.
#[must_use]
pub fn is_preserved_by(&self, after: &Self) -> bool {
self.get_scroll_offset_x().to_bits() == after.get_scroll_offset_x().to_bits()
&& self.get_scroll_offset_y().to_bits() == after.get_scroll_offset_y().to_bits()
&& self.get_active_gesture_id() == after.get_active_gesture_id()
&& self.get_focused_node_id() == after.get_focused_node_id()
&& self.get_page_state_revision() == after.get_page_state_revision()
&& self.get_animation_timeline_ns() == after.get_animation_timeline_ns()
&& after.get_target_refresh_hz() >= self.get_target_refresh_hz()
}
}
/// Default idle state for `HandoffCoordinator`.
impl Default for HandoffCoordinator {
/// Creates an idle `HandoffCoordinator`.
///
/// # Returns
///
/// - `Self` - Idle handoff coordinator.
fn default() -> Self {
Self {
stage: HandoffStage::Idle,
old_candidate: RenderBackendCandidate::Software,
target_candidate: RenderBackendCandidate::Software,
target_width: 0,
target_height: 0,
target_scale_factor: 1.0,
target_scene_version: 0,
started_at_ms: 0,
warmup_steps_completed: 0,
budget_config: HandoffBudgetConfig::default(),
old_resources_retained: false,
commit_fence_id: 0,
completed_fence_id: 0,
post_handoff_present_confirmed: false,
last_abort_reason: None,
seamless_success_count: 0,
abort_count: 0,
preserved_state: RuntimeStateSnapshot::default(),
}
}
}
/// Frame-boundary handoff lifecycle methods for `HandoffCoordinator`.
impl HandoffCoordinator {
/// Returns the most recent abort reason, if any handoff aborted.
///
/// # Arguments
///
/// - `&Self` - Coordinator reference.
///
/// # Returns
///
/// - `Option<HandoffAbortReason>` - Last abort reason.
#[must_use]
pub fn last_abort_reason_value(&self) -> Option<HandoffAbortReason> {
let Self {
last_abort_reason, ..
} = *self;
last_abort_reason
}
/// Returns `true` when a handoff is warming up, boundary-ready, or awaiting post-handoff present confirmation.
///
/// # Arguments
///
/// - `&Self` - Coordinator reference.
///
/// # Returns
///
/// - `bool` - `true` when in flight.
#[must_use]
pub fn is_in_flight(&self) -> bool {
matches!(
self.get_stage(),
HandoffStage::WarmingUp
| HandoffStage::ReadyForBoundary
| HandoffStage::AwaitingPresentConfirmation
)
}
/// Starts warming up `target` on exact `(width, height, scale_factor, scene_version)` while `old` continues presenting uninterrupted.
///
/// # Arguments
///
/// - `&Self` - Mutable handoff coordinator.
/// - `RenderBackendCandidate` - Currently presenting backend that remains active during warmup.
/// - `RenderBackendCandidate` - Candidate backend to warm up.
/// - `(u32, u32, f32, u64)` - Tuple `(width, height, scale_factor, scene_version)`.
/// - `u64` - Monotonic start timestamp in milliseconds.
/// - `RuntimeStateSnapshot` - Interactive state snapshot that MUST remain invariant across takeover.
pub fn begin_handoff(
&mut self,
old: RenderBackendCandidate,
target: RenderBackendCandidate,
frame_identity: (u32, u32, f32, u64),
now_ms: u64,
state: RuntimeStateSnapshot,
) {
let (width, height, scale_factor, scene_version): (u32, u32, f32, u64) = frame_identity;
self.set_stage(HandoffStage::WarmingUp);
self.set_old_candidate(old);
self.set_target_candidate(target);
self.set_target_width(width);
self.set_target_height(height);
self.set_target_scale_factor(scale_factor);
self.set_target_scene_version(scene_version);
self.set_started_at_ms(now_ms);
self.set_warmup_steps_completed(0);
self.set_old_resources_retained(true);
self.set_commit_fence_id(0);
self.set_completed_fence_id(0);
self.set_post_handoff_present_confirmed(false);
self.set_last_abort_reason(None);
self.set_preserved_state(state);
}
/// Executes one budget-sliced UI/render-thread warmup step, aborting cleanly if warmup times out or init fails.
///
/// # Arguments
///
/// - `&Self` - Mutable handoff coordinator.
/// - `f64` - Elapsed work slice duration in milliseconds for this frame.
/// - `bool` - `true` if this warmup step succeeded without error.
/// - `u64` - Current monotonic timestamp in milliseconds.
///
/// # Returns
///
/// - `Result<HandoffStage, HandoffAbortReason>` - Updated handoff stage or clean abort reason.
pub fn step_warmup(
&mut self,
step_elapsed_ms: f64,
step_ok: bool,
now_ms: u64,
) -> Result<HandoffStage, HandoffAbortReason> {
if self.get_stage() != HandoffStage::WarmingUp {
return Ok(self.get_stage());
}
let budget: HandoffBudgetConfig = self.get_budget_config();
let elapsed_total_ms: u64 = now_ms.saturating_sub(self.get_started_at_ms());
if elapsed_total_ms > budget.get_max_warmup_timeout_ms() {
self.abort_internal(HandoffAbortReason::TimedOut);
return Err(HandoffAbortReason::TimedOut);
}
if !step_ok {
self.abort_internal(HandoffAbortReason::InitFailed);
return Err(HandoffAbortReason::InitFailed);
}
if step_elapsed_ms <= budget.get_per_frame_budget_ms()
|| self.get_warmup_steps_completed() == 0
{
let next_steps: u32 = self.get_warmup_steps_completed().saturating_add(1);
self.set_warmup_steps_completed(next_steps);
}
if self.get_warmup_steps_completed() >= budget.get_warmup_steps_required().max(1) {
self.set_stage(HandoffStage::ReadyForBoundary);
}
Ok(self.get_stage())
}
/// Attempts atomic takeover at a frame boundary ONLY when candidate first frame matches `(width, height, scale_factor, scene_version)` and meets deadline.
///
/// # Arguments
///
/// - `&Self` - Mutable handoff coordinator.
/// - `HandoffFrameDescriptor` - Candidate's verified first frame descriptor.
/// - `(u32, u32, f32, u64)` - Current live `(width, height, scale_factor, scene_version)` at the frame boundary.
/// - `u64` - Sync fence ID associated with the takeover frame.
/// - `u64` - Current monotonic timestamp in milliseconds.
///
/// # Returns
///
/// - `Result<RenderBackendCandidate, HandoffAbortReason>` - New active candidate on boundary commit, or abort reason keeping old backend active.
pub fn try_commit_at_frame_boundary(
&mut self,
first_frame: HandoffFrameDescriptor,
current_frame: (u32, u32, f32, u64),
commit_fence_id: u64,
now_ms: u64,
) -> Result<RenderBackendCandidate, HandoffAbortReason> {
let (cur_w, cur_h, cur_scale, cur_scene_ver): (u32, u32, f32, u64) = current_frame;
let budget: HandoffBudgetConfig = self.get_budget_config();
if now_ms.saturating_sub(self.get_started_at_ms()) > budget.get_max_warmup_timeout_ms() {
self.abort_internal(HandoffAbortReason::TimedOut);
return Err(HandoffAbortReason::TimedOut);
}
if !first_frame.get_first_frame_ok() {
self.abort_internal(HandoffAbortReason::FirstFrameFailed);
return Err(HandoffAbortReason::FirstFrameFailed);
}
if first_frame.get_width() != cur_w
|| first_frame.get_height() != cur_h
|| first_frame.get_width() != self.get_target_width()
|| first_frame.get_height() != self.get_target_height()
{
self.abort_internal(HandoffAbortReason::DimensionMismatch);
return Err(HandoffAbortReason::DimensionMismatch);
}
if (first_frame.get_scale_factor() - cur_scale).abs() > 0.001
|| (first_frame.get_scale_factor() - self.get_target_scale_factor()).abs() > 0.001
{
self.abort_internal(HandoffAbortReason::ScaleFactorMismatch);
return Err(HandoffAbortReason::ScaleFactorMismatch);
}
if first_frame.get_scene_version() != cur_scene_ver
|| first_frame.get_scene_version() != self.get_target_scene_version()
{
self.abort_internal(HandoffAbortReason::StaleSceneVersion);
return Err(HandoffAbortReason::StaleSceneVersion);
}
if first_frame.get_frame_time_ms() > first_frame.get_deadline_ms() {
self.abort_internal(HandoffAbortReason::MissedDeadline);
return Err(HandoffAbortReason::MissedDeadline);
}
self.set_stage(HandoffStage::AwaitingPresentConfirmation);
self.set_commit_fence_id(commit_fence_id.max(1));
self.set_old_resources_retained(true);
self.set_post_handoff_present_confirmed(false);
Ok(self.get_target_candidate())
}
/// Confirms post-handoff presentation and sync fence completion, releasing old backend resources ONLY once both succeed.
///
/// # Arguments
///
/// - `&Self` - Mutable handoff coordinator.
/// - `bool` - `true` when the post-handoff frame was confirmed presented on the new backend.
/// - `u64` - Highest completed GPU/surface sync fence identifier.
///
/// # Returns
///
/// - `bool` - `true` when old backend resources are now safe to release and the handoff is finalized as a seamless success.
pub fn confirm_post_handoff_present(
&mut self,
present_confirmed: bool,
completed_fence_id: u64,
) -> bool {
if self.get_stage() != HandoffStage::AwaitingPresentConfirmation {
return false;
}
if present_confirmed {
self.set_post_handoff_present_confirmed(true);
}
let latest_fence: u64 = self.get_completed_fence_id().max(completed_fence_id);
self.set_completed_fence_id(latest_fence);
if self.get_post_handoff_present_confirmed() && latest_fence >= self.get_commit_fence_id() {
self.set_old_resources_retained(false);
self.set_stage(HandoffStage::Committed);
let next_ok: u64 = self.get_seamless_success_count().saturating_add(1);
self.set_seamless_success_count(next_ok);
true
} else {
false
}
}
/// Aborts any in-flight handoff because of an external fault without crediting `seamless_success_count`.
///
/// # Arguments
///
/// - `&Self` - Mutable handoff coordinator.
pub fn abort_for_fault(&mut self) {
if self.is_in_flight() {
self.abort_internal(HandoffAbortReason::FaultInterrupted);
}
}
/// Marks the handoff aborted while preserving the old backend and incrementing `abort_count`.
///
/// # Arguments
///
/// - `&Self` - Mutable handoff coordinator.
/// - `HandoffAbortReason` - Structured abort cause.
fn abort_internal(&mut self, reason: HandoffAbortReason) {
self.set_stage(HandoffStage::Aborted);
self.set_last_abort_reason(Some(reason));
self.set_old_resources_retained(true);
let next_aborts: u64 = self.get_abort_count().saturating_add(1);
self.set_abort_count(next_aborts);
}
}
/// Default shadow-first adaptive router policy (`RecommendOnly`).
impl Default for AdaptiveRouterConfig {
/// Creates the conservative default `AdaptiveRouterConfig` starting in `RecommendOnly` shadow mode.
///
/// # Returns
///
/// - `Self` - Default router config.
fn default() -> Self {
Self {
switch_mode: AdaptiveSwitchMode::RecommendOnly,
sustained_miss_threshold: DEFAULT_SUSTAINED_MISS_THRESHOLD,
input_latency_degrade_ratio: DEFAULT_INPUT_LATENCY_DEGRADE_RATIO,
consecutive_wins_required: DEFAULT_CONSECUTIVE_WINS_REQUIRED,
switch_cost_ms: DEFAULT_SWITCH_COST_MS,
min_dwell_ms: DEFAULT_MIN_DWELL_MS,
cooldown_ms: DEFAULT_COOLDOWN_MS,
probe_min_headroom_ratio: DEFAULT_PROBE_MIN_HEADROOM_RATIO,
telemetry_queue_capacity: DEFAULT_TELEMETRY_QUEUE_CAPACITY,
}
}
}
/// Fault-tag inspection helper for `AdaptiveDecision`.
impl AdaptiveDecision {
/// Returns the optional explicit fault classification attached to this decision.
///
/// # Arguments
///
/// - `&Self` - Decision reference.
///
/// # Returns
///
/// - `Option<FaultEventKind>` - Fault tag when this decision originated from a fault.
#[must_use]
pub fn fault_tag_value(&self) -> Option<FaultEventKind> {
let Self { fault_tag, .. } = *self;
fault_tag
}
}
/// Default adaptive router initialized for a headless software host in shadow `RecommendOnly` mode.
impl Default for AdaptiveRenderRouter {
/// Creates a default headless `AdaptiveRenderRouter`.
///
/// # Returns
///
/// - `Self` - Default adaptive render router.
fn default() -> Self {
Self::new(
AdaptiveRouterConfig::default(),
HostCapabilityProfile::default(),
60.0,
)
}
}
/// Unified 5-stage routing, probing, selection, handoff, and fault handling implementation for `AdaptiveRenderRouter`.
impl AdaptiveRenderRouter {
/// Creates a new 5-stage `AdaptiveRenderRouter` bound to `config`, `host_profile`, and `display_mode_hz`.
///
/// # Arguments
///
/// - `AdaptiveRouterConfig` - Policy thresholds and rollout switch mode.
/// - `HostCapabilityProfile` - Host channel capabilities and visual-equivalence baseline.
/// - `f64` - Initial display mode refresh rate in Hertz.
///
/// # Returns
///
/// - `Self` - Initialized adaptive render router.
#[must_use]
pub fn new(
config: AdaptiveRouterConfig,
host_profile: HostCapabilityProfile,
display_mode_hz: f64,
) -> Self {
let initial_candidate: RenderBackendCandidate = host_profile.best_available_candidate(None);
let queue_cap: usize = config.get_telemetry_queue_capacity();
Self {
config,
host_profile,
winner_cache: WinnerCache::default(),
telemetry_queue: BoundedTelemetryQueue::with_capacity(queue_cap),
handoff: HandoffCoordinator::default(),
active_candidate: initial_candidate,
recommended_candidate: initial_candidate,
active_scene_profile: SceneProfile::StaticUi,
display_mode_hz: if display_mode_hz.is_finite() && display_mode_hz > 0.0 {
display_mode_hz
} else {
60.0
},
device_id: DEFAULT_DEVICE_ID.to_string(),
driver_version: DEFAULT_DRIVER_VERSION.to_string(),
build_id: DEFAULT_BUILD_ID.to_string(),
last_switch_ms: 0,
has_switched_once: false,
cooldown_until_ms: 0,
sustained_miss_streak: 0,
input_latency_degraded: false,
streak_candidate: None,
streak_wins: 0,
last_valid_frame_retained: false,
fault_failover_count: 0,
tagged_fault_events: Vec::new(),
probe_runs: 0,
probe_skips_no_headroom: 0,
cache_hits: 0,
recommendations_logged: 0,
last_decision_reason: REASON_KEEP_CURRENT,
}
}
/// Updates environment identity `(device_id, driver_version, display_mode_hz, build_id)` and invalidates stale cached winners.
///
/// # Arguments
///
/// - `&Self` - Mutable router reference.
/// - `&str` - Device identifier.
/// - `&str` - Graphics driver version.
/// - `f64` - Display mode refresh rate in Hertz.
/// - `&str` - Build identifier.
///
/// # Returns
///
/// - `usize` - Number of stale winner cache entries invalidated.
pub fn update_environment(
&mut self,
device_id: &str,
driver_version: &str,
display_mode_hz: f64,
build_id: &str,
) -> usize {
self.set_device_id(device_id.to_string());
self.set_driver_version(driver_version.to_string());
if display_mode_hz.is_finite() && display_mode_hz > 0.0 {
self.set_display_mode_hz(display_mode_hz);
}
self.set_build_id(build_id.to_string());
let millihz: u32 = hz_to_millihz(self.get_display_mode_hz());
self.get_mut_winner_cache().invalidate_stale_environment(
device_id,
driver_version,
millihz,
build_id,
)
}
/// Builds the current `WinnerCacheKey` for `scene_profile` using active device, driver, display mode, and build identity.
///
/// # Arguments
///
/// - `&Self` - Router reference.
/// - `SceneProfile` - Target scene profile.
///
/// # Returns
///
/// - `WinnerCacheKey` - Exact composite cache key.
#[must_use]
pub fn cache_key_for(&self, scene_profile: SceneProfile) -> WinnerCacheKey {
WinnerCacheKey::new(
self.get_device_id().clone(),
self.get_driver_version().clone(),
hz_to_millihz(self.get_display_mode_hz()),
self.get_build_id().clone(),
scene_profile,
)
}
/// Stage 1 (Startup): selects a verified cached winner if valid, otherwise tries visually-equivalent `GpuDirect` first (locking single-channel hosts).
///
/// # Arguments
///
/// - `&Self` - Mutable router reference.
/// - `SceneProfile` - Initial scene workload profile.
///
/// # Returns
///
/// - `AdaptiveDecision` - Startup backend selection decision.
pub fn select_startup_candidate(&mut self, scene_profile: SceneProfile) -> AdaptiveDecision {
self.set_active_scene_profile(scene_profile);
if self.get_host_profile().is_single_channel() {
let sole: RenderBackendCandidate =
self.get_host_profile().best_available_candidate(None);
self.set_active_candidate(sole);
self.set_recommended_candidate(sole);
self.set_last_decision_reason(REASON_SINGLE_CHANNEL_LOCKED);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::LockedSingleChannel,
active_candidate: sole,
recommended_candidate: sole,
applied: true,
reason: REASON_SINGLE_CHANNEL_LOCKED,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
let key: WinnerCacheKey = self.cache_key_for(scene_profile);
if let Some(entry) = self.get_winner_cache().lookup(&key)
&& self
.get_host_profile()
.candidate_passes_gate(entry.get_winner())
.is_ok()
{
let winner: RenderBackendCandidate = entry.get_winner();
let next_hits: u64 = self.get_cache_hits().saturating_add(1);
self.set_cache_hits(next_hits);
self.set_active_candidate(winner);
self.set_recommended_candidate(winner);
self.set_last_decision_reason(REASON_CACHE_HIT_VERIFIED);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::UseCachedWinner,
active_candidate: winner,
recommended_candidate: winner,
applied: true,
reason: REASON_CACHE_HIT_VERIFIED,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
if self
.get_host_profile()
.candidate_passes_gate(RenderBackendCandidate::GpuDirect)
.is_ok()
{
self.set_active_candidate(RenderBackendCandidate::GpuDirect);
self.set_recommended_candidate(RenderBackendCandidate::GpuDirect);
self.set_last_decision_reason(REASON_STARTUP_GPU_DIRECT);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::StartupGpuDirect,
active_candidate: RenderBackendCandidate::GpuDirect,
recommended_candidate: RenderBackendCandidate::GpuDirect,
applied: true,
reason: REASON_STARTUP_GPU_DIRECT,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
let fallback: RenderBackendCandidate =
self.get_host_profile().best_available_candidate(None);
self.set_active_candidate(fallback);
self.set_recommended_candidate(fallback);
self.set_last_decision_reason(REASON_STARTUP_FALLBACK_READY);
AdaptiveDecision {
kind: AdaptiveDecisionKind::KeepCurrent,
active_candidate: fallback,
recommended_candidate: fallback,
applied: true,
reason: REASON_STARTUP_FALLBACK_READY,
preserve_last_valid_frame: false,
fault_tag: None,
}
}
/// Stage 1 (Startup failover): immediately switches from a failed startup candidate to a known-working visually-equivalent path.
///
/// # Arguments
///
/// - `&Self` - Mutable router reference.
/// - `RenderBackendCandidate` - Candidate that failed initialization or first-frame submission.
/// - `u64` - Current monotonic timestamp in milliseconds.
///
/// # Returns
///
/// - `AdaptiveDecision` - Immediate failover decision.
pub fn on_startup_candidate_failed(
&mut self,
failed: RenderBackendCandidate,
now_ms: u64,
) -> AdaptiveDecision {
let next: RenderBackendCandidate = self
.get_host_profile()
.best_available_candidate(Some(failed));
self.set_active_candidate(next);
self.set_recommended_candidate(next);
self.set_last_switch_ms(now_ms);
self.set_has_switched_once(true);
let cooldown_end: u64 = now_ms.saturating_add(self.get_config().get_cooldown_ms());
self.set_cooldown_until_ms(cooldown_end);
self.set_last_decision_reason(REASON_STARTUP_FAILOVER);
AdaptiveDecision {
kind: AdaptiveDecisionKind::StartupFailover,
active_candidate: next,
recommended_candidate: next,
applied: true,
reason: REASON_STARTUP_FAILOVER,
preserve_last_valid_frame: false,
fault_tag: None,
}
}
/// Stage 2 (Runtime): records a zero-allocation hot-path telemetry sample into `BoundedTelemetryQueue` and updates degradation triggers.
///
/// # Arguments
///
/// - `&Self` - Mutable router reference.
/// - `TelemetrySample` - Frame sample reusing existing callback/present timestamps.
///
/// # Returns
///
/// - `bool` - `true` when enqueued without overwriting an unread sample; `false` when drop-oldest triggered.
pub fn record_runtime_sample(&mut self, sample: TelemetrySample) -> bool {
let target_ms: f64 =
AdaptiveFrameMetrics::target_frame_interval_ms_for_hz(sample.get_display_mode_hz());
if sample.get_present_outcome() == SurfacePresentOutcome::Submitted {
if sample.get_missed_deadline() {
let next_streak: u32 = self.get_sustained_miss_streak().saturating_add(1);
self.set_sustained_miss_streak(next_streak);
} else {
self.set_sustained_miss_streak(0);
}
}
if sample.get_input_latency_measured() {
let degrade_limit: f64 =
target_ms * self.get_config().get_input_latency_degrade_ratio();
self.set_input_latency_degraded(sample.get_input_to_present_ms() > degrade_limit);
}
self.get_mut_telemetry_queue().push(sample)
}
/// Returns `true` ONLY when the runtime is idle OR explicit frame headroom exceeds the configured threshold.
///
/// # Arguments
///
/// - `&Self` - Router reference.
/// - `bool` - `true` when the app is currently idle.
/// - `f64` - Recent active frame duration in milliseconds.
/// - `f64` - Target frame interval in milliseconds.
///
/// # Returns
///
/// - `bool` - `true` when probing has sufficient headroom.
#[must_use]
pub fn has_probe_headroom(
&self,
is_idle: bool,
recent_frame_ms: f64,
target_interval_ms: f64,
) -> bool {
if is_idle {
return true;
}
if !target_interval_ms.is_finite() || target_interval_ms <= 0.0 {
return false;
}
let remaining_ms: f64 = target_interval_ms - recent_frame_ms.max(0.0);
let required_ms: f64 = target_interval_ms
* self
.get_config()
.get_probe_min_headroom_ratio()
.clamp(0.0, 1.0);
remaining_ms >= required_ms
}
/// Stage 2 (Runtime): gates short candidate probing strictly on sustained degradation AND idle/explicit headroom (never probing single-channel hosts).
///
/// # Arguments
///
/// - `&Self` - Mutable router reference.
/// - `bool` - `true` when the UI/render loop is currently idle.
/// - `f64` - Recent active frame time in milliseconds.
/// - `f64` - Target frame interval in milliseconds.
/// - `u64` - Current monotonic timestamp in milliseconds.
///
/// # Returns
///
/// - `Result<ProbeTriggerReason, &'static str>` - `Ok(reason)` when a short probe is authorized, or static suppression reason.
pub fn should_trigger_probe(
&mut self,
is_idle: bool,
recent_frame_ms: f64,
target_interval_ms: f64,
now_ms: u64,
) -> Result<ProbeTriggerReason, &'static str> {
if self.get_host_profile().is_single_channel() {
self.set_last_decision_reason(REASON_SINGLE_CHANNEL_LOCKED);
return Err(REASON_SINGLE_CHANNEL_LOCKED);
}
if now_ms < self.get_cooldown_until_ms() {
self.set_last_decision_reason(REASON_PROBE_COOLDOWN);
return Err(REASON_PROBE_COOLDOWN);
}
if self.get_handoff().is_in_flight() {
self.set_last_decision_reason(REASON_PROBE_HANDOFF_ACTIVE);
return Err(REASON_PROBE_HANDOFF_ACTIVE);
}
let trigger: Option<ProbeTriggerReason> = if self.get_sustained_miss_streak()
>= self.get_config().get_sustained_miss_threshold()
{
Some(ProbeTriggerReason::SustainedDeadlineMiss)
} else if self.get_input_latency_degraded() {
Some(ProbeTriggerReason::InputLatencyDegraded)
} else {
None
};
let Some(reason) = trigger else {
self.set_last_decision_reason(REASON_PROBE_NO_TRIGGER);
return Err(REASON_PROBE_NO_TRIGGER);
};
if !self.has_probe_headroom(is_idle, recent_frame_ms, target_interval_ms) {
let next_skips: u64 = self.get_probe_skips_no_headroom().saturating_add(1);
self.set_probe_skips_no_headroom(next_skips);
self.set_last_decision_reason(REASON_PROBE_NO_HEADROOM);
return Err(REASON_PROBE_NO_HEADROOM);
}
let next_probes: u64 = self.get_probe_runs().saturating_add(1);
self.set_probe_runs(next_probes);
self.set_last_decision_reason(REASON_PROBE_STARTED);
Ok(reason)
}
/// Stage 3 (Selection): compares `current` and `candidate` under identical scene profile and refresh rate after quality, capability, and Hybrid net-gain gates.
///
/// # Arguments
///
/// - `&Self` - Mutable router reference.
/// - `CandidateScore` - Measured score of the currently active backend.
/// - `CandidateScore` - Measured score of the probed candidate backend.
/// - `u64` - Current monotonic timestamp in milliseconds.
///
/// # Returns
///
/// - `AdaptiveDecision` - Selection outcome respecting `RecommendOnly` vs `AutoSwitch`, consecutive wins, dwell time, and cooldown.
pub fn evaluate_candidates(
&mut self,
current: CandidateScore,
candidate: CandidateScore,
now_ms: u64,
) -> AdaptiveDecision {
let active: RenderBackendCandidate = self.get_active_candidate();
if self.get_host_profile().is_single_channel() {
self.set_last_decision_reason(REASON_SINGLE_CHANNEL_LOCKED);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::LockedSingleChannel,
active_candidate: active,
recommended_candidate: active,
applied: false,
reason: REASON_SINGLE_CHANNEL_LOCKED,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
if candidate.get_candidate() == active {
self.set_streak_candidate(None);
self.set_streak_wins(0);
self.set_last_decision_reason(REASON_KEEP_CURRENT);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::KeepCurrent,
active_candidate: active,
recommended_candidate: active,
applied: false,
reason: REASON_KEEP_CURRENT,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
if self
.get_host_profile()
.candidate_passes_gate(candidate.get_candidate())
.is_err()
{
self.set_streak_candidate(None);
self.set_streak_wins(0);
self.set_last_decision_reason(REASON_VISUAL_GATE_FAILED);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::KeepCurrent,
active_candidate: active,
recommended_candidate: active,
applied: false,
reason: REASON_VISUAL_GATE_FAILED,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
if current.get_scene_profile() != candidate.get_scene_profile()
|| current.get_display_mode_hz_millihz() != candidate.get_display_mode_hz_millihz()
{
self.set_last_decision_reason(REASON_CONTEXT_MISMATCH);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::KeepCurrent,
active_candidate: active,
recommended_candidate: active,
applied: false,
reason: REASON_CONTEXT_MISMATCH,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
if candidate.get_candidate() == RenderBackendCandidate::Hybrid
&& candidate.get_hybrid_net_gain_ms() <= 0.0
{
self.set_streak_candidate(None);
self.set_streak_wins(0);
self.set_last_decision_reason(REASON_HYBRID_NO_NET_GAIN);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::KeepCurrent,
active_candidate: active,
recommended_candidate: active,
applied: false,
reason: REASON_HYBRID_NO_NET_GAIN,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
let current_cost: f64 = compute_candidate_composite_cost_ms(¤t);
let candidate_cost: f64 = compute_candidate_composite_cost_ms(&candidate);
let gain_ms: f64 = current_cost - candidate_cost;
let is_tie: bool = gain_ms.abs() <= SCORE_TIE_EPSILON_MS;
let prefer_gpu_on_tie: bool = is_tie
&& candidate.get_candidate() == RenderBackendCandidate::GpuDirect
&& active != RenderBackendCandidate::GpuDirect;
let gpu_wins_tie_stay: bool = is_tie && active == RenderBackendCandidate::GpuDirect;
if gpu_wins_tie_stay {
self.set_streak_candidate(None);
self.set_streak_wins(0);
self.set_last_decision_reason(REASON_TIE_PREFER_GPU_DIRECT);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::KeepCurrent,
active_candidate: active,
recommended_candidate: active,
applied: false,
reason: REASON_TIE_PREFER_GPU_DIRECT,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
let cfg: AdaptiveRouterConfig = self.get_config();
let beats_switch_cost: bool = prefer_gpu_on_tie || gain_ms > cfg.get_switch_cost_ms();
if !beats_switch_cost {
self.set_streak_candidate(None);
self.set_streak_wins(0);
self.set_last_decision_reason(REASON_BELOW_SWITCH_COST);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::KeepCurrent,
active_candidate: active,
recommended_candidate: active,
applied: false,
reason: REASON_BELOW_SWITCH_COST,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
let prev_cand: Option<RenderBackendCandidate> = self.streak_candidate_value();
let next_wins: u32 = if prev_cand == Some(candidate.get_candidate()) {
self.get_streak_wins().saturating_add(1)
} else {
1
};
self.set_streak_candidate(Some(candidate.get_candidate()));
self.set_streak_wins(next_wins);
if next_wins < cfg.get_consecutive_wins_required().max(1) {
self.set_last_decision_reason(REASON_AWAITING_CONSECUTIVE_WINS);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::KeepCurrent,
active_candidate: active,
recommended_candidate: active,
applied: false,
reason: REASON_AWAITING_CONSECUTIVE_WINS,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
let dwell_blocked: bool = self.get_has_switched_once()
&& now_ms.saturating_sub(self.get_last_switch_ms()) < cfg.get_min_dwell_ms();
let cooldown_blocked: bool = now_ms < self.get_cooldown_until_ms();
if dwell_blocked || cooldown_blocked {
self.set_last_decision_reason(REASON_DWELL_OR_COOLDOWN_ACTIVE);
return AdaptiveDecision {
kind: AdaptiveDecisionKind::KeepCurrent,
active_candidate: active,
recommended_candidate: candidate.get_candidate(),
applied: false,
reason: REASON_DWELL_OR_COOLDOWN_ACTIVE,
preserve_last_valid_frame: false,
fault_tag: None,
};
}
self.set_recommended_candidate(candidate.get_candidate());
match cfg.get_switch_mode() {
AdaptiveSwitchMode::RecommendOnly => {
let next_recs: u64 = self.get_recommendations_logged().saturating_add(1);
self.set_recommendations_logged(next_recs);
self.set_last_decision_reason(REASON_RECOMMEND_ONLY_SHADOW);
AdaptiveDecision {
kind: AdaptiveDecisionKind::RecommendSwitch,
active_candidate: active,
recommended_candidate: candidate.get_candidate(),
applied: false,
reason: REASON_RECOMMEND_ONLY_SHADOW,
preserve_last_valid_frame: false,
fault_tag: None,
}
}
AdaptiveSwitchMode::AutoSwitch => {
self.set_last_decision_reason(REASON_AUTO_SWITCH_HANDOFF);
AdaptiveDecision {
kind: AdaptiveDecisionKind::BeginHandoff,
active_candidate: active,
recommended_candidate: candidate.get_candidate(),
applied: true,
reason: REASON_AUTO_SWITCH_HANDOFF,
preserve_last_valid_frame: false,
fault_tag: None,
}
}
}
}
/// Stage 4 (Handoff): initiates budget-sliced candidate warmup while keeping the current backend presenting uninterrupted.
///
/// # Arguments
///
/// - `&Self` - Mutable router reference.
/// - `RenderBackendCandidate` - Candidate backend to warm up.
/// - `(u32, u32, f32, u64)` - Tuple `(width, height, scale_factor, scene_version)`.
/// - `u64` - Monotonic start timestamp in milliseconds.
/// - `RuntimeStateSnapshot` - Interactive runtime state snapshot that must stay invariant.
///
/// # Returns
///
/// - `Result<(), VisualEquivalenceFailure>` - `Ok(())` when warmup started, or visual-equivalence gate failure.
pub fn begin_seamless_handoff(
&mut self,
target: RenderBackendCandidate,
frame_identity: (u32, u32, f32, u64),
now_ms: u64,
state: RuntimeStateSnapshot,
) -> Result<(), VisualEquivalenceFailure> {
self.get_host_profile().candidate_passes_gate(target)?;
let old: RenderBackendCandidate = self.get_active_candidate();
self.get_mut_handoff()
.begin_handoff(old, target, frame_identity, now_ms, state);
Ok(())
}
/// Stage 4 (Handoff): attempts atomic takeover at a frame boundary and updates active candidate on success (or aborts cleanly).
///
/// # Arguments
///
/// - `&Self` - Mutable router reference.
/// - `HandoffFrameDescriptor` - Candidate first-frame verification descriptor.
/// - `(u32, u32, f32, u64)` - Live frame-boundary `(width, height, scale_factor, scene_version)`.
/// - `u64` - Sync fence ID for deferred old-resource reclamation.
/// - `u64` - Current monotonic timestamp in milliseconds.
/// - `CandidateScore` - Verified score of the winning candidate for cache recording.
///
/// # Returns
///
/// - `AdaptiveDecision` - `CommitHandoff` on exact boundary match or `AbortHandoff` leaving old backend active.
pub fn commit_handoff_at_boundary(
&mut self,
first_frame: HandoffFrameDescriptor,
current_frame: (u32, u32, f32, u64),
commit_fence_id: u64,
now_ms: u64,
verified_score: CandidateScore,
) -> AdaptiveDecision {
let old_active: RenderBackendCandidate = self.get_active_candidate();
match self.get_mut_handoff().try_commit_at_frame_boundary(
first_frame,
current_frame,
commit_fence_id,
now_ms,
) {
Ok(next_candidate) => {
self.set_active_candidate(next_candidate);
self.set_recommended_candidate(next_candidate);
self.set_last_switch_ms(now_ms);
self.set_has_switched_once(true);
let cooldown_end: u64 = now_ms.saturating_add(self.get_config().get_cooldown_ms());
self.set_cooldown_until_ms(cooldown_end);
self.set_streak_candidate(None);
self.set_streak_wins(0);
self.set_sustained_miss_streak(0);
let key: WinnerCacheKey = self.cache_key_for(verified_score.get_scene_profile());
let entry: WinnerCacheEntry = WinnerCacheEntry::new(
next_candidate,
now_ms,
verified_score.get_p95_frame_ms(),
verified_score.get_p99_frame_ms(),
verified_score.get_missed_frame_ratio(),
verified_score.get_input_to_present_ms(),
);
self.get_mut_winner_cache().record(key, entry);
self.set_last_decision_reason(REASON_HANDOFF_COMMITTED);
AdaptiveDecision {
kind: AdaptiveDecisionKind::CommitHandoff,
active_candidate: next_candidate,
recommended_candidate: next_candidate,
applied: true,
reason: REASON_HANDOFF_COMMITTED,
preserve_last_valid_frame: false,
fault_tag: None,
}
}
Err(_) => {
self.set_streak_candidate(None);
self.set_streak_wins(0);
self.set_last_decision_reason(REASON_HANDOFF_ABORTED);
AdaptiveDecision {
kind: AdaptiveDecisionKind::AbortHandoff,
active_candidate: old_active,
recommended_candidate: old_active,
applied: false,
reason: REASON_HANDOFF_ABORTED,
preserve_last_valid_frame: true,
fault_tag: None,
}
}
}
}
/// Stage 5 (Fault Handling): handles hardware/surface/driver/thermal faults explicitly, excluding them from seamless-handoff success counts.
///
/// # Arguments
///
/// - `&Self` - Mutable router reference.
/// - `FaultEventKind` - Explicit fault classification (`DeviceLost`, `SurfaceDestroyed`, `DriverSuspended`, `ThermalThrottled`).
/// - `bool` - `true` when the host window remains valid and the last valid frame MUST be retained (never submitting a blank frame).
/// - `u64` - Current monotonic timestamp in milliseconds.
///
/// # Returns
///
/// - `AdaptiveDecision` - Tagged fault response with immediate failover on `DeviceLost`.
pub fn handle_fault(
&mut self,
fault: FaultEventKind,
window_valid: bool,
now_ms: u64,
) -> AdaptiveDecision {
self.get_mut_handoff().abort_for_fault();
self.get_mut_tagged_fault_events().push((now_ms, fault));
self.set_streak_candidate(None);
self.set_streak_wins(0);
let retain_frame: bool = window_valid && fault != FaultEventKind::SurfaceDestroyed;
self.set_last_valid_frame_retained(retain_frame);
match fault {
FaultEventKind::DeviceLost => {
let current: RenderBackendCandidate = self.get_active_candidate();
let next: RenderBackendCandidate = self
.get_host_profile()
.best_available_candidate(Some(current));
self.set_active_candidate(next);
self.set_recommended_candidate(next);
self.set_last_switch_ms(now_ms);
self.set_has_switched_once(true);
let cooldown_end: u64 = now_ms.saturating_add(self.get_config().get_cooldown_ms());
self.set_cooldown_until_ms(cooldown_end);
let next_faults: u64 = self.get_fault_failover_count().saturating_add(1);
self.set_fault_failover_count(next_faults);
self.set_last_decision_reason(REASON_FAULT_DEVICE_LOST);
AdaptiveDecision {
kind: AdaptiveDecisionKind::FaultFailover,
active_candidate: next,
recommended_candidate: next,
applied: true,
reason: REASON_FAULT_DEVICE_LOST,
preserve_last_valid_frame: retain_frame,
fault_tag: Some(fault),
}
}
FaultEventKind::SurfaceDestroyed
| FaultEventKind::DriverSuspended
| FaultEventKind::ThermalThrottled => {
let active: RenderBackendCandidate = self.get_active_candidate();
let reason: &'static str = match fault {
FaultEventKind::SurfaceDestroyed => REASON_FAULT_SURFACE_DESTROYED,
FaultEventKind::DriverSuspended => REASON_FAULT_DRIVER_SUSPENDED,
FaultEventKind::ThermalThrottled => REASON_FAULT_THERMAL_THROTTLED,
FaultEventKind::DeviceLost => REASON_FAULT_DEVICE_LOST,
};
self.set_last_decision_reason(reason);
AdaptiveDecision {
kind: AdaptiveDecisionKind::FaultFailover,
active_candidate: active,
recommended_candidate: active,
applied: false,
reason,
preserve_last_valid_frame: retain_frame,
fault_tag: Some(fault),
}
}
}
}
/// Captures a compact serializable telemetry snapshot of the router and handoff coordinator state.
///
/// # Arguments
///
/// - `&Self` - Router reference.
///
/// # Returns
///
/// - `AdaptiveRouterSnapshot` - Snapshot embedded inside `AdaptiveFrameMetrics`.
#[must_use]
pub fn snapshot(&self) -> AdaptiveRouterSnapshot {
let last_fault: Option<FaultEventKind> = self
.get_tagged_fault_events()
.last()
.map(|(_, kind): &(u64, FaultEventKind)| *kind);
AdaptiveRouterSnapshot {
active_candidate: self.get_active_candidate(),
recommended_candidate: self.get_recommended_candidate(),
switch_mode: self.get_config().get_switch_mode(),
handoff_stage: self.get_handoff().get_stage(),
seamless_handoff_successes: self.get_handoff().get_seamless_success_count(),
handoff_aborts: self.get_handoff().get_abort_count(),
fault_failovers: self.get_fault_failover_count(),
probe_runs: self.get_probe_runs(),
probe_skips_no_headroom: self.get_probe_skips_no_headroom(),
cache_hits: self.get_cache_hits(),
recommendations_logged: self.get_recommendations_logged(),
has_tagged_fault: last_fault.is_some(),
last_fault_kind: last_fault.unwrap_or(FaultEventKind::DeviceLost),
}
}
/// Returns the candidate currently accumulating consecutive wins, if any.
///
/// # Arguments
///
/// - `&Self` - Router reference.
///
/// # Returns
///
/// - `Option<RenderBackendCandidate>` - Candidate on an active win streak.
#[must_use]
pub fn streak_candidate_value(&self) -> Option<RenderBackendCandidate> {
let Self {
streak_candidate, ..
} = *self;
streak_candidate
}
}