asupersync 0.3.4

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Concrete G7 decision contract for RaptorQ runtime governance.
//!
//! This module turns the artifact-only G7 contract into a live runtime policy
//! that can evaluate decoder pressure signals and emit deterministic telemetry
//! for rollout/hold/rollback/fallback decisions.

use std::fmt;
use std::hash::{Hash, Hasher};

use franken_decision::{
    DecisionContract, EvalContext, FallbackPolicy, LossMatrix, Posterior, ValidationError, evaluate,
};
use franken_kernel::{DecisionId, TraceId};

use crate::util::DetHasher;

/// Replay pointer for runtime G7 decisions.
pub const G7_DECISION_REPLAY_REF: &str = "replay:rq-track-g-expected-loss-v1";

const PERMILLE_SCALE: u32 = 1000;
const HEALTHY_FLOOR: u32 = 20;
const MODE_MARGIN_CAP: u32 = 400;
const ACTION_MARGIN_CAP: u32 = 200;
const FALLBACK_REASON_POLICY_BUDGET_EXHAUSTED: &str = "policy_budget_exhausted";
const FALLBACK_REASON_UNKNOWN_LOW_CONFIDENCE: &str = "unknown_state_with_low_confidence";
const FALLBACK_REASON_REGRESSION_LOW_CONFIDENCE: &str = "regression_state_with_low_confidence";
const FALLBACK_REASON_UNCLASSIFIED: &str = "conservative_fallback_reason_unclassified";
const MALFORMED_POSTERIOR_CONFIDENCE: u16 = 0;
const MALFORMED_POSTERIOR_UNCERTAINTY: u16 = 1000;
const MALFORMED_POSTERIOR_EXPECTED_LOSS_TERMS: [u32; action::COUNT] =
    [u32::MAX, u32::MAX, u32::MAX, 0];

/// Canonical fallback reasons the live G7 runtime can emit when fallback is active.
///
/// The broader artifact contract may list additional hard-trigger reasons owned by
/// downstream decode/replay validation surfaces. This list is intentionally narrower:
/// it describes only the reasons surfaced by [`GovernanceTelemetry`] today.
pub const G7_RUNTIME_FALLBACK_REASONS: &[&str] = &[
    FALLBACK_REASON_POLICY_BUDGET_EXHAUSTED,
    FALLBACK_REASON_UNKNOWN_LOW_CONFIDENCE,
    FALLBACK_REASON_REGRESSION_LOW_CONFIDENCE,
    FALLBACK_REASON_UNCLASSIFIED,
];

/// State indices into the posterior.
pub mod state {
    /// Runtime signals are nominal and consistent with approved behavior.
    pub const HEALTHY: usize = 0;
    /// Runtime is still coherent but under material pressure.
    pub const DEGRADED: usize = 1;
    /// Runtime signals indicate likely regression or rollback conditions.
    pub const REGRESSION: usize = 2;
    /// Runtime signals are too ambiguous or conflict-heavy for promotion.
    pub const UNKNOWN: usize = 3;
    /// Total number of states.
    pub const COUNT: usize = 4;
}

/// Action indices.
pub mod action {
    /// Continue the currently selected optimized path.
    pub const CONTINUE: usize = 0;
    /// Hold rollout to a safer optimized path while collecting evidence.
    pub const CANARY_HOLD: usize = 1;
    /// Revert to the conservative approved comparator.
    pub const ROLLBACK: usize = 2;
    /// Force deterministic conservative fallback immediately.
    pub const FALLBACK: usize = 3;
    /// Total number of actions.
    pub const COUNT: usize = 4;
}

/// Fixed-width contributor used in runtime decision telemetry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GovernanceEvidenceContributor {
    /// Canonical contributor name from the G7 artifact.
    pub name: &'static str,
    /// Relative weight in permille among the surfaced top contributors.
    pub contribution_permille: u16,
}

/// Deterministic runtime output for a single G7 decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GovernanceTelemetry {
    /// Unique deterministic identifier for this governance decision.
    pub decision_id: DecisionId,
    /// Trace identifier for correlating the decision with replay evidence.
    pub trace_id: TraceId,
    /// Posterior over G7 states in permille order `[healthy, degraded, regression, unknown]`.
    pub state_posterior_permille: [u16; state::COUNT],
    /// Expected-loss terms for actions `[continue, canary_hold, rollback, fallback]`.
    pub expected_loss_terms: [u32; action::COUNT],
    /// Action chosen by the live contract.
    pub chosen_action: &'static str,
    /// Confidence score in the canonical 0..=1000 range.
    pub confidence_score: u16,
    /// Uncertainty score in the canonical 0..=1000 range.
    pub uncertainty_score: u16,
    /// Whether the deterministic fallback trigger fired.
    pub deterministic_fallback_triggered: bool,
    /// Canonical reason for the fallback trigger, or `"none"`.
    pub deterministic_fallback_reason: &'static str,
    /// Canonical replay pointer for this runtime decision surface.
    pub replay_ref: &'static str,
    /// Top evidence contributors surfaced with deterministic tie-breaking.
    pub top_evidence_contributors: [GovernanceEvidenceContributor; 3],
}

/// Runtime inputs that feed the G7 governance contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GovernanceSnapshot {
    /// Dense-core row count at decision time.
    pub n_rows: usize,
    /// Dense-core column count at decision time.
    pub n_cols: usize,
    /// Dense-core density in permille.
    pub density_permille: usize,
    /// Rank-deficit pressure in permille.
    pub rank_deficit_permille: usize,
    /// Inactivation pressure in permille.
    pub inactivation_pressure_permille: usize,
    /// Row/column overhead ratio in permille.
    pub overhead_ratio_permille: usize,
    /// Whether feature extraction exhausted its strict budget.
    pub budget_exhausted: bool,
    /// Low-level conservative baseline loss.
    pub baseline_loss: u32,
    /// Low-level high-support loss.
    pub high_support_loss: u32,
    /// Low-level block-schur loss, or `u32::MAX` when unavailable.
    pub block_schur_loss: u32,
}

/// Live concrete G7 decision contract.
#[derive(Debug, Clone)]
pub struct RaptorQDecisionContract {
    states: Vec<String>,
    actions: Vec<String>,
    losses: LossMatrix,
    fallback: FallbackPolicy,
}

impl RaptorQDecisionContract {
    #[rustfmt::skip]
    const DEFAULT_LOSSES: [f64; 16] = [
        //                  continue  canary_hold  rollback  fallback
        /* healthy     */   10.0,     25.0,        90.0,     120.0,
        /* degraded    */   80.0,     35.0,        45.0,      50.0,
        /* regression  */  220.0,    120.0,        30.0,      20.0,
        /* unknown     */  170.0,     95.0,        55.0,      35.0,
    ];

    /// Build the canonical G7 decision contract.
    #[must_use]
    pub fn new() -> Self {
        let states = vec![
            "healthy".into(),
            "degraded".into(),
            "regression".into(),
            "unknown".into(),
        ];
        let actions = vec![
            "continue".into(),
            "canary_hold".into(),
            "rollback".into(),
            "fallback".into(),
        ];
        let losses = LossMatrix::new(
            states.clone(),
            actions.clone(),
            Self::DEFAULT_LOSSES.to_vec(),
        )
        .expect("RaptorQ G7 loss matrix should be valid");
        let fallback = FallbackPolicy::new(0.26, 2.1, 0.82)
            .expect("RaptorQ G7 fallback policy should be valid");
        Self {
            states,
            actions,
            losses,
            fallback,
        }
    }

    /// Compute the canonical G7 posterior in permille form.
    #[must_use]
    pub fn state_posterior_permille(snapshot: &GovernanceSnapshot) -> [u16; state::COUNT] {
        let density = clamp_permille(snapshot.density_permille);
        let rank = clamp_permille(snapshot.rank_deficit_permille);
        let inactivation = clamp_permille(snapshot.inactivation_pressure_permille);
        let overhead = clamp_permille(snapshot.overhead_ratio_permille);
        let conflict = policy_conflict_permille(snapshot);

        let budget_penalty = if snapshot.budget_exhausted { 400 } else { 0 };
        let healthy_penalty = density / 2
            + rank * 7 / 10
            + inactivation * 6 / 10
            + overhead * 4 / 10
            + budget_penalty;
        let healthy = HEALTHY_FLOOR.max(PERMILLE_SCALE.saturating_sub(healthy_penalty));
        let degraded =
            100 + density * 9 / 20 + inactivation * 7 / 20 + overhead / 4 + u32::from(conflict) / 5;
        let regression = 40
            + rank * 13 / 20
            + inactivation / 4
            + density * 3 / 20
            + if snapshot.budget_exhausted { 350 } else { 0 };
        let unknown = 20
            + u32::from(conflict) * 9 / 20
            + if snapshot.budget_exhausted { 420 } else { 0 }
            + if snapshot.block_schur_loss == u32::MAX {
                60
            } else {
                0
            };

        normalize_permille([healthy, degraded, regression, unknown])
    }

    /// Evaluate a runtime snapshot and return deterministic G7 telemetry.
    #[must_use]
    pub fn telemetry(&self, snapshot: &GovernanceSnapshot) -> GovernanceTelemetry {
        let posterior_permille = Self::state_posterior_permille(snapshot);
        let posterior = match posterior_from_permille(posterior_permille) {
            Ok(posterior) => posterior,
            Err(error) => {
                return Self::malformed_posterior_fallback_telemetry(
                    snapshot,
                    posterior_permille,
                    &error,
                );
            }
        };
        let expected_loss_terms = expected_loss_terms(&self.losses, &posterior);

        let concentration_score = concentration_score(posterior_permille);
        let action_margin_score = action_margin_score(expected_loss_terms);
        let preliminary_confidence = (((u32::from(concentration_score) * 7)
            + (u32::from(action_margin_score) * 3))
            / 10) as u16;
        let fallback_reason =
            deterministic_fallback_reason(snapshot, posterior_permille, preliminary_confidence);
        let clamped_fallback_confidence = preliminary_confidence.min(250);
        let clamped_fallback_uncertainty = 1000u16.saturating_sub(clamped_fallback_confidence);
        let confidence_score = if fallback_reason == "none" {
            preliminary_confidence
        } else {
            clamped_fallback_confidence
        };
        let uncertainty_score = 1000u16.saturating_sub(confidence_score);
        let ctx = eval_context(snapshot, confidence_score, uncertainty_score);
        // br-asupersync-g1pzep: evaluate now returns Result; for the
        // RaptorQ contract we control the action_set so this should
        // never produce ActionIndexOutOfRange in practice. On error we
        // fall back to the conservative FALLBACK action and emit a
        // canonical-registered reason so safety gates that key on
        // (chosen_action == "fallback" && deterministic_fallback_triggered)
        // engage as designed and is_runtime_fallback_reason returns true.
        // br-asupersync-dezwpc: previously emitted action::CONTINUE +
        // unregistered reason "contract_action_out_of_range" — fail-open
        // on contract evaluation error and broke G7 reason invariant.
        let outcome = match evaluate(self, &posterior, &ctx) {
            Ok(o) => o,
            Err(_) => {
                return GovernanceTelemetry {
                    decision_id: ctx.decision_id,
                    trace_id: ctx.trace_id,
                    state_posterior_permille: posterior_permille,
                    expected_loss_terms,
                    chosen_action: action_label(action::FALLBACK),
                    confidence_score: clamped_fallback_confidence,
                    uncertainty_score: clamped_fallback_uncertainty,
                    deterministic_fallback_triggered: true,
                    deterministic_fallback_reason: FALLBACK_REASON_UNCLASSIFIED,
                    replay_ref: G7_DECISION_REPLAY_REF,
                    top_evidence_contributors: top_evidence_contributors(snapshot),
                };
            }
        };

        let (confidence_score, uncertainty_score) =
            if outcome.fallback_active && fallback_reason == "none" {
                (clamped_fallback_confidence, clamped_fallback_uncertainty)
            } else {
                (confidence_score, uncertainty_score)
            };

        GovernanceTelemetry {
            decision_id: ctx.decision_id,
            trace_id: ctx.trace_id,
            state_posterior_permille: posterior_permille,
            expected_loss_terms,
            chosen_action: action_label(outcome.action_index),
            confidence_score,
            uncertainty_score,
            deterministic_fallback_triggered: outcome.fallback_active,
            deterministic_fallback_reason: if outcome.fallback_active {
                if fallback_reason == "none" {
                    FALLBACK_REASON_UNCLASSIFIED
                } else {
                    fallback_reason
                }
            } else {
                "none"
            },
            replay_ref: G7_DECISION_REPLAY_REF,
            top_evidence_contributors: top_evidence_contributors(snapshot),
        }
    }

    fn malformed_posterior_fallback_telemetry(
        snapshot: &GovernanceSnapshot,
        posterior_permille: [u16; state::COUNT],
        _error: &ValidationError,
    ) -> GovernanceTelemetry {
        crate::tracing_compat::warn!(
            target: "asupersync::raptorq::decision_contract",
            healthy_permille = posterior_permille[state::HEALTHY],
            degraded_permille = posterior_permille[state::DEGRADED],
            regression_permille = posterior_permille[state::REGRESSION],
            unknown_permille = posterior_permille[state::UNKNOWN],
            error = %_error,
            "raptorq G7 posterior conversion failed; emitting deterministic fallback telemetry"
        );

        let ctx = eval_context(
            snapshot,
            MALFORMED_POSTERIOR_CONFIDENCE,
            MALFORMED_POSTERIOR_UNCERTAINTY,
        );
        GovernanceTelemetry {
            decision_id: ctx.decision_id,
            trace_id: ctx.trace_id,
            state_posterior_permille: posterior_permille,
            expected_loss_terms: MALFORMED_POSTERIOR_EXPECTED_LOSS_TERMS,
            chosen_action: action_label(action::FALLBACK),
            confidence_score: MALFORMED_POSTERIOR_CONFIDENCE,
            uncertainty_score: MALFORMED_POSTERIOR_UNCERTAINTY,
            deterministic_fallback_triggered: true,
            deterministic_fallback_reason: FALLBACK_REASON_UNCLASSIFIED,
            replay_ref: G7_DECISION_REPLAY_REF,
            top_evidence_contributors: top_evidence_contributors(snapshot),
        }
    }
}

impl Default for RaptorQDecisionContract {
    fn default() -> Self {
        Self::new()
    }
}

impl DecisionContract for RaptorQDecisionContract {
    #[allow(clippy::unnecessary_literal_bound)]
    #[inline]
    fn name(&self) -> &str {
        "raptorq_expected_loss_governance"
    }

    #[inline]
    fn state_space(&self) -> &[String] {
        &self.states
    }

    #[inline]
    fn action_set(&self) -> &[String] {
        &self.actions
    }

    #[inline]
    fn loss_matrix(&self) -> &LossMatrix {
        &self.losses
    }

    fn update_posterior(
        &self,
        posterior: &mut Posterior,
        observation: usize,
    ) -> Result<(), franken_decision::UpdatePosteriorError> {
        // br-asupersync-u5uhpt: previously this returned `()` and silently
        // skipped on wrong-length posteriors, allowing stale beliefs to
        // drive subsequent choose_action calls. The trait now signals the
        // condition via a typed error so callers can re-initialise the
        // posterior or escalate to fallback. Tracing is still emitted to
        // preserve the diagnostic surface for SREs scanning logs.
        if posterior.len() != state::COUNT {
            crate::tracing_compat::warn!(
                expected = state::COUNT,
                actual = posterior.len(),
                observation = observation,
                "raptorq G7 update_posterior: wrong-length posterior — update skipped, \
                 next choose_action will fall back to the conservative action"
            );
            return Err(franken_decision::UpdatePosteriorError::LengthMismatch {
                expected: state::COUNT,
                actual: posterior.len(),
            });
        }
        if observation >= state::COUNT {
            crate::tracing_compat::warn!(
                state_count = state::COUNT,
                observation = observation,
                "raptorq G7 update_posterior: observation index out of range — update skipped"
            );
            return Err(
                franken_decision::UpdatePosteriorError::ObservationOutOfRange {
                    observation,
                    state_count: state::COUNT,
                },
            );
        }
        let mut likelihoods = [0.1; state::COUNT];
        likelihoods[observation] = 0.9;
        posterior.bayesian_update(&likelihoods);
        Ok(())
    }

    fn choose_action(&self, posterior: &Posterior) -> usize {
        if posterior.len() != state::COUNT {
            return self.fallback_action();
        }
        choose_action_from_expected_loss_terms(expected_loss_terms(&self.losses, posterior))
    }

    #[inline]
    fn fallback_action(&self) -> usize {
        action::FALLBACK
    }

    #[inline]
    fn fallback_policy(&self) -> &FallbackPolicy {
        &self.fallback
    }
}

impl GovernanceTelemetry {
    /// Format as a single-line structured log entry for forensic replay.
    ///
    /// Output format: `g7_decision: decision_id=<hex> trace_id=<hex>
    /// state_posterior=[h,d,r,u] expected_loss=[c,ch,rb,fb] action=<chosen>
    /// confidence=<n> uncertainty=<n> fallback=<bool> reason=<str> replay=<ref>
    /// top=[name1:w1,name2:w2,name3:w3]`
    #[must_use]
    pub fn to_structured_log(&self) -> String {
        format!(
            "g7_decision: decision_id={} trace_id={} \
             state_posterior=[{},{},{},{}] expected_loss=[{},{},{},{}] \
             action={} confidence={} uncertainty={} fallback={} reason={} \
             replay={} top=[{}:{},{}:{},{}:{}]",
            self.decision_id,
            self.trace_id,
            self.state_posterior_permille[state::HEALTHY],
            self.state_posterior_permille[state::DEGRADED],
            self.state_posterior_permille[state::REGRESSION],
            self.state_posterior_permille[state::UNKNOWN],
            self.expected_loss_terms[action::CONTINUE],
            self.expected_loss_terms[action::CANARY_HOLD],
            self.expected_loss_terms[action::ROLLBACK],
            self.expected_loss_terms[action::FALLBACK],
            self.chosen_action,
            self.confidence_score,
            self.uncertainty_score,
            self.deterministic_fallback_triggered,
            self.deterministic_fallback_reason,
            self.replay_ref,
            self.top_evidence_contributors[0].name,
            self.top_evidence_contributors[0].contribution_permille,
            self.top_evidence_contributors[1].name,
            self.top_evidence_contributors[1].contribution_permille,
            self.top_evidence_contributors[2].name,
            self.top_evidence_contributors[2].contribution_permille,
        )
    }
}

impl fmt::Display for GovernanceTelemetry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_structured_log())
    }
}

/// Evaluate a snapshot with the canonical G7 contract.
#[must_use]
pub fn evaluate_governance(snapshot: &GovernanceSnapshot) -> GovernanceTelemetry {
    RaptorQDecisionContract::new().telemetry(snapshot)
}

/// Returns true when `reason` is a canonical runtime-emittable G7 fallback reason.
#[must_use]
#[inline]
pub fn is_runtime_fallback_reason(reason: &str) -> bool {
    G7_RUNTIME_FALLBACK_REASONS.contains(&reason)
}

#[inline]
fn clamp_permille(value: usize) -> u32 {
    value.min(PERMILLE_SCALE as usize) as u32
}

fn normalize_permille_generic<const N: usize>(scores: [u32; N], zero_total: [u16; N]) -> [u16; N] {
    let total: u32 = scores.iter().sum();
    if total == 0 {
        return zero_total;
    }

    let mut normalized = [0u16; N];
    let mut remainders = [(0usize, 0u32); N];
    let mut assigned = 0u32;
    for (index, score) in scores.iter().copied().enumerate() {
        let scaled = score.saturating_mul(PERMILLE_SCALE);
        let base = scaled / total;
        // Cap to u16::MAX if base exceeds u16 range (pathological case)
        normalized[index] = u16::try_from(base).unwrap_or(u16::MAX);
        assigned = assigned.saturating_add(base);
        remainders[index] = (index, scaled % total);
    }

    let mut remaining = usize::try_from(PERMILLE_SCALE.saturating_sub(assigned)).unwrap_or(0); // fallback to 0 if conversion fails
    remainders.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    for (index, remainder) in remainders {
        if remaining == 0 || remainder == 0 {
            break;
        }
        normalized[index] = normalized[index].saturating_add(1);
        remaining -= 1;
    }

    normalized
}

#[inline]
fn normalize_permille(scores: [u32; state::COUNT]) -> [u16; state::COUNT] {
    normalize_permille_generic(scores, [250; state::COUNT])
}

#[inline]
fn normalize_contributor_permille(scores: [u32; 3]) -> [u16; 3] {
    normalize_permille_generic(scores, [0; 3])
}

#[inline]
fn posterior_from_permille(
    posterior_permille: [u16; state::COUNT],
) -> Result<Posterior, ValidationError> {
    Posterior::new(
        posterior_permille
            .into_iter()
            .map(|value| f64::from(value) / f64::from(PERMILLE_SCALE))
            .collect(),
    )
}

#[inline]
fn policy_conflict_permille(snapshot: &GovernanceSnapshot) -> u16 {
    let mut best = u32::MAX;
    let mut second = u32::MAX;
    for loss in [
        snapshot.baseline_loss,
        snapshot.high_support_loss,
        snapshot.block_schur_loss,
    ] {
        if loss == u32::MAX {
            continue;
        }
        if loss < best {
            second = best;
            best = loss;
        } else if loss < second {
            second = loss;
        }
    }

    if second == u32::MAX {
        return PERMILLE_SCALE as u16;
    }
    let margin = second.saturating_sub(best).min(MODE_MARGIN_CAP);
    ((MODE_MARGIN_CAP - margin) * PERMILLE_SCALE / MODE_MARGIN_CAP) as u16
}

fn expected_loss_terms(losses: &LossMatrix, posterior: &Posterior) -> [u32; action::COUNT] {
    let mut terms = [0u32; action::COUNT];
    for (index, term) in terms.iter_mut().enumerate() {
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        {
            *term = losses.expected_loss(posterior, index).round() as u32;
        }
    }
    terms
}

#[inline]
fn choose_action_from_expected_loss_terms(expected_loss_terms: [u32; action::COUNT]) -> usize {
    // G7 uses a conservative deterministic tie-breaker:
    // fallback > rollback > canary_hold > continue.
    (0..action::COUNT)
        .min_by(|&a, &b| {
            expected_loss_terms[a]
                .cmp(&expected_loss_terms[b])
                .then_with(|| b.cmp(&a))
        })
        .unwrap_or(action::FALLBACK)
}

#[inline]
fn concentration_score(posterior_permille: [u16; state::COUNT]) -> u16 {
    let max_prob = posterior_permille.into_iter().max().unwrap_or(250);
    if max_prob <= 250 {
        return 0;
    }
    ((u32::from(max_prob - 250) * PERMILLE_SCALE) / 750) as u16
}

#[inline]
fn action_margin_score(expected_loss_terms: [u32; action::COUNT]) -> u16 {
    let mut ordered = expected_loss_terms;
    ordered.sort_unstable();
    let gap = ordered[1].saturating_sub(ordered[0]).min(ACTION_MARGIN_CAP);
    (gap * PERMILLE_SCALE / ACTION_MARGIN_CAP) as u16
}

#[inline]
fn dominant_state(posterior_permille: [u16; state::COUNT]) -> usize {
    posterior_permille
        .iter()
        .copied()
        .enumerate()
        .max_by_key(|&(index, value)| (value, std::cmp::Reverse(index)))
        .map_or(state::HEALTHY, |(index, _)| index)
}

fn deterministic_fallback_reason(
    snapshot: &GovernanceSnapshot,
    posterior_permille: [u16; state::COUNT],
    confidence_score: u16,
) -> &'static str {
    if snapshot.budget_exhausted {
        return FALLBACK_REASON_POLICY_BUDGET_EXHAUSTED;
    }

    match dominant_state(posterior_permille) {
        state::UNKNOWN if confidence_score < 350 => FALLBACK_REASON_UNKNOWN_LOW_CONFIDENCE,
        state::REGRESSION if snapshot.rank_deficit_permille >= 600 && confidence_score < 500 => {
            FALLBACK_REASON_REGRESSION_LOW_CONFIDENCE
        }
        _ => "none",
    }
}

fn eval_context(
    snapshot: &GovernanceSnapshot,
    confidence_score: u16,
    uncertainty_score: u16,
) -> EvalContext {
    let mut hasher = DetHasher::default();
    snapshot.hash(&mut hasher);
    confidence_score.hash(&mut hasher);
    uncertainty_score.hash(&mut hasher);
    let fingerprint = u128::from(hasher.finish());
    // br-asupersync-s2jxu0 — derive ts_unix_ms from a stable
    // DetHasher mix over the full bit width of n_rows + n_cols
    // rather than the prior bit-pack
    //   ((n_rows as u64) << 32) | ((n_cols as u64) & 0xFFFF_FFFF)
    // which silently truncated bits >= 32 of either dimension on
    // 64-bit targets, producing colliding ts_unix_ms (and hence
    // colliding DecisionId / TraceId) for distinct (n_rows, n_cols)
    // pairs differing only in those bits — a violation of the
    // unique-decision invariant the contract relies on for replay
    // and dedup. DetHasher.write_usize covers every bit of usize on
    // both 32- and 64-bit targets; the domain tag prevents this
    // mix from colliding with `fingerprint` (which already covers
    // the snapshot via snapshot.hash but with a different schema).
    let mut ts_hasher = DetHasher::default();
    ts_hasher.write_u64(0x7333_3273_6a78_7530); // domain tag "s2sjxu0"
    ts_hasher.write_usize(snapshot.n_rows);
    ts_hasher.write_usize(snapshot.n_cols);
    let ts_unix_ms = ts_hasher.finish();
    let e_process = 1.0
        + f64::from(
            snapshot
                .rank_deficit_permille
                .max(snapshot.inactivation_pressure_permille) as u32,
        ) / 450.0
        + if snapshot.budget_exhausted { 1.2 } else { 0.0 };

    EvalContext {
        calibration_score: f64::from(confidence_score) / f64::from(PERMILLE_SCALE),
        e_process,
        ci_width: f64::from(uncertainty_score) / f64::from(PERMILLE_SCALE),
        decision_id: DecisionId::from_parts(ts_unix_ms, fingerprint),
        trace_id: TraceId::from_parts(ts_unix_ms, fingerprint ^ 0xA5A5_A5A5_A5A5),
        ts_unix_ms,
    }
}

fn top_evidence_contributors(snapshot: &GovernanceSnapshot) -> [GovernanceEvidenceContributor; 3] {
    let density = clamp_permille(snapshot.density_permille);
    let rank = clamp_permille(snapshot.rank_deficit_permille);
    let inactivation = clamp_permille(snapshot.inactivation_pressure_permille);
    let overhead = clamp_permille(snapshot.overhead_ratio_permille);
    let conflict = u32::from(policy_conflict_permille(snapshot));

    let mut signals = [
        (
            0usize,
            "correctness_mismatch_signal",
            rank * 5 / 10 + if snapshot.budget_exhausted { 350 } else { 0 } + overhead / 10,
        ),
        (
            1usize,
            "performance_budget_signal",
            density * 3 / 10 + overhead * 7 / 20 + inactivation / 10,
        ),
        (
            2usize,
            "instability_signal",
            inactivation * 9 / 20 + if snapshot.budget_exhausted { 140 } else { 0 },
        ),
        (
            3usize,
            "cache_policy_signal",
            density * 3 / 20
                + if snapshot.block_schur_loss == u32::MAX {
                    80
                } else {
                    20
                },
        ),
        (
            4usize,
            "policy_conflict_signal",
            conflict / 2
                + if snapshot.block_schur_loss == u32::MAX {
                    40
                } else {
                    0
                },
        ),
    ];
    signals.sort_by(|a, b| b.2.cmp(&a.2).then_with(|| a.0.cmp(&b.0)));

    let normalized = normalize_contributor_permille([signals[0].2, signals[1].2, signals[2].2]);

    [
        GovernanceEvidenceContributor {
            name: signals[0].1,
            contribution_permille: normalized[0],
        },
        GovernanceEvidenceContributor {
            name: signals[1].1,
            contribution_permille: normalized[1],
        },
        GovernanceEvidenceContributor {
            name: signals[2].1,
            contribution_permille: normalized[2],
        },
    ]
}

#[inline]
const fn action_label(index: usize) -> &'static str {
    match index {
        action::CONTINUE => "continue",
        action::CANARY_HOLD => "canary_hold",
        action::ROLLBACK => "rollback",
        // FALLBACK and any out-of-range index both map to fallback.
        _ => "fallback",
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;

    #[test]
    fn healthy_snapshot_has_dominant_healthy_posterior() {
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 24,
            n_cols: 16,
            density_permille: 90,
            rank_deficit_permille: 0,
            inactivation_pressure_permille: 80,
            overhead_ratio_permille: 120,
            budget_exhausted: false,
            baseline_loss: 540,
            high_support_loss: 760,
            block_schur_loss: u32::MAX,
        });

        // With missing block_schur (u32::MAX) there is non-trivial uncertainty,
        // so the expected-loss-optimal action is canary_hold (cautious monitoring).
        // The loss matrix favors canary_hold when degraded/unknown mass > ~15%.
        assert!(
            telemetry.chosen_action == "canary_hold" || telemetry.chosen_action == "continue",
            "healthy snapshot should prefer canary_hold or continue, got: {}",
            telemetry.chosen_action
        );
        assert!(!telemetry.deterministic_fallback_triggered);
        assert_eq!(telemetry.replay_ref, G7_DECISION_REPLAY_REF);
        assert!(
            telemetry.state_posterior_permille[state::HEALTHY]
                > telemetry.state_posterior_permille[state::DEGRADED]
        );
    }

    #[test]
    fn very_clean_snapshot_prefers_continue() {
        // Minimal pressure, all losses available and well-separated
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 16,
            n_cols: 12,
            density_permille: 20,
            rank_deficit_permille: 0,
            inactivation_pressure_permille: 10,
            overhead_ratio_permille: 15,
            budget_exhausted: false,
            baseline_loss: 100,
            high_support_loss: 800,
            block_schur_loss: 900,
        });

        assert_eq!(
            telemetry.chosen_action, "continue",
            "very clean snapshot with well-separated losses should prefer continue"
        );
        assert!(!telemetry.deterministic_fallback_triggered);
    }

    #[test]
    fn surfaced_expected_loss_ties_drive_the_reported_action() {
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 24,
            n_cols: 16,
            density_permille: 0,
            rank_deficit_permille: 0,
            inactivation_pressure_permille: 0,
            overhead_ratio_permille: 150,
            budget_exhausted: false,
            baseline_loss: 520,
            high_support_loss: 900,
            block_schur_loss: 900,
        });

        assert!(!telemetry.deterministic_fallback_triggered);
        assert_eq!(
            telemetry.expected_loss_terms[action::CONTINUE],
            telemetry.expected_loss_terms[action::CANARY_HOLD],
            "regression fixture requires a surfaced tie on the minimum expected-loss terms"
        );
        assert_eq!(
            telemetry.chosen_action,
            action_label(choose_action_from_expected_loss_terms(
                telemetry.expected_loss_terms,
            )),
        );
        assert_eq!(telemetry.chosen_action, "canary_hold");
    }

    #[test]
    fn exact_canary_hold_action_is_reported_without_fallback() {
        let contract = RaptorQDecisionContract::new();
        let snapshot = GovernanceSnapshot {
            n_rows: 24,
            n_cols: 16,
            density_permille: 0,
            rank_deficit_permille: 0,
            inactivation_pressure_permille: 0,
            overhead_ratio_permille: 0,
            budget_exhausted: false,
            baseline_loss: 500,
            high_support_loss: 520,
            block_schur_loss: 540,
        };

        let telemetry = contract.telemetry(&snapshot);
        let ctx = eval_context(
            &snapshot,
            telemetry.confidence_score,
            telemetry.uncertainty_score,
        );
        let fallback = contract.fallback_policy();

        assert_eq!(telemetry.chosen_action, "canary_hold");
        assert!(!telemetry.deterministic_fallback_triggered);
        assert_eq!(telemetry.deterministic_fallback_reason, "none");
        assert!(
            telemetry.expected_loss_terms[action::CANARY_HOLD]
                < telemetry.expected_loss_terms[action::CONTINUE]
        );
        assert!(
            telemetry.expected_loss_terms[action::CANARY_HOLD]
                < telemetry.expected_loss_terms[action::ROLLBACK]
        );
        assert!(
            telemetry.expected_loss_terms[action::CANARY_HOLD]
                < telemetry.expected_loss_terms[action::FALLBACK]
        );
        assert!(ctx.calibration_score >= fallback.calibration_drift_threshold);
        assert!(ctx.e_process <= fallback.e_process_breach_threshold);
        assert!(ctx.ci_width <= fallback.confidence_width_threshold);
    }

    #[test]
    fn budget_exhaustion_forces_fallback() {
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 65,
            n_cols: 65,
            density_permille: 1000,
            rank_deficit_permille: 500,
            inactivation_pressure_permille: 900,
            overhead_ratio_permille: 0,
            budget_exhausted: true,
            baseline_loss: 1024,
            high_support_loss: 1700,
            block_schur_loss: 1600,
        });

        assert_eq!(telemetry.chosen_action, "fallback");
        assert!(telemetry.deterministic_fallback_triggered);
        assert_eq!(
            telemetry.deterministic_fallback_reason,
            FALLBACK_REASON_POLICY_BUDGET_EXHAUSTED
        );
    }

    #[test]
    fn policy_fallback_never_reports_none_reason() {
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 48,
            n_cols: 32,
            density_permille: 10,
            rank_deficit_permille: 0,
            inactivation_pressure_permille: 600,
            overhead_ratio_permille: 0,
            budget_exhausted: false,
            baseline_loss: 100,
            high_support_loss: 800,
            block_schur_loss: 900,
        });

        assert!(
            telemetry.deterministic_fallback_triggered,
            "e-process breach should activate fallback"
        );
        assert_eq!(telemetry.chosen_action, "fallback");
        assert_eq!(
            telemetry.deterministic_fallback_reason, FALLBACK_REASON_UNCLASSIFIED,
            "fallback-active telemetry must never report reason=none"
        );
        assert!(
            telemetry.confidence_score <= 250,
            "fallback-active telemetry must clamp surfaced confidence even when the reason is synthesized"
        );
        assert_eq!(
            telemetry.confidence_score + telemetry.uncertainty_score,
            1000,
            "fallback-active telemetry must keep confidence/uncertainty normalized after clamping"
        );
    }

    #[test]
    fn explicit_regression_low_confidence_reason_is_reported() {
        let contract = RaptorQDecisionContract::new();
        let snapshot = GovernanceSnapshot {
            n_rows: 48,
            n_cols: 32,
            density_permille: 0,
            rank_deficit_permille: 650,
            inactivation_pressure_permille: 150,
            overhead_ratio_permille: 100,
            budget_exhausted: false,
            baseline_loss: 500,
            high_support_loss: 520,
            block_schur_loss: 540,
        };

        let posterior_permille = RaptorQDecisionContract::state_posterior_permille(&snapshot);
        let posterior = posterior_from_permille(posterior_permille)
            .expect("state_posterior_permille must produce a valid posterior");
        let preliminary_confidence = (((u32::from(concentration_score(posterior_permille)) * 7)
            + (u32::from(action_margin_score(expected_loss_terms(
                contract.loss_matrix(),
                &posterior,
            ))) * 3))
            / 10) as u16;
        let telemetry = contract.telemetry(&snapshot);

        assert!(posterior_permille[state::REGRESSION] > posterior_permille[state::HEALTHY]);
        assert!(posterior_permille[state::REGRESSION] > posterior_permille[state::DEGRADED]);
        assert!(posterior_permille[state::REGRESSION] > posterior_permille[state::UNKNOWN]);
        assert!(
            preliminary_confidence < 500,
            "test must stay on the low-confidence side of the explicit REGRESSION fallback seam"
        );
        assert_eq!(
            deterministic_fallback_reason(&snapshot, posterior_permille, preliminary_confidence),
            FALLBACK_REASON_REGRESSION_LOW_CONFIDENCE
        );
        assert!(telemetry.deterministic_fallback_triggered);
        assert_eq!(telemetry.chosen_action, "fallback");
        assert_eq!(
            telemetry.deterministic_fallback_reason,
            FALLBACK_REASON_REGRESSION_LOW_CONFIDENCE
        );
        assert!(
            telemetry.confidence_score <= 250,
            "fallback-reason path should clamp surfaced confidence"
        );
    }

    #[test]
    fn telemetry_fields_are_normalized_and_stable() {
        let snapshot = GovernanceSnapshot {
            n_rows: 18,
            n_cols: 16,
            density_permille: 820,
            rank_deficit_permille: 140,
            inactivation_pressure_permille: 760,
            overhead_ratio_permille: 60,
            budget_exhausted: false,
            baseline_loss: 1180,
            high_support_loss: 900,
            block_schur_loss: 880,
        };

        let first = evaluate_governance(&snapshot);
        let second = evaluate_governance(&snapshot);

        assert_eq!(first, second, "governance evaluation must be deterministic");
        assert_eq!(
            first
                .state_posterior_permille
                .iter()
                .map(|&value| u32::from(value))
                .sum::<u32>(),
            PERMILLE_SCALE
        );
        assert_eq!(
            first
                .top_evidence_contributors
                .iter()
                .map(|entry| u32::from(entry.contribution_permille))
                .sum::<u32>(),
            PERMILLE_SCALE
        );
        assert!(first.confidence_score <= 1000);
        assert!(first.uncertainty_score <= 1000);
    }

    #[test]
    fn high_pressure_snapshot_prefers_rollback_or_fallback() {
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 64,
            n_cols: 64,
            density_permille: 950,
            rank_deficit_permille: 800,
            inactivation_pressure_permille: 850,
            overhead_ratio_permille: 700,
            budget_exhausted: false,
            baseline_loss: 2000,
            high_support_loss: 1800,
            block_schur_loss: 1900,
        });

        assert!(
            telemetry.chosen_action == "rollback" || telemetry.chosen_action == "fallback",
            "high-pressure snapshot should prefer rollback or fallback, got: {}",
            telemetry.chosen_action
        );
        assert!(
            telemetry.state_posterior_permille[state::REGRESSION]
                > telemetry.state_posterior_permille[state::HEALTHY],
            "regression posterior should exceed healthy under high pressure"
        );
    }

    #[test]
    fn exact_rollback_action_is_reported_without_fallback() {
        let contract = RaptorQDecisionContract::new();
        let snapshot = GovernanceSnapshot {
            n_rows: 40,
            n_cols: 32,
            density_permille: 500,
            rank_deficit_permille: 50,
            inactivation_pressure_permille: 400,
            overhead_ratio_permille: 600,
            budget_exhausted: false,
            baseline_loss: 100,
            high_support_loss: 800,
            block_schur_loss: 900,
        };

        let telemetry = contract.telemetry(&snapshot);
        let ctx = eval_context(
            &snapshot,
            telemetry.confidence_score,
            telemetry.uncertainty_score,
        );
        let fallback = contract.fallback_policy();

        assert_eq!(telemetry.chosen_action, "rollback");
        assert!(!telemetry.deterministic_fallback_triggered);
        assert_eq!(telemetry.deterministic_fallback_reason, "none");
        assert!(
            telemetry.expected_loss_terms[action::ROLLBACK]
                < telemetry.expected_loss_terms[action::CONTINUE]
        );
        assert!(
            telemetry.expected_loss_terms[action::ROLLBACK]
                < telemetry.expected_loss_terms[action::CANARY_HOLD]
        );
        assert!(
            telemetry.expected_loss_terms[action::ROLLBACK]
                < telemetry.expected_loss_terms[action::FALLBACK]
        );
        assert!(ctx.calibration_score >= fallback.calibration_drift_threshold);
        assert!(ctx.e_process <= fallback.e_process_breach_threshold);
        assert!(ctx.ci_width <= fallback.confidence_width_threshold);
    }

    #[test]
    fn moderate_pressure_selects_conservative_action() {
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 32,
            n_cols: 24,
            density_permille: 450,
            rank_deficit_permille: 200,
            inactivation_pressure_permille: 400,
            overhead_ratio_permille: 350,
            budget_exhausted: false,
            baseline_loss: 800,
            high_support_loss: 600,
            block_schur_loss: 750,
        });

        // Under moderate pressure the expected-loss engine may select
        // canary_hold, rollback, or fallback depending on posterior shape.
        assert!(
            telemetry.chosen_action != "continue",
            "moderate pressure should not prefer continue, got: {}",
            telemetry.chosen_action
        );
    }

    #[test]
    fn unknown_state_low_confidence_triggers_fallback() {
        // Conflicting policy signals + missing block_schur → high unknown posterior
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 40,
            n_cols: 32,
            density_permille: 300,
            rank_deficit_permille: 100,
            inactivation_pressure_permille: 200,
            overhead_ratio_permille: 100,
            budget_exhausted: true,
            baseline_loss: 500,
            high_support_loss: 500,
            block_schur_loss: u32::MAX,
        });

        assert!(
            telemetry.deterministic_fallback_triggered,
            "budget exhaustion should trigger deterministic fallback"
        );
        assert_eq!(telemetry.chosen_action, "fallback");
    }

    #[test]
    fn explicit_unknown_low_confidence_reason_is_reported() {
        // Missing block_schur plus maximally conflicting policy losses make UNKNOWN
        // the dominant posterior state, while high rank pressure keeps confidence low
        // without relying on the separate budget-exhaustion fallback path.
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 48,
            n_cols: 32,
            density_permille: 0,
            rank_deficit_permille: 650,
            inactivation_pressure_permille: 0,
            overhead_ratio_permille: 190,
            budget_exhausted: false,
            baseline_loss: 500,
            high_support_loss: 500,
            block_schur_loss: u32::MAX,
        });

        assert!(
            telemetry.state_posterior_permille[state::UNKNOWN]
                > telemetry.state_posterior_permille[state::HEALTHY]
        );
        assert!(
            telemetry.state_posterior_permille[state::UNKNOWN]
                > telemetry.state_posterior_permille[state::DEGRADED]
        );
        assert!(
            telemetry.state_posterior_permille[state::UNKNOWN]
                > telemetry.state_posterior_permille[state::REGRESSION]
        );
        assert!(
            telemetry.confidence_score < 350,
            "test must stay on the low-confidence side of the explicit UNKNOWN fallback seam"
        );
        assert!(
            telemetry.deterministic_fallback_triggered,
            "explicit low-confidence UNKNOWN path must trigger deterministic fallback"
        );
        assert_eq!(telemetry.chosen_action, "fallback");
        assert_eq!(
            telemetry.deterministic_fallback_reason,
            FALLBACK_REASON_UNKNOWN_LOW_CONFIDENCE
        );
    }

    #[test]
    fn conflicting_evidence_raises_uncertainty() {
        // All policy losses are nearly identical → high conflict → high unknown
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 20,
            n_cols: 16,
            density_permille: 200,
            rank_deficit_permille: 50,
            inactivation_pressure_permille: 100,
            overhead_ratio_permille: 50,
            budget_exhausted: false,
            baseline_loss: 1000,
            high_support_loss: 1001,
            block_schur_loss: 1002,
        });

        // With closely matched losses, uncertainty should be material
        assert!(
            telemetry.uncertainty_score >= 500,
            "conflicting evidence should produce high uncertainty, got: {}",
            telemetry.uncertainty_score
        );
    }

    #[test]
    fn structured_log_contains_all_required_fields() {
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 24,
            n_cols: 16,
            density_permille: 90,
            rank_deficit_permille: 0,
            inactivation_pressure_permille: 80,
            overhead_ratio_permille: 120,
            budget_exhausted: false,
            baseline_loss: 540,
            high_support_loss: 760,
            block_schur_loss: u32::MAX,
        });

        let log = telemetry.to_structured_log();

        assert!(
            log.starts_with("g7_decision:"),
            "log must start with g7_decision prefix"
        );
        assert!(log.contains("decision_id="), "log must include decision id");
        assert!(log.contains("trace_id="), "log must include trace id");
        assert!(
            log.contains("state_posterior="),
            "log must include state_posterior"
        );
        assert!(
            log.contains("expected_loss="),
            "log must include expected_loss"
        );
        assert!(log.contains("action="), "log must include chosen action");
        assert!(
            log.contains("confidence="),
            "log must include confidence score"
        );
        assert!(
            log.contains("uncertainty="),
            "log must include uncertainty score"
        );
        assert!(log.contains("fallback="), "log must include fallback flag");
        assert!(log.contains("reason="), "log must include fallback reason");
        assert!(log.contains("replay="), "log must include replay ref");
        assert!(
            log.contains("top="),
            "log must include top evidence contributors"
        );
        assert!(
            log.contains(&format!("decision_id={}", telemetry.decision_id)),
            "log decision id must match telemetry"
        );
        assert!(
            log.contains(&format!("trace_id={}", telemetry.trace_id)),
            "log trace id must match telemetry"
        );
    }

    #[test]
    fn display_impl_matches_structured_log() {
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 24,
            n_cols: 16,
            density_permille: 500,
            rank_deficit_permille: 300,
            inactivation_pressure_permille: 400,
            overhead_ratio_permille: 200,
            budget_exhausted: false,
            baseline_loss: 800,
            high_support_loss: 900,
            block_schur_loss: 850,
        });

        assert_eq!(
            format!("{telemetry}"),
            telemetry.to_structured_log(),
            "Display impl must match to_structured_log"
        );
    }

    #[test]
    fn replay_reproducibility_across_contract_instances() {
        let snapshot = GovernanceSnapshot {
            n_rows: 48,
            n_cols: 32,
            density_permille: 600,
            rank_deficit_permille: 250,
            inactivation_pressure_permille: 500,
            overhead_ratio_permille: 300,
            budget_exhausted: false,
            baseline_loss: 1200,
            high_support_loss: 950,
            block_schur_loss: 1100,
        };

        let contract_a = RaptorQDecisionContract::new();
        let contract_b = RaptorQDecisionContract::new();

        let telemetry_a = contract_a.telemetry(&snapshot);
        let telemetry_b = contract_b.telemetry(&snapshot);

        assert_eq!(
            telemetry_a, telemetry_b,
            "different contract instances must produce identical telemetry for the same snapshot"
        );
        assert_eq!(
            telemetry_a.to_structured_log(),
            telemetry_b.to_structured_log(),
            "structured log output must be identical across instances"
        );
    }

    #[test]
    fn confidence_uncertainty_are_complementary() {
        for (density, rank, inact, overhead) in [
            (0, 0, 0, 0),
            (500, 500, 500, 500),
            (1000, 1000, 1000, 1000),
            (100, 900, 50, 200),
        ] {
            let telemetry = evaluate_governance(&GovernanceSnapshot {
                n_rows: 32,
                n_cols: 24,
                density_permille: density,
                rank_deficit_permille: rank,
                inactivation_pressure_permille: inact,
                overhead_ratio_permille: overhead,
                budget_exhausted: false,
                baseline_loss: 600,
                high_support_loss: 800,
                block_schur_loss: 700,
            });

            assert_eq!(
                telemetry.confidence_score + telemetry.uncertainty_score,
                1000,
                "confidence + uncertainty must equal 1000 for density={density} rank={rank}"
            );
        }
    }

    #[test]
    fn all_actions_are_reachable() {
        // Very clean → continue (well-separated losses, no missing block_schur)
        let healthy = evaluate_governance(&GovernanceSnapshot {
            n_rows: 16,
            n_cols: 12,
            density_permille: 20,
            rank_deficit_permille: 0,
            inactivation_pressure_permille: 10,
            overhead_ratio_permille: 15,
            budget_exhausted: false,
            baseline_loss: 100,
            high_support_loss: 800,
            block_schur_loss: 900,
        });
        assert_eq!(healthy.chosen_action, "continue");

        // Budget exhausted → fallback
        let exhausted = evaluate_governance(&GovernanceSnapshot {
            n_rows: 64,
            n_cols: 64,
            density_permille: 900,
            rank_deficit_permille: 700,
            inactivation_pressure_permille: 800,
            overhead_ratio_permille: 600,
            budget_exhausted: true,
            baseline_loss: 2000,
            high_support_loss: 1800,
            block_schur_loss: 1900,
        });
        assert_eq!(exhausted.chosen_action, "fallback");

        // Verify each action is a valid label
        for action_name in &["continue", "canary_hold", "rollback", "fallback"] {
            let idx = match *action_name {
                "continue" => action::CONTINUE,
                "canary_hold" => action::CANARY_HOLD,
                "rollback" => action::ROLLBACK,
                "fallback" => action::FALLBACK,
                _ => unreachable!(),
            };
            assert_eq!(action_label(idx), *action_name);
        }
    }

    #[test]
    fn action_label_out_of_range_returns_fallback() {
        assert_eq!(action_label(99), "fallback");
        assert_eq!(action_label(usize::MAX), "fallback");
    }

    #[test]
    fn normalize_permille_zero_total_gives_uniform() {
        let result = normalize_permille([0, 0, 0, 0]);
        assert_eq!(result, [250, 250, 250, 250]);
    }

    #[test]
    fn normalize_permille_does_not_assign_remainder_to_zero_score_bucket() {
        let result = normalize_permille([1, 1, 1, 0]);
        assert_eq!(result, [334, 333, 333, 0]);
    }

    #[test]
    fn posterior_from_permille_rejects_malformed_distribution() {
        let err = posterior_from_permille([1000, 1000, 1000, 1000])
            .expect_err("non-normalized permille input must not construct a posterior");

        assert!(
            matches!(err, ValidationError::PosteriorNotNormalized { sum } if (sum - 4.0).abs() < f64::EPSILON),
            "expected PosteriorNotNormalized, got {err:?}"
        );
    }

    #[test]
    fn malformed_posterior_telemetry_fails_closed_with_full_uncertainty() {
        let snapshot = GovernanceSnapshot {
            n_rows: 48,
            n_cols: 32,
            density_permille: 400,
            rank_deficit_permille: 250,
            inactivation_pressure_permille: 300,
            overhead_ratio_permille: 150,
            budget_exhausted: false,
            baseline_loss: 500,
            high_support_loss: 520,
            block_schur_loss: 540,
        };
        let posterior_permille = [1000, 1000, 1000, 1000];
        let error = posterior_from_permille(posterior_permille)
            .expect_err("malformed posterior fixture must reject before telemetry fallback");
        let telemetry = RaptorQDecisionContract::malformed_posterior_fallback_telemetry(
            &snapshot,
            posterior_permille,
            &error,
        );

        assert_eq!(telemetry.state_posterior_permille, posterior_permille);
        assert_eq!(
            telemetry.expected_loss_terms,
            MALFORMED_POSTERIOR_EXPECTED_LOSS_TERMS
        );
        assert_eq!(telemetry.chosen_action, "fallback");
        assert!(telemetry.deterministic_fallback_triggered);
        assert_eq!(
            telemetry.deterministic_fallback_reason,
            FALLBACK_REASON_UNCLASSIFIED
        );
        assert_eq!(telemetry.confidence_score, 0);
        assert_eq!(telemetry.uncertainty_score, 1000);
        assert!(
            is_runtime_fallback_reason(telemetry.deterministic_fallback_reason),
            "malformed posterior fallback must use a canonical runtime reason"
        );
    }

    #[test]
    fn contributor_normalization_does_not_assign_remainder_to_zero_weight() {
        let result = normalize_contributor_permille([2, 1, 0]);
        assert_eq!(result, [667, 333, 0]);
    }

    #[test]
    fn contract_trait_methods_are_consistent() {
        let contract = RaptorQDecisionContract::new();
        assert_eq!(contract.name(), "raptorq_expected_loss_governance");
        assert_eq!(contract.state_space().len(), state::COUNT);
        assert_eq!(contract.action_set().len(), action::COUNT);
        assert_eq!(contract.fallback_action(), action::FALLBACK);

        // Loss matrix dimensions match states × actions
        let losses = contract.loss_matrix();
        for s in 0..state::COUNT {
            for a in 0..action::COUNT {
                let loss = losses.get(s, a);
                assert!(loss >= 0.0, "loss({s},{a}) must be non-negative");
            }
        }
    }

    #[test]
    fn choose_action_uses_conservative_tie_breaker() {
        let contract = RaptorQDecisionContract::new();

        let continue_vs_hold = Posterior::new(vec![0.75, 0.25, 0.0, 0.0]).unwrap();
        assert_eq!(
            contract.choose_action(&continue_vs_hold),
            action::CANARY_HOLD,
            "equal expected loss between continue/canary_hold must prefer canary_hold"
        );

        let rollback_vs_fallback = Posterior::new(vec![0.25, 0.0, 0.75, 0.0]).unwrap();
        assert_eq!(
            contract.choose_action(&rollback_vs_fallback),
            action::FALLBACK,
            "equal expected loss between rollback/fallback must prefer fallback"
        );
    }

    #[test]
    fn posterior_update_concentrates_on_observation() {
        let contract = RaptorQDecisionContract::new();
        let mut posterior = Posterior::uniform(state::COUNT);
        contract
            .update_posterior(&mut posterior, state::REGRESSION)
            .expect("update_posterior succeeds for matching length + valid observation");

        // After observing REGRESSION, its probability should increase
        let probs = posterior.probs();
        assert!(
            probs[state::REGRESSION] > probs[state::HEALTHY],
            "regression probability should exceed healthy after observing regression"
        );
    }

    #[test]
    fn choose_action_fails_closed_for_malformed_posterior_length() {
        let contract = RaptorQDecisionContract::new();
        let malformed = Posterior::new(vec![0.34, 0.33, 0.33]).unwrap();

        assert_eq!(
            contract.choose_action(&malformed),
            action::FALLBACK,
            "malformed posterior length must fail closed to fallback"
        );
    }

    #[test]
    fn posterior_update_returns_length_mismatch_error() {
        // br-asupersync-u5uhpt: previously a wrong-length posterior was
        // a silent no-op. Now it surfaces a typed error and the posterior
        // remains unchanged so callers can fall back deterministically.
        let contract = RaptorQDecisionContract::new();
        let mut malformed = Posterior::new(vec![0.34, 0.33, 0.33]).unwrap();
        let before = malformed.probs().to_vec();

        let err = contract
            .update_posterior(&mut malformed, state::REGRESSION)
            .expect_err("wrong-length posterior must surface a typed error");

        assert!(
            matches!(
                err,
                franken_decision::UpdatePosteriorError::LengthMismatch {
                    expected: state::COUNT,
                    actual: 3,
                }
            ),
            "expected LengthMismatch, got {err:?}"
        );
        assert_eq!(
            malformed.probs(),
            before.as_slice(),
            "malformed posterior length must remain unchanged after update"
        );
    }

    #[test]
    fn posterior_update_returns_observation_out_of_range_error() {
        // br-asupersync-u5uhpt: an out-of-range observation must surface a
        // typed error; the posterior must remain unchanged.
        let contract = RaptorQDecisionContract::new();
        let mut posterior = Posterior::uniform(state::COUNT);
        let before = posterior.probs().to_vec();

        let err = contract
            .update_posterior(&mut posterior, usize::MAX)
            .expect_err("out-of-range observation must surface a typed error");

        assert!(
            matches!(
                err,
                franken_decision::UpdatePosteriorError::ObservationOutOfRange {
                    observation: usize::MAX,
                    state_count: state::COUNT,
                }
            ),
            "expected ObservationOutOfRange, got {err:?}"
        );
        assert_eq!(
            posterior.probs(),
            before.as_slice(),
            "out-of-range observations must not perturb posterior state"
        );
    }

    #[test]
    fn default_impl_matches_new() {
        let from_new = RaptorQDecisionContract::new();
        let from_default = RaptorQDecisionContract::default();
        assert_eq!(from_new.name(), from_default.name());
        assert_eq!(from_new.state_space(), from_default.state_space());
        assert_eq!(from_new.action_set(), from_default.action_set());
    }

    #[test]
    fn runtime_fallback_reason_boundary_matches_live_contract() {
        assert_eq!(
            G7_RUNTIME_FALLBACK_REASONS,
            &[
                FALLBACK_REASON_POLICY_BUDGET_EXHAUSTED,
                FALLBACK_REASON_UNKNOWN_LOW_CONFIDENCE,
                FALLBACK_REASON_REGRESSION_LOW_CONFIDENCE,
                FALLBACK_REASON_UNCLASSIFIED,
            ],
            "live runtime fallback boundary must stay aligned with canonical telemetry reasons"
        );

        for reason in G7_RUNTIME_FALLBACK_REASONS {
            assert!(
                is_runtime_fallback_reason(reason),
                "{reason} must remain runtime-emittable"
            );
        }
    }

    #[test]
    fn broader_contract_only_triggers_are_not_runtime_emittable_reasons() {
        for reason in [
            "decode_mismatch_detected",
            "proof_replay_mismatch",
            "none",
            "unknown_reason",
        ] {
            assert!(
                !is_runtime_fallback_reason(reason),
                "{reason} must stay outside the live runtime-emittable reason boundary"
            );
        }
    }

    #[test]
    fn evidence_contributors_are_always_three() {
        for budget_exhausted in [false, true] {
            let telemetry = evaluate_governance(&GovernanceSnapshot {
                n_rows: 32,
                n_cols: 24,
                density_permille: 500,
                rank_deficit_permille: 300,
                inactivation_pressure_permille: 400,
                overhead_ratio_permille: 200,
                budget_exhausted,
                baseline_loss: 800,
                high_support_loss: 900,
                block_schur_loss: 850,
            });

            assert_eq!(telemetry.top_evidence_contributors.len(), 3);
            for contributor in &telemetry.top_evidence_contributors {
                assert!(
                    !contributor.name.is_empty(),
                    "contributor name must not be empty"
                );
                assert!(
                    contributor.contribution_permille <= 1000,
                    "contributor weight must be <= 1000"
                );
            }
        }
    }

    /// br-asupersync-s2jxu0 — DecisionId / TraceId derived from
    /// (n_rows, n_cols) must NOT collide for distinct dimension
    /// pairs. The previous bit-pack
    ///   `(n_rows as u64) << 32 | (n_cols as u64) & 0xFFFF_FFFF`
    /// silently truncated bits >= 32 of either dimension on 64-bit
    /// targets, producing identical IDs for distinct pairs that
    /// differed only in those bits. The fix derives ts_unix_ms from
    /// a DetHasher mix that covers every bit of usize.
    #[test]
    fn s2jxu0_decision_id_distinct_for_distinct_dimensions() {
        fn snapshot_with(n_rows: usize, n_cols: usize) -> GovernanceSnapshot {
            GovernanceSnapshot {
                n_rows,
                n_cols,
                density_permille: 0,
                rank_deficit_permille: 0,
                inactivation_pressure_permille: 0,
                overhead_ratio_permille: 0,
                budget_exhausted: false,
                baseline_loss: 0,
                high_support_loss: 0,
                block_schur_loss: 0,
            }
        }

        // Value pair from the bead instructions: u32::MAX vs u32::MAX-1.
        let a = eval_context(
            &snapshot_with(u32::MAX as usize, (u32::MAX - 1) as usize),
            500,
            500,
        );
        let b = eval_context(
            &snapshot_with((u32::MAX - 1) as usize, u32::MAX as usize),
            500,
            500,
        );
        assert_ne!(
            a.decision_id, b.decision_id,
            "swapping (n_rows, n_cols) must yield distinct DecisionIds"
        );
        assert_ne!(
            a.trace_id, b.trace_id,
            "swapping (n_rows, n_cols) must yield distinct TraceIds"
        );

        // 64-bit-only collision pair: differs only in bits >= 32 of
        // n_rows. Under the old shift-truncating logic these would
        // produce the same ts_unix_ms; under the fix they must
        // differ.
        #[cfg(target_pointer_width = "64")]
        {
            let small = eval_context(&snapshot_with(1, 1), 500, 500);
            // n_rows = 1 + (1 << 32); on the OLD `(n_rows as u64) << 32`
            // path, the bit at index 32 shifts out of u64 and the low
            // bit ends up at position 32 — the same as the small
            // snapshot's encoding. After the fix, full-bit-width
            // hashing makes them distinct.
            let big = eval_context(&snapshot_with(1 + (1usize << 32), 1), 500, 500);
            assert_ne!(
                small.decision_id, big.decision_id,
                "(1,1) and (1+2^32,1) must NOT collide after s2jxu0 fix"
            );
            assert_ne!(
                small.trace_id, big.trace_id,
                "(1,1) and (1+2^32,1) must NOT collide after s2jxu0 fix"
            );
        }

        // Stress: 100 distinct dimension pairs all produce distinct
        // ts_unix_ms surrogates.
        let mut seen = std::collections::HashSet::new();
        for r in 0..10usize {
            for c in 0..10usize {
                let ctx = eval_context(&snapshot_with(r, c), 500, 500);
                assert!(
                    seen.insert(ctx.ts_unix_ms),
                    "duplicate ts_unix_ms for ({r},{c})"
                );
            }
        }
        assert_eq!(seen.len(), 100);
    }

    /// br-asupersync-gqnv2o: when `outcome.fallback_active` is true
    /// AND the deterministic_fallback_reason resolves to "none" (the
    /// UNCLASSIFIED bucket at the publish site), the published
    /// `confidence_score` MUST be the clamped fallback ceiling (250)
    /// rather than the unclamped `preliminary_confidence`. Pre-fix the
    /// triple was inconsistent — a downstream rollback gate that
    /// keys on `(deterministic_fallback_triggered=true,
    /// confidence_score < threshold)` would observe (true, high) and
    /// silently skip the safety branch despite the explicit fallback
    /// signal. The fix re-binds confidence_score and uncertainty_score
    /// to the clamped values when the asymmetry is observed; this
    /// test pins the contract.
    #[test]
    fn gqnv2o_named_fallback_clamps_confidence_to_ceiling() {
        let telemetry = evaluate_governance(&GovernanceSnapshot {
            n_rows: 24,
            n_cols: 16,
            density_permille: 90,
            rank_deficit_permille: 0,
            inactivation_pressure_permille: 80,
            overhead_ratio_permille: 120,
            budget_exhausted: true,
            baseline_loss: 540,
            high_support_loss: 760,
            block_schur_loss: u32::MAX,
        });
        assert!(telemetry.deterministic_fallback_triggered);
        assert!(
            telemetry.confidence_score <= 250,
            "named-reason fallback must clamp confidence to <= 250, \
             got {}",
            telemetry.confidence_score
        );
        assert_eq!(
            u32::from(telemetry.uncertainty_score) + u32::from(telemetry.confidence_score),
            1000
        );
    }

    /// br-asupersync-gqnv2o: defensive sweep — for every snapshot in
    /// a small adversarial set, the
    /// `(deterministic_fallback_triggered=true ⇒ confidence_score<=250)`
    /// implication MUST hold. Catches any future code path that
    /// re-introduces the pre-fix asymmetry.
    #[test]
    fn gqnv2o_fallback_implies_clamped_confidence_invariant() {
        let snapshots = [
            GovernanceSnapshot {
                n_rows: 16,
                n_cols: 16,
                density_permille: 100,
                rank_deficit_permille: 0,
                inactivation_pressure_permille: 0,
                overhead_ratio_permille: 0,
                budget_exhausted: true,
                baseline_loss: 0,
                high_support_loss: 0,
                block_schur_loss: 0,
            },
            GovernanceSnapshot {
                n_rows: 32,
                n_cols: 16,
                density_permille: 200,
                rank_deficit_permille: 100,
                inactivation_pressure_permille: 200,
                overhead_ratio_permille: 250,
                budget_exhausted: true,
                baseline_loss: u32::MAX,
                high_support_loss: u32::MAX,
                block_schur_loss: u32::MAX,
            },
        ];
        for (i, s) in snapshots.iter().enumerate() {
            let telemetry = evaluate_governance(s);
            if telemetry.deterministic_fallback_triggered {
                assert!(
                    telemetry.confidence_score <= 250,
                    "snapshot[{i}]: fallback triggered but confidence={} \
                     — gate would not engage rollback (br-asupersync-gqnv2o)",
                    telemetry.confidence_score
                );
                assert_eq!(
                    u32::from(telemetry.uncertainty_score) + u32::from(telemetry.confidence_score),
                    1000,
                    "snapshot[{i}]: uncertainty + confidence != 1000"
                );
            }
        }
    }

    /// br-asupersync-dezwpc: pin the contract-evaluation-error fallback path
    /// constants. The early-return GovernanceTelemetry on `evaluate()` Err
    /// must use action::FALLBACK (the conservative action) and a reason
    /// registered in G7_RUNTIME_FALLBACK_REASONS. Previously emitted
    /// action::CONTINUE (most-aggressive) and "contract_action_out_of_range"
    /// (unregistered) — fail-open on contract error, broke reason invariant.
    #[test]
    fn dezwpc_contract_error_fallback_uses_canonical_action_and_reason() {
        // The action emitted on the contract-evaluation-error path must
        // resolve to the conservative "fallback" label, not "continue".
        assert_eq!(
            action_label(action::FALLBACK),
            "fallback",
            "action::FALLBACK must label as 'fallback' for safety-gate matching"
        );
        assert_ne!(
            action_label(action::FALLBACK),
            action_label(action::CONTINUE),
            "FALLBACK and CONTINUE labels must be distinct"
        );

        // The deterministic_fallback_reason emitted on the error path must
        // pass the canonical-reason filter, otherwise replay/golden-snapshot
        // validators silently drop these telemetry rows.
        assert!(
            is_runtime_fallback_reason(FALLBACK_REASON_UNCLASSIFIED),
            "FALLBACK_REASON_UNCLASSIFIED must be registered in G7_RUNTIME_FALLBACK_REASONS"
        );
        // The previous (buggy) reason string must NOT pass the filter — pin
        // the regression so a future revert is caught.
        assert!(
            !is_runtime_fallback_reason("contract_action_out_of_range"),
            "the previously-emitted unregistered reason string must remain rejected; \
             if you re-add it, also register it in G7_RUNTIME_FALLBACK_REASONS"
        );
    }
}