tacet-core 0.4.2

Core statistical analysis for timing side-channel detection (no_std)
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
//! Result types for adaptive Bayesian timing analysis.
//!
//! See spec Section 4.1 (Result Types) for the full specification.

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use serde::{Deserialize, Serialize};

// ============================================================================
// Outcome - The top-level result type
// ============================================================================

/// Top-level outcome of a timing test.
///
/// The adaptive Bayesian oracle returns one of four outcomes:
/// - `Pass`: No timing leak detected (leak_probability < pass_threshold)
/// - `Fail`: Timing leak confirmed (leak_probability > fail_threshold)
/// - `Inconclusive`: Cannot reach a definitive conclusion
/// - `Unmeasurable`: Operation too fast to measure on this platform
///
/// See spec Section 4.1 (Result Types).
#[derive(Clone, Serialize, Deserialize)]
#[allow(clippy::large_enum_variant)]
pub enum Outcome {
    /// No timing leak detected.
    ///
    /// The posterior probability of a timing leak is below the pass threshold
    /// (default 0.05), meaning we're confident there is no exploitable leak.
    Pass {
        /// Posterior probability of timing leak: P(effect > theta | data).
        /// Will be < pass_threshold (default 0.05).
        leak_probability: f64,

        /// Effect size estimate (shift and tail components).
        effect: EffectEstimate,

        /// Number of samples used in the analysis.
        samples_used: usize,

        /// Measurement quality assessment.
        quality: MeasurementQuality,

        /// Diagnostic information for debugging.
        diagnostics: Diagnostics,

        /// User's requested threshold in nanoseconds.
        theta_user: f64,

        /// Effective threshold used for inference (may be elevated due to measurement floor).
        theta_eff: f64,

        /// Measurement floor at final sample count.
        theta_floor: f64,
    },

    /// Timing leak confirmed.
    ///
    /// The posterior probability of a timing leak exceeds the fail threshold
    /// (default 0.95), meaning we're confident there is an exploitable leak.
    Fail {
        /// Posterior probability of timing leak: P(effect > theta | data).
        /// Will be > fail_threshold (default 0.95).
        leak_probability: f64,

        /// Effect size estimate (shift and tail components).
        effect: EffectEstimate,

        /// Exploitability assessment based on effect magnitude.
        exploitability: Exploitability,

        /// Number of samples used in the analysis.
        samples_used: usize,

        /// Measurement quality assessment.
        quality: MeasurementQuality,

        /// Diagnostic information for debugging.
        diagnostics: Diagnostics,

        /// User's requested threshold in nanoseconds.
        theta_user: f64,

        /// Effective threshold used for inference (may be elevated due to measurement floor).
        theta_eff: f64,

        /// Measurement floor at final sample count.
        theta_floor: f64,
    },

    /// Cannot reach a definitive conclusion.
    ///
    /// The posterior probability is between pass_threshold and fail_threshold,
    /// or the analysis hit a limit (timeout, sample budget, noise).
    Inconclusive {
        /// Reason why the result is inconclusive.
        reason: InconclusiveReason,

        /// Current posterior probability of timing leak.
        leak_probability: f64,

        /// Effect size estimate (may have wide credible intervals).
        effect: EffectEstimate,

        /// Number of samples used in the analysis.
        samples_used: usize,

        /// Measurement quality assessment.
        quality: MeasurementQuality,

        /// Diagnostic information for debugging.
        diagnostics: Diagnostics,

        /// User's requested threshold in nanoseconds.
        theta_user: f64,

        /// Effective threshold used for inference (may be elevated due to measurement floor).
        theta_eff: f64,

        /// Measurement floor at final sample count.
        theta_floor: f64,
    },

    /// Operation too fast to measure reliably on this platform.
    ///
    /// The operation completes faster than the timer's resolution allows
    /// for meaningful measurement, even with adaptive batching.
    Unmeasurable {
        /// Estimated operation duration in nanoseconds.
        operation_ns: f64,

        /// Minimum measurable duration on this platform.
        threshold_ns: f64,

        /// Platform description (e.g., "Apple Silicon (cntvct)").
        platform: String,

        /// Suggested actions to make the operation measurable.
        recommendation: String,
    },

    /// Research mode result.
    ///
    /// Returned when using `AttackerModel::Research`. Unlike Pass/Fail/Inconclusive
    /// which make threshold-based decisions, research mode characterizes the
    /// timing behavior relative to the measurement floor using CI-based semantics.
    ///
    /// See `ResearchOutcome` for details on the stopping conditions.
    Research(ResearchOutcome),
}

// ============================================================================
// InconclusiveReason - Why we couldn't reach a conclusion
// ============================================================================

/// Reason why a timing test result is inconclusive.
///
/// See spec Section 4.1 (Result Types).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum InconclusiveReason {
    /// Data is too noisy to reach a conclusion.
    ///
    /// The measurement noise is high enough that we cannot distinguish
    /// between "no leak" and "small leak" with the available samples.
    DataTooNoisy {
        /// Human-readable explanation.
        message: String,
        /// Suggested actions to improve measurement quality.
        guidance: String,
    },

    /// Posterior is not converging toward either threshold.
    ///
    /// After collecting samples, the leak probability remains in the
    /// inconclusive range and isn't trending toward pass or fail.
    NotLearning {
        /// Human-readable explanation.
        message: String,
        /// Suggested actions.
        guidance: String,
    },

    /// Reaching a conclusion would take too long.
    ///
    /// Based on current convergence rate, reaching the pass or fail
    /// threshold would exceed the configured time budget.
    WouldTakeTooLong {
        /// Estimated time in seconds to reach a conclusion.
        estimated_time_secs: f64,
        /// Estimated samples needed to reach a conclusion.
        samples_needed: usize,
        /// Suggested actions.
        guidance: String,
    },

    /// Time budget exhausted.
    ///
    /// The configured time limit was reached before the posterior
    /// converged to a conclusive result.
    TimeBudgetExceeded {
        /// Posterior probability when budget was exhausted.
        current_probability: f64,
        /// Number of samples collected.
        samples_collected: usize,
    },

    /// Sample budget exhausted.
    ///
    /// The maximum number of samples was collected without reaching
    /// a conclusive result.
    SampleBudgetExceeded {
        /// Posterior probability when budget was exhausted.
        current_probability: f64,
        /// Number of samples collected.
        samples_collected: usize,
    },

    /// Measurement conditions changed during the test.
    ///
    /// Detected by comparing calibration statistics with post-test statistics.
    /// This can indicate environmental interference (CPU frequency scaling,
    /// concurrent processes, etc.) that invalidates the covariance estimate.
    /// See spec §3.5.4, Gate 4 (Condition Drift).
    ConditionsChanged {
        /// Human-readable explanation.
        message: String,
        /// Suggested actions.
        guidance: String,
    },

    /// Threshold was elevated and pass criterion was met at effective threshold.
    ///
    /// The measurement floor exceeded the user's requested threshold, so inference
    /// was performed at an elevated effective threshold. The posterior probability
    /// dropped below pass_threshold at θ_eff, but since θ_eff > θ_user + ε, we
    /// cannot guarantee the user's original requirement is met.
    ///
    /// This is NOT a quality gate failure - it's a semantic constraint: Pass requires
    /// both P < pass_threshold AND θ_eff ≤ θ_user + ε.
    ///
    /// See spec Section 3.5.3 (v5.5 Threshold Elevation Decision Rule).
    ThresholdElevated {
        /// User's requested threshold in nanoseconds (θ_user).
        theta_user: f64,
        /// Effective threshold used for inference (θ_eff = max(θ_user, θ_floor)).
        theta_eff: f64,
        /// Posterior probability at θ_eff (was < pass_threshold).
        leak_probability_at_eff: f64,
        /// True: P(leak > θ_eff) < pass_threshold (pass criterion met at elevated threshold).
        meets_pass_criterion_at_eff: bool,
        /// True: θ_floor at max_samples would be ≤ θ_user + ε (more samples could achieve user threshold).
        achievable_at_max: bool,
        /// Human-readable explanation.
        message: String,
        /// Suggested actions.
        guidance: String,
    },
}

// ============================================================================
// EffectEstimate - Timing effect summary (spec §5.2)
// ============================================================================

/// Estimated timing effect with credible interval and top quantiles.
///
/// This struct summarizes the timing difference between baseline and sample classes.
/// The effect is characterized by the maximum absolute quantile difference across
/// all 9 deciles, with a 95% credible interval and details about which quantiles
/// contribute most to any detected leak.
///
/// See spec Section 5.2 (Effect Reporting).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EffectEstimate {
    /// Posterior mean of max_k |δ_k| in nanoseconds.
    ///
    /// This is the maximum absolute timing difference across all 9 deciles,
    /// averaged over posterior samples. Positive values indicate detectable
    /// timing differences between the two input classes.
    pub max_effect_ns: f64,

    /// 95% credible interval for max|δ| in nanoseconds.
    ///
    /// This is a Bayesian credible interval: there is a 95% posterior probability
    /// that the true maximum effect lies within this range.
    pub credible_interval_ns: (f64, f64),

    /// Top 2-3 quantiles by exceedance probability.
    ///
    /// When a timing leak is detected, these are the specific quantiles that
    /// contribute most to the leak detection. Each entry includes the quantile
    /// probability (e.g., 0.9 for 90th percentile), the posterior mean effect,
    /// the 95% marginal credible interval, and the exceedance probability.
    ///
    /// Empty when no leak is detected or effect is negligible.
    pub top_quantiles: Vec<TopQuantile>,
}

impl EffectEstimate {
    /// Create a new EffectEstimate with the given values.
    pub fn new(
        max_effect_ns: f64,
        credible_interval_ns: (f64, f64),
        top_quantiles: Vec<TopQuantile>,
    ) -> Self {
        Self {
            max_effect_ns,
            credible_interval_ns,
            top_quantiles,
        }
    }

    /// Check if the effect is negligible (max effect below threshold).
    pub fn is_negligible(&self, threshold_ns: f64) -> bool {
        self.max_effect_ns.abs() < threshold_ns
    }

    /// Get the total effect magnitude (same as max_effect_ns for API compatibility).
    pub fn total_effect_ns(&self) -> f64 {
        self.max_effect_ns
    }
}

impl Default for EffectEstimate {
    fn default() -> Self {
        Self {
            max_effect_ns: 0.0,
            credible_interval_ns: (0.0, 0.0),
            top_quantiles: Vec::new(),
        }
    }
}

// ============================================================================
// Exploitability - Risk assessment
// ============================================================================

/// Exploitability assessment based on effect magnitude.
///
/// Based on Crosby et al. (2009) thresholds for timing attack feasibility.
/// These thresholds are heuristics based on academic research for risk
/// prioritization, not guarantees. The thresholds reflect modern attack
/// techniques including HTTP/2 multiplexing (Timeless Timing Attacks) and
/// shared-hardware attacks (KyberSlash, Flush+Reload).
///
/// See spec Section 5.4 (Exploitability).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum Exploitability {
    /// Effect < 10 ns: Requires shared hardware to exploit.
    ///
    /// Only exploitable by attackers with physical co-location: SGX enclaves,
    /// hyperthreading on same core, containers on same host, or cross-VM on
    /// shared cache. Remote exploitation is impractical.
    ///
    /// References: KyberSlash (2024), Flush+Reload, Prime+Probe literature
    SharedHardwareOnly,

    /// 10-100 ns: Exploitable via HTTP/2 request multiplexing.
    ///
    /// Requires ~100k concurrent HTTP/2 requests to exploit. The "Timeless
    /// Timing Attacks" technique eliminates network jitter by sending requests
    /// that arrive simultaneously, making response order reveal timing differences.
    ///
    /// Reference: Van Goethem et al., "Timeless Timing Attacks" (USENIX Security 2020)
    Http2Multiplexing,

    /// 100 ns - 10 μs: Exploitable with standard remote timing.
    ///
    /// Requires ~1k-10k requests using traditional timing techniques.
    /// Exploitable on LAN with any protocol, or over internet with HTTP/2.
    ///
    /// References: Crosby et al. (2009), Brumley & Boneh (2005)
    StandardRemote,

    /// > 10 μs: Obvious timing leak, trivially exploitable.
    ///
    /// Detectable with < 100 requests. Exploitable over the internet even
    /// with high-jitter connections using traditional timing techniques.
    ObviousLeak,
}

impl Exploitability {
    /// Determine exploitability from effect size in nanoseconds.
    ///
    /// Thresholds are based on:
    /// - < 10 ns: Below HTTP/2 timing precision, requires shared hardware
    /// - 10-100 ns: Within HTTP/2 "Timeless Timing Attacks" range
    /// - 100 ns - 10 μs: Standard remote timing attack range
    /// - > 10 μs: Trivially observable
    pub fn from_effect_ns(effect_ns: f64) -> Self {
        let effect_ns = effect_ns.abs();
        if effect_ns < 10.0 {
            Exploitability::SharedHardwareOnly
        } else if effect_ns < 100.0 {
            Exploitability::Http2Multiplexing
        } else if effect_ns < 10_000.0 {
            Exploitability::StandardRemote
        } else {
            Exploitability::ObviousLeak
        }
    }
}

// ============================================================================
// MeasurementQuality - Assessment of measurement reliability
// ============================================================================

/// Measurement quality assessment based on noise level.
///
/// Quality is determined primarily by the minimum detectable effect (MDE)
/// relative to the configured threshold.
///
/// See spec Section 5.5 (Quality Assessment).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum MeasurementQuality {
    /// Low noise, high confidence (MDE < 5 ns).
    Excellent,

    /// Normal noise levels (MDE 5-20 ns).
    Good,

    /// High noise, results less reliable (MDE 20-100 ns).
    Poor,

    /// Cannot produce meaningful results (MDE > 100 ns).
    TooNoisy,
}

impl MeasurementQuality {
    /// Determine quality from minimum detectable effect.
    ///
    /// Invalid MDE values (less than or equal to 0 or non-finite) indicate a measurement problem
    /// and are classified as `TooNoisy`.
    ///
    /// Very small MDE (< 0.01 ns) also indicates timer resolution issues
    /// where most samples have identical values.
    pub fn from_mde_ns(mde_ns: f64) -> Self {
        // Invalid MDE indicates measurement failure
        if mde_ns <= 0.01 || !mde_ns.is_finite() {
            return MeasurementQuality::TooNoisy;
        }

        if mde_ns < 5.0 {
            MeasurementQuality::Excellent
        } else if mde_ns < 20.0 {
            MeasurementQuality::Good
        } else if mde_ns < 100.0 {
            MeasurementQuality::Poor
        } else {
            MeasurementQuality::TooNoisy
        }
    }
}

// ============================================================================
// ResearchOutcome - Result type for research mode
// ============================================================================

/// Status of a research mode run.
///
/// Research mode (AttackerModel::Research) doesn't make Pass/Fail decisions.
/// Instead, it characterizes the timing behavior with respect to the measurement floor.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ResearchStatus {
    /// CI clearly above θ_floor — timing difference detected.
    ///
    /// The 95% credible interval lower bound is clearly above the measurement
    /// floor (> 1.1 × θ_floor), indicating a confidently detectable effect.
    EffectDetected,

    /// CI clearly below θ_floor — no timing difference above noise.
    ///
    /// The 95% credible interval upper bound is clearly below the measurement
    /// floor (< 0.9 × θ_floor), indicating no detectable effect.
    NoEffectDetected,

    /// Hit timer resolution limit; θ_floor is as good as it gets.
    ///
    /// Further sampling won't improve the measurement floor because we've
    /// hit the fundamental timer tick resolution.
    ResolutionLimitReached,

    /// Data quality issue detected.
    ///
    /// A quality gate triggered during research mode. Unlike standard mode,
    /// this doesn't block the result but is reported for transparency.
    QualityIssue(InconclusiveReason),

    /// Ran out of time/samples before reaching conclusion.
    ///
    /// The budget was exhausted before the CI could confidently settle
    /// above or below the measurement floor.
    BudgetExhausted,
}

/// Research mode outcome (spec v4.1 research mode).
///
/// This struct is returned when using `AttackerModel::Research`. Unlike the
/// standard `Outcome` which makes Pass/Fail decisions, research mode characterizes
/// the timing behavior relative to the measurement floor.
///
/// Key differences from standard mode:
/// - No Pass/Fail verdict (no threshold comparison)
/// - Reports measurement floor (`theta_floor`) at final sample size
/// - `detectable` field indicates if CI lower bound > floor
/// - `model_mismatch` is non-blocking (tracked but doesn't stop analysis)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResearchOutcome {
    /// Research outcome status.
    pub status: ResearchStatus,

    /// Maximum effect across quantiles: max_k |(Xβ)_k| in nanoseconds.
    /// This is the posterior mean of the maximum absolute predicted effect.
    pub max_effect_ns: f64,

    /// 95% credible interval for maximum effect: (2.5th, 97.5th percentile).
    pub max_effect_ci: (f64, f64),

    /// Measurement floor at final sample size.
    /// This is the minimum detectable effect given measurement noise.
    pub theta_floor: f64,

    /// True if the effect is detectable: CI lower bound > theta_floor.
    pub detectable: bool,

    /// True if model mismatch was detected (Q > q_thresh).
    /// In research mode, this is non-blocking but adds a caveat to interpretation.
    pub model_mismatch: bool,

    /// Effect size estimate with decomposition.
    /// If `model_mismatch` is true, `interpretation_caveat` will be set.
    pub effect: EffectEstimate,

    /// Number of samples used.
    pub samples_used: usize,

    /// Measurement quality assessment.
    pub quality: MeasurementQuality,

    /// Diagnostic information.
    pub diagnostics: Diagnostics,
}

impl ResearchOutcome {
    /// Check if a timing effect was confidently detected.
    pub fn is_effect_detected(&self) -> bool {
        matches!(self.status, ResearchStatus::EffectDetected)
    }

    /// Check if no effect was confidently detected.
    pub fn is_no_effect_detected(&self) -> bool {
        matches!(self.status, ResearchStatus::NoEffectDetected)
    }

    /// Check if the resolution limit was reached.
    pub fn is_resolution_limit_reached(&self) -> bool {
        matches!(self.status, ResearchStatus::ResolutionLimitReached)
    }

    /// Check if there was a quality issue.
    pub fn has_quality_issue(&self) -> bool {
        matches!(self.status, ResearchStatus::QualityIssue(_))
    }

    /// Get the effect estimate.
    pub fn effect(&self) -> &EffectEstimate {
        &self.effect
    }

    /// Get the measurement quality.
    pub fn quality(&self) -> MeasurementQuality {
        self.quality
    }

    /// Get the diagnostics.
    pub fn diagnostics(&self) -> &Diagnostics {
        &self.diagnostics
    }
}

impl fmt::Display for ResearchStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ResearchStatus::EffectDetected => write!(f, "effect detected"),
            ResearchStatus::NoEffectDetected => write!(f, "no effect detected"),
            ResearchStatus::ResolutionLimitReached => write!(f, "resolution limit reached"),
            ResearchStatus::QualityIssue(reason) => write!(f, "quality issue: {}", reason),
            ResearchStatus::BudgetExhausted => write!(f, "budget exhausted"),
        }
    }
}

impl fmt::Display for ResearchOutcome {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Research Mode: {}", self.status)?;
        writeln!(
            f,
            "  Max effect: {:.2}ns (CI: {:.2}-{:.2}ns)",
            self.max_effect_ns, self.max_effect_ci.0, self.max_effect_ci.1
        )?;
        writeln!(f, "  Measurement floor: {:.2}ns", self.theta_floor)?;
        writeln!(
            f,
            "  Detectable: {}",
            if self.detectable { "yes" } else { "no" }
        )?;
        if self.model_mismatch {
            writeln!(f, "  Warning: model mismatch detected")?;
        }
        writeln!(f, "  Samples: {}", self.samples_used)?;
        writeln!(f, "  Quality: {}", self.quality)?;
        Ok(())
    }
}

// ============================================================================
// TopQuantile - Information about significant quantiles (spec §5.2)
// ============================================================================

/// Information about a quantile with high exceedance probability.
///
/// When a timing leak is detected, this struct provides information about
/// which specific quantiles (deciles) contribute most to the leak detection.
/// The top 2-3 quantiles by exceedance probability are included in
/// `EffectEstimate.top_quantiles` to help users understand where timing
/// differences are concentrated.
///
/// See spec Section 5.2 (Effect Reporting).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TopQuantile {
    /// Quantile probability (e.g., 0.9 for 90th percentile).
    pub quantile_p: f64,

    /// Posterior mean δ_k in nanoseconds.
    pub mean_ns: f64,

    /// 95% marginal credible interval (lower, upper) in nanoseconds.
    pub ci95_ns: (f64, f64),

    /// P(|δ_k| > θ_eff | Δ) - per-quantile exceedance probability.
    ///
    /// This is the probability that this individual quantile's effect
    /// exceeds the threshold, computed from the marginal posterior.
    pub exceed_prob: f64,
}

impl TopQuantile {
    /// Create a new TopQuantile entry.
    pub fn new(quantile_p: f64, mean_ns: f64, ci95_ns: (f64, f64), exceed_prob: f64) -> Self {
        Self {
            quantile_p,
            mean_ns,
            ci95_ns,
            exceed_prob,
        }
    }
}

// ============================================================================
// Diagnostics - Detailed diagnostic information (spec §6)
// ============================================================================

/// Diagnostic information for debugging and analysis.
///
/// See spec Section 6 (Quality Metrics).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Diagnostics {
    /// Block size used for bootstrap (Politis-White automatic selection).
    pub dependence_length: usize,

    /// Effective sample size accounting for autocorrelation (ESS approx n / dependence_length).
    pub effective_sample_size: usize,

    /// Non-stationarity: ratio of inference to calibration variance.
    /// Values 0.5-2.0 are normal; >5.0 indicates non-stationarity.
    pub stationarity_ratio: f64,

    /// True if stationarity ratio is within acceptable bounds (0.5-2.0).
    pub stationarity_ok: bool,

    /// Outlier rate for baseline class (fraction trimmed).
    pub outlier_rate_baseline: f64,

    /// Outlier rate for sample class (fraction trimmed).
    pub outlier_rate_sample: f64,

    /// True if outlier rates are symmetric (both <1%, ratio <3x, diff <2%).
    pub outlier_asymmetry_ok: bool,

    /// Whether discrete timer mode was used (low timer resolution).
    pub discrete_mode: bool,

    /// Timer resolution in nanoseconds.
    pub timer_resolution_ns: f64,

    /// Fraction of samples with duplicate timing values (0.0-1.0).
    pub duplicate_fraction: f64,

    /// True if preflight checks passed (sanity, generator, system).
    pub preflight_ok: bool,

    /// Number of samples used for calibration (covariance estimation).
    pub calibration_samples: usize,

    /// Total time spent on the analysis in seconds.
    pub total_time_secs: f64,

    /// Human-readable warnings (empty if all checks pass).
    pub warnings: Vec<String>,

    /// Quality issues detected during measurement.
    pub quality_issues: Vec<QualityIssue>,

    /// Preflight warnings from calibration phase.
    ///
    /// These warnings are categorized by severity:
    /// - `Informational`: Sampling efficiency issues (results still valid)
    /// - `ResultUndermining`: Statistical assumption violations (results may be unreliable)
    pub preflight_warnings: Vec<PreflightWarningInfo>,

    // =========================================================================
    // Reproduction info (for verbose/debug output)
    // =========================================================================
    /// Measurement seed used for reproducibility.
    pub seed: Option<u64>,

    /// Attacker model name (e.g., "AdjacentNetwork", "SharedHardware").
    pub attacker_model: Option<String>,

    /// Effect threshold (theta) in nanoseconds.
    pub threshold_ns: f64,

    /// Timer implementation name (e.g., "rdtsc", "cntvct_el0", "kperf").
    pub timer_name: String,

    /// Platform description (e.g., "macos-aarch64").
    pub platform: String,

    /// Reason the timer fell back from high-precision PMU (if applicable).
    ///
    /// Used to generate context-aware recommendations in output.
    /// - "concurrent access": kperf locked by another process
    /// - "no sudo": not running with elevated privileges
    /// - "unavailable": PMU init failed despite privileges
    /// - None: using high-precision timer or x86_64 (rdtsc is already ~0.3ns)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timer_fallback_reason: Option<String>,

    // =========================================================================
    // v5.4 Gibbs sampler diagnostics
    // =========================================================================
    /// v5.4: Total number of Gibbs iterations.
    pub gibbs_iters_total: usize,

    /// v5.4: Number of burn-in iterations.
    pub gibbs_burnin: usize,

    /// v5.4: Number of retained samples.
    pub gibbs_retained: usize,

    /// v5.4: Posterior mean of latent scale λ.
    pub lambda_mean: f64,

    /// v5.4: Posterior standard deviation of λ.
    pub lambda_sd: f64,

    /// v5.4: Coefficient of variation of λ (λ_sd / λ_mean).
    pub lambda_cv: f64,

    /// v5.4: Effective sample size of λ chain.
    pub lambda_ess: f64,

    /// v5.4: Whether λ chain mixed well (CV ≥ 0.1 AND ESS ≥ 20).
    pub lambda_mixing_ok: bool,

    // =========================================================================
    // v5.6 Gibbs sampler κ (kappa) diagnostics - robust t-likelihood
    // =========================================================================
    /// v5.6: Posterior mean of likelihood precision κ.
    pub kappa_mean: f64,

    /// v5.6: Posterior standard deviation of κ.
    pub kappa_sd: f64,

    /// v5.6: Coefficient of variation of κ (kappa_sd / kappa_mean).
    pub kappa_cv: f64,

    /// v5.6: Effective sample size of κ chain.
    pub kappa_ess: f64,

    /// v5.6: Whether κ chain mixed well (CV ≥ 0.1 AND ESS ≥ 20).
    pub kappa_mixing_ok: bool,
}

impl Diagnostics {
    /// Create diagnostics indicating all checks passed.
    ///
    /// Uses placeholder values for numeric fields; prefer constructing
    /// explicitly with actual measured values.
    pub fn all_ok() -> Self {
        Self {
            dependence_length: 1,
            effective_sample_size: 0,
            stationarity_ratio: 1.0,
            stationarity_ok: true,
            outlier_rate_baseline: 0.0,
            outlier_rate_sample: 0.0,
            outlier_asymmetry_ok: true,
            discrete_mode: false,
            timer_resolution_ns: 1.0,
            duplicate_fraction: 0.0,
            preflight_ok: true,
            calibration_samples: 0,
            total_time_secs: 0.0,
            warnings: Vec::new(),
            quality_issues: Vec::new(),
            preflight_warnings: Vec::new(),
            seed: None,
            attacker_model: None,
            threshold_ns: 0.0,
            timer_name: String::new(),
            platform: String::new(),
            timer_fallback_reason: None,
            // v5.4 Gibbs sampler diagnostics
            gibbs_iters_total: 256,
            gibbs_burnin: 64,
            gibbs_retained: 192,
            lambda_mean: 1.0,
            lambda_sd: 0.0,
            lambda_cv: 0.0,
            lambda_ess: 0.0,
            lambda_mixing_ok: true,
            // v5.6 kappa diagnostics
            kappa_mean: 1.0,
            kappa_sd: 0.0,
            kappa_cv: 0.0,
            kappa_ess: 0.0,
            kappa_mixing_ok: true,
        }
    }

    /// Check if all diagnostics are OK.
    pub fn all_checks_passed(&self) -> bool {
        self.stationarity_ok && self.outlier_asymmetry_ok && self.preflight_ok
    }
}

impl Default for Diagnostics {
    fn default() -> Self {
        Self::all_ok()
    }
}

// ============================================================================
// QualityIssue - Specific quality problems
// ============================================================================

/// A specific quality issue detected during measurement.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct QualityIssue {
    /// Issue code for programmatic handling.
    pub code: IssueCode,

    /// Human-readable description of the issue.
    pub message: String,

    /// Suggested actions to address the issue.
    pub guidance: String,
}

/// Issue codes for programmatic handling of quality problems.
///
/// Consolidated to 8 categories per spec §6.1 (v6.0).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum IssueCode {
    /// High temporal dependence reduces effective sample size.
    ///
    /// Covers: high autocorrelation, low effective sample size.
    /// The block bootstrap accounts for this, but it means more samples
    /// were needed to reach the same confidence level.
    DependenceHigh,

    /// Low measurement precision due to setup issues.
    ///
    /// Covers: small sample count for discrete mode, generator cost asymmetry,
    /// low entropy in random inputs. These affect measurement quality but
    /// results are still valid.
    PrecisionLow,

    /// Timer has low resolution, using discrete mode.
    ///
    /// The timer resolution is coarse enough that many samples have identical
    /// values. The bootstrap handles this, but sensitivity is reduced.
    DiscreteMode,

    /// Threshold was adjusted due to measurement limitations.
    ///
    /// Covers: threshold elevated due to measurement floor, threshold clamped
    /// to timer resolution. The effective threshold may differ from the
    /// user-requested threshold.
    ThresholdIssue,

    /// Outlier filtering was applied to the data.
    ///
    /// Covers: high winsorization rate, quantiles filtered from analysis.
    /// Some data points were trimmed as outliers. This is normal but
    /// excessive filtering may indicate environmental issues.
    FilteringApplied,

    /// Stationarity of timing distribution is suspect.
    ///
    /// The timing distribution may have changed during measurement,
    /// violating the i.i.d. assumption. This can occur due to CPU
    /// frequency scaling, thermal throttling, or concurrent processes.
    StationarityIssue,

    /// Numerical issues in Gibbs sampler.
    ///
    /// Covers: lambda chain poor mixing, kappa chain poor mixing.
    /// The MCMC chains showed poor convergence (CV < 0.1 or ESS < 20).
    /// Results may be less reliable.
    NumericalIssue,

    /// Likelihood covariance was inflated for robustness.
    ///
    /// The robust t-likelihood inflated covariance by ~1/κ_mean to accommodate
    /// data that doesn't match the estimated Σₙ. Effect estimates remain valid
    /// but uncertainty was increased for robustness (kappa_mean < 0.3).
    LikelihoodInflated,
}

// ============================================================================
// PreflightWarning - Preflight check results
// ============================================================================

/// Severity of a preflight warning.
///
/// This distinction is critical for interpreting results:
///
/// - **Informational**: Affects sampling efficiency but not result validity.
///   The Bayesian posterior is still trustworthy; you just needed more samples
///   to reach the same confidence level. Examples: high autocorrelation,
///   coarse timer resolution, suboptimal CPU governor.
///
/// - **ResultUndermining**: Violates statistical assumptions the Bayesian model
///   relies on. The posterior confidence may be misplaced because the model's
///   assumptions don't hold. Examples: non-monotonic timer (measurements are
///   garbage), severe non-stationarity (distribution changed during measurement),
///   broken harness with mutable state (Fixed-vs-Fixed inconsistency).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum PreflightSeverity {
    /// Sampling efficiency issue - doesn't invalidate results.
    ///
    /// These warnings indicate that the measurement setup is suboptimal and
    /// required more samples to reach a conclusion, but the Bayesian posterior
    /// is still valid. The result can be trusted.
    ///
    /// Examples:
    /// - High autocorrelation (reduces effective sample size)
    /// - Coarse timer resolution (requires more samples)
    /// - Suboptimal CPU governor (adds variance)
    /// - Generator cost asymmetry (may inflate differences but doesn't invalidate)
    Informational,

    /// Statistical assumption violation - undermines result confidence.
    ///
    /// These warnings indicate that fundamental assumptions of the Bayesian
    /// model may be violated. Even if the posterior appears confident, that
    /// confidence may be misplaced.
    ///
    /// Examples:
    /// - Non-monotonic timer (measurements are meaningless)
    /// - Severe non-stationarity (distribution changed during measurement)
    /// - Fixed-vs-Fixed inconsistency with randomization (likely mutable state bug)
    ResultUndermining,
}

/// Category of preflight check.
///
/// Used for organizing warnings in output and for programmatic filtering.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum PreflightCategory {
    /// Timer sanity checks (monotonicity, basic functionality).
    ///
    /// **Severity**: ResultUndermining if failed - measurements are unreliable.
    TimerSanity,

    /// Fixed-vs-Fixed internal consistency check.
    ///
    /// **Severity**: ResultUndermining if triggered - may indicate mutable state
    /// captured in test closure, or severe environmental interference.
    /// Note: May be intentional for FPR validation testing.
    Sanity,

    /// Autocorrelation in timing samples.
    ///
    /// **Severity**: Informational - reduces effective sample size but the
    /// block bootstrap accounts for this.
    Autocorrelation,

    /// System configuration (CPU governor, turbo boost, etc.).
    ///
    /// **Severity**: Informational - suboptimal config adds variance but
    /// doesn't invalidate results.
    System,

    /// Timer resolution and precision.
    ///
    /// **Severity**: Informational - coarse timers require more samples but
    /// adaptive batching compensates for this.
    Resolution,

    /// Stationarity of timing distribution.
    ///
    /// **Severity**: ResultUndermining if severely violated - indicates the
    /// timing distribution changed during measurement.
    Stationarity,
}

/// Information about a preflight warning.
///
/// Preflight warnings are collected during the calibration phase and reported
/// to help users understand measurement quality and potential issues.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreflightWarningInfo {
    /// Category of the check that generated this warning.
    pub category: PreflightCategory,

    /// Severity of this warning.
    ///
    /// - `Informational`: Sampling efficiency issue, results still valid.
    /// - `ResultUndermining`: Statistical assumption violation, results may be unreliable.
    pub severity: PreflightSeverity,

    /// Human-readable description of the warning.
    pub message: String,

    /// Optional guidance for addressing the issue.
    pub guidance: Option<String>,
}

impl PreflightWarningInfo {
    /// Create a new preflight warning.
    pub fn new(
        category: PreflightCategory,
        severity: PreflightSeverity,
        message: impl Into<String>,
    ) -> Self {
        Self {
            category,
            severity,
            message: message.into(),
            guidance: None,
        }
    }

    /// Create a new preflight warning with guidance.
    pub fn with_guidance(
        category: PreflightCategory,
        severity: PreflightSeverity,
        message: impl Into<String>,
        guidance: impl Into<String>,
    ) -> Self {
        Self {
            category,
            severity,
            message: message.into(),
            guidance: Some(guidance.into()),
        }
    }

    /// Check if this warning undermines result confidence.
    pub fn is_result_undermining(&self) -> bool {
        self.severity == PreflightSeverity::ResultUndermining
    }
}

// ============================================================================
// MinDetectableEffect - Sensitivity information (spec §3.3)
// ============================================================================

/// Minimum detectable effect at current noise level.
///
/// The MDE tells you the smallest effect that could be reliably detected
/// given the measurement noise. If MDE > threshold, a "pass" result means
/// insufficient sensitivity, not necessarily safety.
///
/// See spec Section 3.3 (Minimum Detectable Effect).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MinDetectableEffect {
    /// Minimum detectable effect in nanoseconds.
    ///
    /// This is the smallest timing difference that could be reliably detected
    /// at 50% power given the measurement noise. Computed from the covariance
    /// of the quantile differences.
    pub mde_ns: f64,
}

impl MinDetectableEffect {
    /// Create a new MinDetectableEffect with the given value.
    pub fn new(mde_ns: f64) -> Self {
        Self { mde_ns }
    }
}

impl Default for MinDetectableEffect {
    fn default() -> Self {
        Self {
            mde_ns: f64::INFINITY,
        }
    }
}

// ============================================================================
// BatchingInfo - Metadata about batching
// ============================================================================

/// Information about batching configuration used during collection.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchingInfo {
    /// Whether batching was enabled.
    pub enabled: bool,

    /// Iterations per batch (1 if batching disabled).
    pub k: u32,

    /// Effective ticks per batch measurement.
    pub ticks_per_batch: f64,

    /// Explanation of why batching was enabled/disabled.
    pub rationale: String,

    /// Whether the operation was too fast to measure reliably.
    pub unmeasurable: Option<UnmeasurableInfo>,
}

/// Information about why an operation is unmeasurable.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnmeasurableInfo {
    /// Estimated operation duration in nanoseconds.
    pub operation_ns: f64,

    /// Minimum measurable threshold in nanoseconds.
    pub threshold_ns: f64,

    /// Ticks per call (below MIN_TICKS_SINGLE_CALL).
    pub ticks_per_call: f64,
}

// ============================================================================
// Metadata - Runtime information
// ============================================================================

/// Metadata for debugging and analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Metadata {
    /// Samples per class after outlier filtering.
    pub samples_per_class: usize,

    /// Cycles per nanosecond (for conversion).
    pub cycles_per_ns: f64,

    /// Timer type used.
    pub timer: String,

    /// Timer resolution in nanoseconds.
    pub timer_resolution_ns: f64,

    /// Batching configuration and rationale.
    pub batching: BatchingInfo,

    /// Total runtime in seconds.
    pub runtime_secs: f64,
}

// ============================================================================
// UnreliablePolicy - How to handle unreliable results
// ============================================================================

/// Policy for handling unreliable measurements in test assertions.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum UnreliablePolicy {
    /// Log warning and skip assertions. Test passes.
    /// Use when: noisy CI, parallel tests, "some coverage is better than none".
    #[default]
    FailOpen,

    /// Panic. Test fails.
    /// Use when: security-critical code, dedicated quiet CI runners.
    FailClosed,
}

impl UnreliablePolicy {
    /// Get policy from environment variable, or use default.
    ///
    /// Checks `TIMING_ORACLE_UNRELIABLE_POLICY`:
    /// - "fail_open" or "skip" → FailOpen
    /// - "fail_closed" or "panic" → FailClosed
    /// - unset or other → default
    #[cfg(feature = "std")]
    pub fn from_env_or(default: Self) -> Self {
        match std::env::var("TIMING_ORACLE_UNRELIABLE_POLICY")
            .ok()
            .as_deref()
        {
            Some("fail_open") | Some("skip") => Self::FailOpen,
            Some("fail_closed") | Some("panic") => Self::FailClosed,
            _ => default,
        }
    }

    /// Get policy from environment variable, or use default.
    ///
    /// In no_std mode, always returns the default.
    #[cfg(not(feature = "std"))]
    pub fn from_env_or(default: Self) -> Self {
        default
    }
}

// ============================================================================
// Outcome implementation
// ============================================================================

impl Outcome {
    /// Check if the test passed (no timing leak detected).
    pub fn passed(&self) -> bool {
        matches!(self, Outcome::Pass { .. })
    }

    /// Check if the test failed (timing leak detected).
    pub fn failed(&self) -> bool {
        matches!(self, Outcome::Fail { .. })
    }

    /// Check if the result is conclusive (either Pass or Fail).
    pub fn is_conclusive(&self) -> bool {
        matches!(self, Outcome::Pass { .. } | Outcome::Fail { .. })
    }

    /// Check if the operation was measurable.
    pub fn is_measurable(&self) -> bool {
        !matches!(self, Outcome::Unmeasurable { .. })
    }

    /// Get the leak probability if available.
    ///
    /// Returns `None` for `Unmeasurable` and `Research` (research mode uses CI, not probability).
    pub fn leak_probability(&self) -> Option<f64> {
        match self {
            Outcome::Pass {
                leak_probability, ..
            } => Some(*leak_probability),
            Outcome::Fail {
                leak_probability, ..
            } => Some(*leak_probability),
            Outcome::Inconclusive {
                leak_probability, ..
            } => Some(*leak_probability),
            Outcome::Unmeasurable { .. } => None,
            Outcome::Research(_) => None, // Research mode uses CI-based semantics
        }
    }

    /// Get the effect estimate if available.
    pub fn effect(&self) -> Option<&EffectEstimate> {
        match self {
            Outcome::Pass { effect, .. } => Some(effect),
            Outcome::Fail { effect, .. } => Some(effect),
            Outcome::Inconclusive { effect, .. } => Some(effect),
            Outcome::Unmeasurable { .. } => None,
            Outcome::Research(res) => Some(&res.effect),
        }
    }

    /// Get the measurement quality if available.
    pub fn quality(&self) -> Option<MeasurementQuality> {
        match self {
            Outcome::Pass { quality, .. } => Some(*quality),
            Outcome::Fail { quality, .. } => Some(*quality),
            Outcome::Inconclusive { quality, .. } => Some(*quality),
            Outcome::Unmeasurable { .. } => None,
            Outcome::Research(res) => Some(res.quality),
        }
    }

    /// Get the diagnostics if available.
    pub fn diagnostics(&self) -> Option<&Diagnostics> {
        match self {
            Outcome::Pass { diagnostics, .. } => Some(diagnostics),
            Outcome::Fail { diagnostics, .. } => Some(diagnostics),
            Outcome::Inconclusive { diagnostics, .. } => Some(diagnostics),
            Outcome::Unmeasurable { .. } => None,
            Outcome::Research(res) => Some(&res.diagnostics),
        }
    }

    /// Get the number of samples used if available.
    pub fn samples_used(&self) -> Option<usize> {
        match self {
            Outcome::Pass { samples_used, .. } => Some(*samples_used),
            Outcome::Fail { samples_used, .. } => Some(*samples_used),
            Outcome::Inconclusive { samples_used, .. } => Some(*samples_used),
            Outcome::Unmeasurable { .. } => None,
            Outcome::Research(res) => Some(res.samples_used),
        }
    }

    /// Check if the measurement is reliable enough for assertions.
    ///
    /// Returns `true` if:
    /// - Test is conclusive (Pass or Fail), AND
    /// - Quality is not TooNoisy, OR posterior is very conclusive (< 0.1 or > 0.9)
    ///
    /// The key insight: a very conclusive posterior is trustworthy even with noisy
    /// measurements - the signal overcame the noise.
    ///
    /// For Research mode, reliability is based on whether the CI is clearly above
    /// or below the measurement floor.
    pub fn is_reliable(&self) -> bool {
        match self {
            Outcome::Unmeasurable { .. } => false,
            Outcome::Inconclusive { .. } => false,
            Outcome::Pass {
                quality,
                leak_probability,
                ..
            } => *quality != MeasurementQuality::TooNoisy || *leak_probability < 0.01,
            Outcome::Fail {
                quality,
                leak_probability,
                ..
            } => *quality != MeasurementQuality::TooNoisy || *leak_probability > 0.99,
            Outcome::Research(res) => {
                // Research mode is reliable if we reached a confident conclusion
                matches!(
                    res.status,
                    ResearchStatus::EffectDetected | ResearchStatus::NoEffectDetected
                )
            }
        }
    }

    /// Unwrap a Pass result, panicking otherwise.
    pub fn unwrap_pass(self) -> (f64, EffectEstimate, MeasurementQuality, Diagnostics) {
        match self {
            Outcome::Pass {
                leak_probability,
                effect,
                quality,
                diagnostics,
                ..
            } => (leak_probability, effect, quality, diagnostics),
            _ => panic!("Expected Pass outcome, got {:?}", self),
        }
    }

    /// Unwrap a Fail result, panicking otherwise.
    pub fn unwrap_fail(
        self,
    ) -> (
        f64,
        EffectEstimate,
        Exploitability,
        MeasurementQuality,
        Diagnostics,
    ) {
        match self {
            Outcome::Fail {
                leak_probability,
                effect,
                exploitability,
                quality,
                diagnostics,
                ..
            } => (
                leak_probability,
                effect,
                exploitability,
                quality,
                diagnostics,
            ),
            _ => panic!("Expected Fail outcome, got {:?}", self),
        }
    }

    /// Handle unreliable results according to policy.
    ///
    /// Returns `Some(self)` if the result is reliable.
    /// For unreliable results:
    /// - `FailOpen`: prints warning, returns `None`
    /// - `FailClosed`: panics
    ///
    /// # Example
    ///
    /// ```ignore
    /// let outcome = oracle.test(...);
    /// if let Some(result) = outcome.handle_unreliable("test_name", UnreliablePolicy::FailOpen) {
    ///     assert!(result.passed());
    /// }
    /// ```
    #[cfg(feature = "std")]
    pub fn handle_unreliable(self, test_name: &str, policy: UnreliablePolicy) -> Option<Self> {
        if self.is_reliable() {
            return Some(self);
        }

        let reason = match &self {
            Outcome::Unmeasurable { recommendation, .. } => {
                format!("unmeasurable: {}", recommendation)
            }
            Outcome::Inconclusive { reason, .. } => {
                format!("inconclusive: {:?}", reason)
            }
            Outcome::Pass { quality, .. } | Outcome::Fail { quality, .. } => {
                format!("unreliable quality: {:?}", quality)
            }
            Outcome::Research(research) => {
                format!("research mode: {:?}", research.status)
            }
        };

        match policy {
            UnreliablePolicy::FailOpen => {
                eprintln!("[SKIPPED] {}: {} (fail-open policy)", test_name, reason);
                None
            }
            UnreliablePolicy::FailClosed => {
                panic!("[FAILED] {}: {} (fail-closed policy)", test_name, reason);
            }
        }
    }

    /// Handle unreliable results according to policy (no_std version).
    ///
    /// In no_std mode, this always panics on unreliable results with FailClosed,
    /// and returns None with FailOpen (no printing).
    #[cfg(not(feature = "std"))]
    pub fn handle_unreliable(self, _test_name: &str, policy: UnreliablePolicy) -> Option<Self> {
        if self.is_reliable() {
            return Some(self);
        }

        match policy {
            UnreliablePolicy::FailOpen => None,
            UnreliablePolicy::FailClosed => {
                panic!("Unreliable result with fail-closed policy");
            }
        }
    }
}

// ============================================================================
// Display implementations
// ============================================================================

impl fmt::Display for Outcome {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", crate::formatting::format_outcome_plain(self))
    }
}

impl fmt::Display for Exploitability {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Exploitability::SharedHardwareOnly => write!(f, "shared hardware only"),
            Exploitability::Http2Multiplexing => write!(f, "HTTP/2 multiplexing"),
            Exploitability::StandardRemote => write!(f, "standard remote"),
            Exploitability::ObviousLeak => write!(f, "obvious leak"),
        }
    }
}

impl fmt::Display for MeasurementQuality {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MeasurementQuality::Excellent => write!(f, "excellent"),
            MeasurementQuality::Good => write!(f, "good"),
            MeasurementQuality::Poor => write!(f, "poor"),
            MeasurementQuality::TooNoisy => write!(f, "too noisy"),
        }
    }
}

impl fmt::Display for InconclusiveReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            InconclusiveReason::DataTooNoisy { message, guidance } => {
                write!(f, "Data too noisy: {}\n  \u{2192} {}", message, guidance)
            }
            InconclusiveReason::NotLearning { message, guidance } => {
                write!(f, "Not learning: {}\n  \u{2192} {}", message, guidance)
            }
            InconclusiveReason::WouldTakeTooLong {
                estimated_time_secs,
                samples_needed,
                guidance,
            } => {
                write!(
                    f,
                    "Would take too long: ~{:.0}s / {} samples needed\n  \u{2192} {}",
                    estimated_time_secs, samples_needed, guidance
                )
            }
            InconclusiveReason::TimeBudgetExceeded { .. } => {
                write!(f, "Time budget exceeded")
            }
            InconclusiveReason::SampleBudgetExceeded { .. } => {
                write!(f, "Sample budget exceeded")
            }
            InconclusiveReason::ConditionsChanged { message, guidance } => {
                write!(
                    f,
                    "Conditions changed: {}\n  \u{2192} {}",
                    message, guidance
                )
            }
            InconclusiveReason::ThresholdElevated {
                theta_user,
                theta_eff,
                leak_probability_at_eff,
                achievable_at_max,
                guidance,
                ..
            } => {
                let achievability = if *achievable_at_max {
                    "achievable with more samples"
                } else {
                    "not achievable at max samples"
                };
                write!(
                    f,
                    "Threshold elevated: requested {:.1}ns, used {:.1}ns (P={:.1}% at θ_eff, {})\n  \u{2192} {}",
                    theta_user, theta_eff, leak_probability_at_eff * 100.0, achievability, guidance
                )
            }
        }
    }
}

// ============================================================================
// Debug implementation for Outcome
// ============================================================================

impl fmt::Debug for Outcome {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", crate::formatting::format_debug_summary_plain(self))
    }
}