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
//! Scenario runner for FrankenLab deterministic testing (bd-1hu19.2).
//!
//! Bridges [`Scenario`](super::scenario::Scenario) YAML specifications to
//! [`LabRuntime`](super::runtime::LabRuntime) execution, providing:
//!
//! - Timed fault injection based on scenario fault events
//! - Oracle filtering (only check oracles listed in the scenario)
//! - Seed exploration (run the same scenario across multiple seeds)
//! - Replay validation (run twice, verify identical trace certificates)
//!
//! # Quick Start
//!
//! ```ignore
//! use asupersync::lab::scenario_runner::{ScenarioRunner, ScenarioRunResult};
//! use asupersync::lab::scenario::Scenario;
//!
//! let yaml = std::fs::read_to_string("examples/scenarios/smoke_happy_path.yaml")?;
//! let scenario: Scenario = serde_yaml::from_str(&yaml)?;
//!
//! let result = ScenarioRunner::run(&scenario)?;
//! assert!(result.passed());
//! ```

use super::config::LabConfig;
use super::dual_run::{DualRunScenarioIdentity, ReplayMetadata, SeedLineageRecord};
use super::meta::mutation::ALL_ORACLE_INVARIANTS;
use super::oracle::OracleReport;
use super::runtime::{LabRunReport, LabRuntime};
use super::scenario::{FaultAction, FaultEvent, Scenario, ValidationError};
use crate::trace::replay::ReplayTrace;
use crate::types::Time;
use std::collections::{BTreeMap, HashSet};
use std::fmt::Write as _;

const LAB_SCENARIO_RUNNER_ADAPTER: &str = "lab.scenario_runner";

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Errors produced by the scenario runner.
#[derive(Debug)]
pub enum ScenarioRunnerError {
    /// Scenario validation failed.
    Validation {
        /// Scenario identifier that failed validation.
        scenario_id: String,
        /// Validation errors emitted by the scenario contract.
        errors: Vec<ValidationError>,
    },
    /// An oracle listed in the scenario is not recognized.
    UnknownOracle(String),
    /// Replay divergence: two runs with the same seed produced different traces.
    ReplayDivergence {
        /// The seed that diverged.
        seed: u64,
        /// Certificate from the first run.
        first: TraceCertificateSnapshot,
        /// Certificate from the second run.
        second: TraceCertificateSnapshot,
    },
}

impl std::fmt::Display for ScenarioRunnerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Validation {
                scenario_id,
                errors,
            } => {
                write!(
                    f,
                    "scenario validation failed for {scenario_id} ({} issue(s)):",
                    errors.len()
                )?;
                for e in errors {
                    write!(f, " {e};")?;
                }
                Ok(())
            }
            Self::UnknownOracle(name) => write!(f, "unknown oracle: {name}"),
            Self::ReplayDivergence {
                seed,
                first,
                second,
            } => write!(
                f,
                "replay divergence at seed {seed}: \
                 first(event_hash={}, schedule_hash={}, steps={}) != \
                 second(event_hash={}, schedule_hash={}, steps={})",
                first.event_hash,
                first.schedule_hash,
                first.steps,
                second.event_hash,
                second.schedule_hash,
                second.steps,
            ),
        }
    }
}

impl std::error::Error for ScenarioRunnerError {}

// ---------------------------------------------------------------------------
// Certificate snapshot (for replay validation)
// ---------------------------------------------------------------------------

/// Lightweight copy of trace identity for comparison.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TraceCertificateSnapshot {
    /// Hash of all trace events.
    pub event_hash: u64,
    /// Hash of scheduling decisions.
    pub schedule_hash: u64,
    /// Total steps executed.
    pub steps: u64,
    /// Trace fingerprint (Foata equivalence class).
    pub trace_fingerprint: u64,
}

/// Structured record for a scenario fault injection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FaultInjectionLogEntry {
    /// Virtual time in milliseconds when the fault fired.
    pub at_ms: u64,
    /// Stable fault action name.
    pub action: String,
    /// Canonical, sorted argument summary.
    pub args_summary: String,
    /// Redacted trace message emitted into the lab trace buffer.
    pub trace_message: String,
}

impl FaultInjectionLogEntry {
    /// Convert to JSON for artifact storage.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;
        json!({
            "at_ms": self.at_ms,
            "action": self.action,
            "args_summary": self.args_summary,
            "trace_message": self.trace_message,
        })
    }
}

/// Deterministic effect accounting for scenario fault actions.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FaultEffectSummary {
    /// Active disk-pressure bytes after all scheduled faults have fired.
    pub active_disk_pressure_bytes: u64,
    /// Maximum active disk-pressure bytes observed during the run.
    pub max_disk_pressure_bytes: u64,
    /// Number of disk-pressure events applied.
    pub disk_pressure_events: usize,
    /// Active disk-pressure bytes by canonical path.
    pub disk_pressure_by_path: BTreeMap<String, u64>,
    /// Total cleanup delay requested by delayed-cleanup faults.
    pub delayed_cleanup_total_ms: u64,
    /// Cleanup delay requested by phase.
    pub delayed_cleanup_phases: BTreeMap<String, u64>,
    /// Total bounded process-stall duration requested by process-stall faults.
    pub process_stall_total_ms: u64,
    /// Participants still stalled after the scheduled fault stream.
    pub stalled_participants_until_ms: BTreeMap<String, u64>,
    /// Resource-cap breaches observed while applying fault effects.
    pub resource_cap_breaches: Vec<String>,
}

impl FaultEffectSummary {
    fn fault_string_arg<'a>(fault: &'a FaultEvent, key: &str) -> Option<&'a str> {
        fault.args.get(key).and_then(serde_json::Value::as_str)
    }

    fn fault_u64_arg(fault: &FaultEvent, key: &str) -> Option<u64> {
        fault.args.get(key).and_then(serde_json::Value::as_u64)
    }

    fn refresh_active_disk_pressure(&mut self, cap: Option<u64>) {
        self.active_disk_pressure_bytes = self.disk_pressure_by_path.values().copied().sum();
        self.max_disk_pressure_bytes = self
            .max_disk_pressure_bytes
            .max(self.active_disk_pressure_bytes);

        if let Some(cap) = cap {
            if self.active_disk_pressure_bytes > cap {
                self.resource_cap_breaches.push(format!(
                    "disk_pressure_bytes:{}>{cap}",
                    self.active_disk_pressure_bytes
                ));
            }
        }
    }

    fn expire_process_stalls(&mut self, now_ms: u64) {
        self.stalled_participants_until_ms
            .retain(|_, resume_at_ms| *resume_at_ms > now_ms);
    }

    fn apply_fault(&mut self, fault: &FaultEvent, max_artifact_bytes: Option<u64>) {
        self.expire_process_stalls(fault.at_ms);

        match fault.action {
            FaultAction::DiskPressure => {
                if let (Some(path), Some(bytes)) = (
                    Self::fault_string_arg(fault, "path"),
                    Self::fault_u64_arg(fault, "bytes"),
                ) {
                    self.disk_pressure_events += 1;
                    self.disk_pressure_by_path.insert(path.to_string(), bytes);
                    self.refresh_active_disk_pressure(max_artifact_bytes);
                }
            }
            FaultAction::DiskRecovered => {
                if let Some(path) = Self::fault_string_arg(fault, "path") {
                    self.disk_pressure_by_path.remove(path);
                    self.refresh_active_disk_pressure(max_artifact_bytes);
                }
            }
            FaultAction::DelayedCleanup => {
                if let (Some(phase), Some(delay_ms)) = (
                    Self::fault_string_arg(fault, "phase"),
                    Self::fault_u64_arg(fault, "delay_ms"),
                ) {
                    self.delayed_cleanup_total_ms =
                        self.delayed_cleanup_total_ms.saturating_add(delay_ms);
                    self.delayed_cleanup_phases
                        .entry(phase.to_string())
                        .and_modify(|total| *total = total.saturating_add(delay_ms))
                        .or_insert(delay_ms);
                }
            }
            FaultAction::ProcessStall => {
                if let (Some(host), Some(duration_ms)) = (
                    Self::fault_string_arg(fault, "host"),
                    Self::fault_u64_arg(fault, "duration_ms"),
                ) {
                    self.process_stall_total_ms =
                        self.process_stall_total_ms.saturating_add(duration_ms);
                    self.stalled_participants_until_ms
                        .insert(host.to_string(), fault.at_ms.saturating_add(duration_ms));
                }
            }
            FaultAction::ProcessResume => {
                if let Some(host) = Self::fault_string_arg(fault, "host") {
                    self.stalled_participants_until_ms.remove(host);
                }
            }
            FaultAction::Partition
            | FaultAction::Heal
            | FaultAction::HostCrash
            | FaultAction::HostRestart
            | FaultAction::ClockSkew
            | FaultAction::ClockReset => {}
        }
    }

    /// Convert to JSON for artifact storage.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;
        let active_stalled_participants = self
            .stalled_participants_until_ms
            .keys()
            .cloned()
            .collect::<Vec<_>>();

        json!({
            "active_disk_pressure_bytes": self.active_disk_pressure_bytes,
            "max_disk_pressure_bytes": self.max_disk_pressure_bytes,
            "disk_pressure_events": self.disk_pressure_events,
            "disk_pressure_by_path": self.disk_pressure_by_path,
            "delayed_cleanup_total_ms": self.delayed_cleanup_total_ms,
            "delayed_cleanup_phases": self.delayed_cleanup_phases,
            "process_stall_total_ms": self.process_stall_total_ms,
            "active_stalled_participants": active_stalled_participants,
            "stalled_participants_until_ms": self.stalled_participants_until_ms,
            "resource_cap_breaches": self.resource_cap_breaches,
        })
    }
}

/// Deterministic minimized counterexample packet for unresolved scenario faults.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MinimizedCounterexamplePacket {
    /// Scenario identifier that produced the counterexample.
    pub scenario_id: String,
    /// Stable reason for the packet.
    pub reason: String,
    /// Number of fault-log entries retained in the minimized packet.
    pub prefix_len: usize,
    /// Total scheduled fault count from the original scenario run.
    pub fault_count: usize,
    /// Configured maximum counterexample events.
    pub max_counterexample_events: usize,
    /// Participants still stalled at the end of the scheduled fault stream.
    pub active_stalled_participants: Vec<String>,
    /// Redacted fault-log entries retained for replay/debugging.
    pub fault_log_prefix: Vec<FaultInjectionLogEntry>,
    /// Whether the source scenario requested redacted projection.
    pub redacted: bool,
}

impl MinimizedCounterexamplePacket {
    /// Convert to JSON for artifact storage.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;
        json!({
            "scenario_id": self.scenario_id,
            "reason": self.reason,
            "prefix_len": self.prefix_len,
            "fault_count": self.fault_count,
            "max_counterexample_events": self.max_counterexample_events,
            "active_stalled_participants": self.active_stalled_participants,
            "fault_log_prefix": self
                .fault_log_prefix
                .iter()
                .map(FaultInjectionLogEntry::to_json)
                .collect::<Vec<_>>(),
            "redacted": self.redacted,
        })
    }
}

// ---------------------------------------------------------------------------
// Run result
// ---------------------------------------------------------------------------

/// Result of running a single scenario.
#[derive(Debug, Clone)]
pub struct ScenarioRunResult {
    /// Scenario identifier.
    pub scenario_id: String,
    /// Seed used for this run.
    pub seed: u64,
    /// The underlying lab run report.
    pub lab_report: LabRunReport,
    /// Filtered oracle report (only oracles listed in the scenario).
    pub oracle_report: FilteredOracleReport,
    /// Number of fault events injected during the run.
    pub faults_injected: usize,
    /// Structured log of fault injections, in deterministic execution order.
    pub fault_log: Vec<FaultInjectionLogEntry>,
    /// Deterministic summary of effects applied by fault injection.
    pub fault_effect_summary: FaultEffectSummary,
    /// Minimized counterexample packet when bounded fault effects remain unresolved.
    pub minimized_counterexample: Option<MinimizedCounterexamplePacket>,
    /// Replay trace, if recording was enabled.
    pub replay_trace: Option<ReplayTrace>,
    /// Trace certificate snapshot for replay validation.
    pub certificate: TraceCertificateSnapshot,
    /// Adapter identity that produced this lab result.
    pub adapter: String,
    /// Shared dual-run replay metadata for this execution.
    pub replay_metadata: ReplayMetadata,
    /// Stable seed-lineage audit record for this execution.
    pub seed_lineage: SeedLineageRecord,
}

impl ScenarioRunResult {
    /// Returns true if all checked oracles passed and no invariant violations were found.
    #[must_use]
    pub fn passed(&self) -> bool {
        self.lab_report.quiescent
            && self.oracle_report.all_passed
            && self.lab_report.invariant_violations.is_empty()
    }

    /// Convert to JSON for artifact storage.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;
        json!({
            "scenario_id": self.scenario_id,
            "surface_id": self.replay_metadata.family.surface_id,
            "surface_contract_version": self.replay_metadata.family.surface_contract_version,
            "seed": self.seed,
            "seed_lineage_id": self.seed_lineage.seed_lineage_id,
            "adapter": self.adapter,
            "execution_instance_id": self.replay_metadata.instance.key(),
            "passed": self.passed(),
            "steps": self.lab_report.steps_total,
            "faults_injected": self.faults_injected,
            "fault_log": self.fault_log.iter().map(FaultInjectionLogEntry::to_json).collect::<Vec<_>>(),
            "fault_effect_summary": self.fault_effect_summary.to_json(),
            "minimized_counterexample": self
                .minimized_counterexample
                .as_ref()
                .map(MinimizedCounterexamplePacket::to_json),
            "certificate": {
                "event_hash": self.certificate.event_hash,
                "schedule_hash": self.certificate.schedule_hash,
                "trace_fingerprint": self.certificate.trace_fingerprint,
            },
            "oracle_report": self.oracle_report.to_json(),
            "invariant_violations": self.lab_report.invariant_violations,
            "replay_metadata": &self.replay_metadata,
            "seed_lineage": &self.seed_lineage,
        })
    }
}

// ---------------------------------------------------------------------------
// Filtered oracle report
// ---------------------------------------------------------------------------

/// Oracle report filtered to only the oracles requested by the scenario.
#[derive(Debug, Clone)]
pub struct FilteredOracleReport {
    /// The full oracle report from the runtime.
    pub full_report: OracleReport,
    /// Which oracle names were checked.
    pub checked: Vec<String>,
    /// Which checked oracles passed.
    pub passed_count: usize,
    /// Which checked oracles failed.
    pub failed_count: usize,
    /// Whether all checked oracles passed.
    pub all_passed: bool,
    /// Entries for only the checked oracles.
    pub entries: Vec<super::oracle::OracleEntryReport>,
}

impl FilteredOracleReport {
    fn from_full(full_report: OracleReport, oracle_names: &[String]) -> Self {
        let check_all = oracle_names.iter().any(|n| n == "all");
        let oracle_filter = (!check_all).then(|| {
            oracle_names
                .iter()
                .map(String::as_str)
                .collect::<HashSet<_>>()
        });

        let entries: Vec<_> = if check_all {
            full_report.entries.clone()
        } else {
            full_report
                .entries
                .iter()
                .filter(|e| {
                    oracle_filter
                        .as_ref()
                        .is_some_and(|filter| filter.contains(e.invariant.as_str()))
                })
                .cloned()
                .collect()
        };

        let checked: Vec<String> = entries.iter().map(|e| e.invariant.clone()).collect();
        let passed_count = entries.iter().filter(|e| e.passed).count();
        let failed_count = entries.len() - passed_count;
        let all_passed = failed_count == 0;

        Self {
            full_report,
            checked,
            passed_count,
            failed_count,
            all_passed,
            entries,
        }
    }

    /// Convert to JSON.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;
        json!({
            "checked": self.checked,
            "passed": self.passed_count,
            "failed": self.failed_count,
            "all_passed": self.all_passed,
            "entries": self.entries.iter().map(|e| {
                let mut v = serde_json::Map::new();
                v.insert("invariant".into(), json!(e.invariant));
                v.insert("passed".into(), json!(e.passed));
                if let Some(ref violation) = e.violation {
                    v.insert("violation".into(), json!(violation));
                }
                serde_json::Value::Object(v)
            }).collect::<Vec<_>>(),
        })
    }
}

// ---------------------------------------------------------------------------
// Exploration result
// ---------------------------------------------------------------------------

/// Result of exploring a scenario across multiple seeds.
#[derive(Debug, Clone)]
pub struct ScenarioExplorationResult {
    /// Scenario identifier.
    pub scenario_id: String,
    /// Number of seeds explored.
    pub seeds_explored: usize,
    /// Number of passing runs.
    pub passed: usize,
    /// Number of failing runs.
    pub failed: usize,
    /// Unique trace fingerprints observed.
    pub unique_fingerprints: usize,
    /// Per-seed results (seed → pass/fail + fingerprint).
    pub runs: Vec<ExplorationRunSummary>,
    /// First failing seed, if any.
    pub first_failure_seed: Option<u64>,
}

impl ScenarioExplorationResult {
    /// Returns true if all explored seeds passed.
    #[must_use]
    pub fn all_passed(&self) -> bool {
        self.failed == 0
    }

    /// Convert to JSON.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;
        json!({
            "scenario_id": self.scenario_id,
            "seeds_explored": self.seeds_explored,
            "passed": self.passed,
            "failed": self.failed,
            "unique_fingerprints": self.unique_fingerprints,
            "first_failure_seed": self.first_failure_seed,
            "runs": self.runs.iter().map(ExplorationRunSummary::to_json).collect::<Vec<_>>(),
        })
    }
}

/// Summary of a single exploration run.
#[derive(Debug, Clone)]
pub struct ExplorationRunSummary {
    /// Seed used.
    pub seed: u64,
    /// Whether the run passed.
    pub passed: bool,
    /// Steps executed.
    pub steps: u64,
    /// Trace fingerprint.
    pub fingerprint: u64,
    /// Failure descriptions, if any.
    pub failures: Vec<String>,
}

impl ExplorationRunSummary {
    /// Convert to JSON.
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        use serde_json::json;
        json!({
            "seed": self.seed,
            "passed": self.passed,
            "steps": self.steps,
            "fingerprint": self.fingerprint,
            "failures": self.failures,
        })
    }
}

// ---------------------------------------------------------------------------
// ScenarioRunner
// ---------------------------------------------------------------------------

/// Execution engine for FrankenLab scenarios.
///
/// Bridges [`Scenario`] YAML specifications to deterministic runtime execution.
pub struct ScenarioRunner;

impl ScenarioRunner {
    fn scenario_surface_id(scenario: &Scenario) -> String {
        scenario
            .metadata
            .get("surface_id")
            .cloned()
            .unwrap_or_else(|| scenario.id.clone())
    }

    fn scenario_surface_contract_version(scenario: &Scenario) -> String {
        scenario
            .metadata
            .get("surface_contract_version")
            .cloned()
            .unwrap_or_else(|| format!("{}.v1", scenario.id))
    }

    fn scenario_seed_lineage_id(scenario: &Scenario) -> String {
        scenario
            .metadata
            .get("seed_lineage_id")
            .cloned()
            .unwrap_or_else(|| format!("seed.{}.v1", scenario.id))
    }

    fn scenario_identity(
        scenario: &Scenario,
        seed_override: Option<u64>,
    ) -> DualRunScenarioIdentity {
        let description = if scenario.description.trim().is_empty() {
            format!("Scenario {}", scenario.id)
        } else {
            scenario.description.clone()
        };
        let mut identity = DualRunScenarioIdentity::phase1(
            &scenario.id,
            Self::scenario_surface_id(scenario),
            Self::scenario_surface_contract_version(scenario),
            description,
            scenario.lab.seed,
        );
        let mut seed_plan = identity.seed_plan.clone();
        seed_plan.seed_lineage_id = Self::scenario_seed_lineage_id(scenario);
        if let Some(seed) = seed_override {
            seed_plan = seed_plan.with_lab_override(seed);
        }
        if let Some(entropy_seed) = scenario.lab.entropy_seed {
            seed_plan = seed_plan.with_entropy_seed(entropy_seed);
        }
        identity = identity.with_seed_plan(seed_plan);
        for (key, value) in &scenario.metadata {
            identity = identity.with_metadata(key.clone(), value.clone());
        }
        identity
    }

    fn replay_metadata_for_run(
        identity: &DualRunScenarioIdentity,
        lab_report: &LabRunReport,
    ) -> ReplayMetadata {
        identity
            .lab_replay_metadata()
            .with_lab_report(
                lab_report.trace_fingerprint,
                lab_report.trace_certificate.event_hash,
                lab_report.trace_certificate.event_count,
                lab_report.trace_certificate.schedule_hash,
                lab_report.steps_total,
            )
            .with_repro_command(format!(
                "ASUPERSYNC_SEED=0x{:X} rch exec -- cargo test {} -- --nocapture",
                lab_report.seed, identity.scenario_id
            ))
    }

    fn validation_error(scenario: &Scenario, errors: Vec<ValidationError>) -> ScenarioRunnerError {
        ScenarioRunnerError::Validation {
            scenario_id: scenario.id.clone(),
            errors,
        }
    }

    /// Validate oracle names in a scenario against the known oracle registry.
    fn validate_oracle_names(scenario: &Scenario) -> Result<(), ScenarioRunnerError> {
        for name in &scenario.oracles {
            if name == "all" {
                continue;
            }
            if !ALL_ORACLE_INVARIANTS.contains(&name.as_str()) {
                return Err(ScenarioRunnerError::UnknownOracle(name.clone()));
            }
        }
        Ok(())
    }

    /// Create a `LabConfig` from a scenario, always enabling replay recording.
    fn lab_config_for(scenario: &Scenario, seed_override: Option<u64>) -> LabConfig {
        let config = seed_override.map_or_else(
            || scenario.to_lab_config(),
            |seed| {
                let mut modified = scenario.clone();
                modified.lab.seed = seed;
                modified.to_lab_config()
            },
        );
        // Always enable replay recording so we get trace certificates
        config.with_default_replay_recording()
    }

    /// Create a `LabConfig` from a scenario plus an explicit dual-run identity.
    fn lab_config_for_identity(
        scenario: &Scenario,
        identity: &DualRunScenarioIdentity,
    ) -> LabConfig {
        let mut config = scenario.to_lab_config();
        let effective_seed = identity.seed_plan.effective_lab_seed();
        config.seed = effective_seed;
        config.entropy_seed = identity.seed_plan.effective_entropy_seed(effective_seed);
        config.with_default_replay_recording()
    }

    /// Inject timed fault events into the runtime.
    ///
    /// Processes faults in `at_ms` order, advancing virtual time and injecting
    /// each fault action. Between faults, the runtime runs to idle.
    fn inject_faults(
        runtime: &mut LabRuntime,
        scenario: &Scenario,
    ) -> (Vec<FaultInjectionLogEntry>, FaultEffectSummary) {
        let mut fault_log = Vec::with_capacity(scenario.faults.len());
        let mut fault_effect_summary = FaultEffectSummary::default();

        for fault in &scenario.faults {
            // Advance time to the fault trigger point
            let target_nanos = fault.at_ms.saturating_mul(1_000_000);
            let target_time = Time::from_nanos(target_nanos);
            if target_time > runtime.now() {
                let delta_nanos = target_time.as_nanos() - runtime.now().as_nanos();
                runtime.advance_time(delta_nanos);
            }

            // Run to idle so pending tasks respond to the current state
            runtime.run_until_idle();

            // Record the fault as a user_trace event
            let action_name = match fault.action {
                FaultAction::Partition => "partition",
                FaultAction::Heal => "heal",
                FaultAction::DiskPressure => "disk_pressure",
                FaultAction::DiskRecovered => "disk_recovered",
                FaultAction::DelayedCleanup => "delayed_cleanup",
                FaultAction::ProcessStall => "process_stall",
                FaultAction::ProcessResume => "process_resume",
                FaultAction::HostCrash => "host_crash",
                FaultAction::HostRestart => "host_restart",
                FaultAction::ClockSkew => "clock_skew",
                FaultAction::ClockReset => "clock_reset",
            };
            let args_summary = Self::fault_args_summary(&fault.args);
            let trace_message = format!("fault:{action_name}:{args_summary}");
            let now = runtime.now();
            let trace_message_for_event = trace_message.clone();
            runtime.state.record_trace_event(|seq| {
                crate::trace::TraceEvent::user_trace(seq, now, trace_message_for_event)
            });
            fault_log.push(FaultInjectionLogEntry {
                at_ms: fault.at_ms,
                action: action_name.to_string(),
                args_summary,
                trace_message,
            });
            fault_effect_summary.apply_fault(fault, scenario.resource_caps.max_artifact_bytes);
        }

        (fault_log, fault_effect_summary)
    }

    /// Summarize fault args for trace events.
    fn fault_args_summary(args: &BTreeMap<String, serde_json::Value>) -> String {
        let mut summary = String::new();
        for (index, (key, value)) in args.iter().enumerate() {
            if index > 0 {
                summary.push(',');
            }
            summary.push_str(key);
            summary.push('=');
            match value {
                serde_json::Value::String(s) => summary.push_str(s),
                other => {
                    let _ = write!(&mut summary, "{other}");
                }
            }
        }
        summary
    }

    fn minimized_counterexample_for(
        scenario: &Scenario,
        fault_log: &[FaultInjectionLogEntry],
        fault_effect_summary: &FaultEffectSummary,
    ) -> Option<MinimizedCounterexamplePacket> {
        if !scenario.minimization.enabled
            || fault_effect_summary
                .stalled_participants_until_ms
                .is_empty()
        {
            return None;
        }

        let active_stalled_participants = fault_effect_summary
            .stalled_participants_until_ms
            .keys()
            .cloned()
            .collect::<Vec<_>>();
        let first_stall_index = fault_log.iter().enumerate().find_map(|(index, entry)| {
            if entry.action != "process_stall" {
                return None;
            }
            let host_is_still_stalled = entry.args_summary.split(',').any(|arg| {
                arg.strip_prefix("host=").is_some_and(|host| {
                    fault_effect_summary
                        .stalled_participants_until_ms
                        .contains_key(host)
                })
            });
            host_is_still_stalled.then_some(index)
        })?;
        let max_counterexample_events = scenario
            .minimization
            .max_counterexample_events
            .or(scenario.resource_caps.max_counterexample_events)
            .unwrap_or(fault_log.len())
            .max(1);
        let required_prefix_len = first_stall_index.saturating_add(1).min(fault_log.len());
        let retained_len = required_prefix_len.min(max_counterexample_events);
        let retained_start = required_prefix_len.saturating_sub(retained_len);
        let fault_log_prefix = fault_log
            .iter()
            .skip(retained_start)
            .take(retained_len)
            .cloned()
            .collect::<Vec<_>>();
        let prefix_len = fault_log_prefix.len();

        Some(MinimizedCounterexamplePacket {
            scenario_id: scenario.id.clone(),
            reason: "unresolved_process_stall".to_string(),
            prefix_len,
            fault_count: fault_log.len(),
            max_counterexample_events,
            active_stalled_participants,
            fault_log_prefix,
            redacted: scenario.golden_projection.redacted,
        })
    }

    /// Build a certificate snapshot from a lab report.
    fn certificate_snapshot(report: &LabRunReport) -> TraceCertificateSnapshot {
        TraceCertificateSnapshot {
            event_hash: report.trace_certificate.event_hash,
            schedule_hash: report.trace_certificate.schedule_hash,
            steps: report.steps_total,
            trace_fingerprint: report.trace_fingerprint,
        }
    }

    /// Run a scenario with the default seed.
    ///
    /// # Errors
    ///
    /// Returns an error if the scenario fails validation or contains unknown oracle names.
    pub fn run(scenario: &Scenario) -> Result<ScenarioRunResult, ScenarioRunnerError> {
        Self::run_with_seed(scenario, None)
    }

    /// Run a scenario using an explicit dual-run identity and seed plan.
    ///
    /// This keeps scenario-family metadata stable while allowing the concrete
    /// lab execution seed to vary via the identity's seed plan.
    ///
    /// # Errors
    ///
    /// Returns an error if the scenario fails validation or contains unknown oracle names.
    pub fn run_with_identity(
        scenario: &Scenario,
        identity: &DualRunScenarioIdentity,
    ) -> Result<ScenarioRunResult, ScenarioRunnerError> {
        let errors = scenario.validate();
        if !errors.is_empty() {
            return Err(Self::validation_error(scenario, errors));
        }
        Self::validate_oracle_names(scenario)?;

        let effective_seed = identity.seed_plan.effective_lab_seed();
        let config = Self::lab_config_for_identity(scenario, identity);
        let mut runtime = LabRuntime::new(config);

        let (fault_log, fault_effect_summary) = Self::inject_faults(&mut runtime, scenario);
        let faults_injected = fault_log.len();
        let minimized_counterexample =
            Self::minimized_counterexample_for(scenario, &fault_log, &fault_effect_summary);
        runtime.run_until_quiescent();

        let lab_report = runtime.report();
        let certificate = Self::certificate_snapshot(&lab_report);
        let replay_metadata = Self::replay_metadata_for_run(identity, &lab_report);
        let seed_lineage = identity.seed_lineage();
        let oracle_report =
            FilteredOracleReport::from_full(lab_report.oracle_report.clone(), &scenario.oracles);
        let replay_trace = runtime.finish_replay_trace();

        Ok(ScenarioRunResult {
            scenario_id: scenario.id.clone(),
            seed: effective_seed,
            lab_report,
            oracle_report,
            faults_injected,
            fault_log,
            fault_effect_summary,
            minimized_counterexample,
            replay_trace,
            certificate,
            adapter: LAB_SCENARIO_RUNNER_ADAPTER.to_string(),
            replay_metadata,
            seed_lineage,
        })
    }

    /// Run a scenario, optionally overriding the seed.
    ///
    /// # Errors
    ///
    /// Returns an error if the scenario fails validation or contains unknown oracle names.
    pub fn run_with_seed(
        scenario: &Scenario,
        seed_override: Option<u64>,
    ) -> Result<ScenarioRunResult, ScenarioRunnerError> {
        // 1. Validate
        let errors = scenario.validate();
        if !errors.is_empty() {
            return Err(Self::validation_error(scenario, errors));
        }
        Self::validate_oracle_names(scenario)?;

        // 2. Build runtime
        let effective_seed = seed_override.unwrap_or(scenario.lab.seed);
        let config = Self::lab_config_for(scenario, seed_override);
        let mut runtime = LabRuntime::new(config);

        // 3. Inject timed faults and run between them
        let (fault_log, fault_effect_summary) = Self::inject_faults(&mut runtime, scenario);
        let faults_injected = fault_log.len();
        let minimized_counterexample =
            Self::minimized_counterexample_for(scenario, &fault_log, &fault_effect_summary);

        // 4. Run to quiescence after all faults
        runtime.run_until_quiescent();

        // 5. Collect report
        let lab_report = runtime.report();
        let certificate = Self::certificate_snapshot(&lab_report);
        let identity = Self::scenario_identity(scenario, seed_override);
        let replay_metadata = Self::replay_metadata_for_run(&identity, &lab_report);
        let seed_lineage = identity.seed_lineage();

        // 6. Filter oracle results
        let oracle_report =
            FilteredOracleReport::from_full(lab_report.oracle_report.clone(), &scenario.oracles);

        // 7. Extract replay trace
        let replay_trace = runtime.finish_replay_trace();

        Ok(ScenarioRunResult {
            scenario_id: scenario.id.clone(),
            seed: effective_seed,
            lab_report,
            oracle_report,
            faults_injected,
            fault_log,
            fault_effect_summary,
            minimized_counterexample,
            replay_trace,
            certificate,
            adapter: LAB_SCENARIO_RUNNER_ADAPTER.to_string(),
            replay_metadata,
            seed_lineage,
        })
    }

    /// Explore a scenario across a range of seeds.
    ///
    /// Runs the scenario once per seed in `seed_start..seed_start+count` and
    /// collects results. Useful for finding schedule-dependent bugs.
    ///
    /// # Errors
    ///
    /// Returns an error if the scenario fails validation or contains unknown oracle names.
    pub fn explore_seeds(
        scenario: &Scenario,
        seed_start: u64,
        count: usize,
    ) -> Result<ScenarioExplorationResult, ScenarioRunnerError> {
        // Validate once up front
        let errors = scenario.validate();
        if !errors.is_empty() {
            return Err(Self::validation_error(scenario, errors));
        }
        Self::validate_oracle_names(scenario)?;

        let mut runs = Vec::with_capacity(count);
        let mut fingerprint_set = std::collections::HashSet::new();
        let mut first_failure_seed = None;

        for i in 0..count {
            let seed = seed_start.wrapping_add(i as u64);
            // Run with this seed (skip validation since we already validated)
            let result = Self::run_with_seed(scenario, Some(seed))?;

            fingerprint_set.insert(result.certificate.trace_fingerprint);

            let passed = result.passed();
            let failures: Vec<String> = if passed {
                Vec::new()
            } else {
                let mut f: Vec<String> = result
                    .oracle_report
                    .entries
                    .iter()
                    .filter(|e| !e.passed)
                    .map(|e| {
                        format!(
                            "{}: {}",
                            e.invariant,
                            e.violation.as_deref().unwrap_or("failed")
                        )
                    })
                    .collect();
                f.extend(result.lab_report.invariant_violations.clone());
                if !result.lab_report.quiescent {
                    f.push("runtime not quiescent at report boundary".to_string());
                }
                f
            };

            if !passed && first_failure_seed.is_none() {
                first_failure_seed = Some(seed);
            }

            runs.push(ExplorationRunSummary {
                seed,
                passed,
                steps: result.lab_report.steps_total,
                fingerprint: result.certificate.trace_fingerprint,
                failures,
            });
        }

        let passed = runs.iter().filter(|r| r.passed).count();
        let failed = runs.len() - passed;

        Ok(ScenarioExplorationResult {
            scenario_id: scenario.id.clone(),
            seeds_explored: count,
            passed,
            failed,
            unique_fingerprints: fingerprint_set.len(),
            runs,
            first_failure_seed,
        })
    }

    /// Validate replay determinism: run a scenario twice with the same seed
    /// and verify identical trace certificates.
    ///
    /// # Errors
    ///
    /// Returns `ReplayDivergence` if the two runs produce different certificates.
    pub fn validate_replay(scenario: &Scenario) -> Result<ScenarioRunResult, ScenarioRunnerError> {
        let first = Self::run(scenario)?;
        let second = Self::run(scenario)?;

        if first.certificate != second.certificate {
            return Err(ScenarioRunnerError::ReplayDivergence {
                seed: first.seed,
                first: first.certificate,
                second: second.certificate,
            });
        }

        Ok(first)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[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::*;
    use crate::lab::scenario::{
        ChaosSection, FaultAction, FaultEvent, LabSection, MinimizationSection, NetworkSection,
        Scenario,
    };
    use std::collections::BTreeMap;

    fn init_test(name: &str) {
        crate::test_utils::init_test_logging();
        crate::test_phase!(name);
    }

    fn minimal_scenario() -> Scenario {
        Scenario {
            schema_version: 1,
            id: "test-minimal".to_string(),
            description: "Minimal test scenario".to_string(),
            lab: LabSection::default(),
            chaos: ChaosSection::Off,
            network: NetworkSection::default(),
            ..Scenario::default()
        }
    }

    #[test]
    fn run_minimal_scenario() {
        init_test("run_minimal_scenario");
        let scenario = minimal_scenario();
        let result = ScenarioRunner::run(&scenario).unwrap();
        assert!(result.passed(), "minimal scenario should pass");
        assert_eq!(result.scenario_id, "test-minimal");
        assert_eq!(result.seed, 42);
        assert_eq!(result.faults_injected, 0);
        assert_eq!(result.adapter, LAB_SCENARIO_RUNNER_ADAPTER);
        assert_eq!(result.replay_metadata.family.surface_id, "test-minimal");
        assert_eq!(
            result.replay_metadata.family.surface_contract_version,
            "test-minimal.v1"
        );
        assert_eq!(result.seed_lineage.seed_lineage_id, "seed.test-minimal.v1");
        crate::test_complete!("run_minimal_scenario");
    }

    #[test]
    fn run_with_seed_preserves_family_and_tracks_execution_seed() {
        init_test("run_with_seed_preserves_family_and_tracks_execution_seed");
        let scenario = minimal_scenario();
        let result = ScenarioRunner::run_with_seed(&scenario, Some(7)).unwrap();

        assert_eq!(result.seed, 7);
        assert_eq!(result.replay_metadata.family.id, "test-minimal");
        assert_eq!(result.replay_metadata.effective_seed, 7);
        assert_eq!(result.seed_lineage.canonical_seed, 42);
        assert_eq!(result.seed_lineage.lab_effective_seed, 7);

        crate::test_complete!("run_with_seed_preserves_family_and_tracks_execution_seed");
    }

    #[test]
    fn passed_requires_quiescence() {
        init_test("passed_requires_quiescence");
        let scenario = minimal_scenario();
        let result = ScenarioRunner::run(&scenario).unwrap();
        assert!(result.passed());

        let mut forced_non_quiescent = result;
        forced_non_quiescent.lab_report.quiescent = false;
        assert!(!forced_non_quiescent.passed());
        crate::test_complete!("passed_requires_quiescence");
    }

    #[test]
    fn run_with_seed_override() {
        init_test("run_with_seed_override");
        let scenario = minimal_scenario();
        let result = ScenarioRunner::run_with_seed(&scenario, Some(123)).unwrap();
        assert_eq!(result.seed, 123);
        assert!(result.passed());
        crate::test_complete!("run_with_seed_override");
    }

    #[test]
    fn run_with_faults() {
        init_test("run_with_faults");
        let mut scenario = minimal_scenario();
        scenario.faults = vec![
            FaultEvent {
                at_ms: 10,
                action: FaultAction::Partition,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("from".into(), serde_json::json!("alice"));
                    m.insert("to".into(), serde_json::json!("bob"));
                    m
                },
            },
            FaultEvent {
                at_ms: 50,
                action: FaultAction::Heal,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("from".into(), serde_json::json!("alice"));
                    m.insert("to".into(), serde_json::json!("bob"));
                    m
                },
            },
        ];
        let result = ScenarioRunner::run(&scenario).unwrap();
        assert!(result.passed());
        assert_eq!(result.faults_injected, 2);
        crate::test_complete!("run_with_faults");
    }

    #[test]
    fn run_with_all_fault_types() {
        init_test("run_with_all_fault_types");
        let mut scenario = minimal_scenario();
        scenario.participants = vec![
            crate::lab::scenario::Participant {
                name: "alice".to_string(),
                role: "sender".to_string(),
                properties: BTreeMap::new(),
            },
            crate::lab::scenario::Participant {
                name: "bob".to_string(),
                role: "receiver".to_string(),
                properties: BTreeMap::new(),
            },
        ];
        scenario.faults = vec![
            FaultEvent {
                at_ms: 10,
                action: FaultAction::Partition,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("from".into(), serde_json::json!("alice"));
                    m.insert("to".into(), serde_json::json!("bob"));
                    m
                },
            },
            FaultEvent {
                at_ms: 20,
                action: FaultAction::Heal,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("from".into(), serde_json::json!("alice"));
                    m.insert("to".into(), serde_json::json!("bob"));
                    m
                },
            },
            FaultEvent {
                at_ms: 30,
                action: FaultAction::DiskPressure,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("path".into(), serde_json::json!("target/proof"));
                    m.insert("bytes".into(), serde_json::json!(4096));
                    m
                },
            },
            FaultEvent {
                at_ms: 40,
                action: FaultAction::DiskRecovered,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("path".into(), serde_json::json!("target/proof"));
                    m
                },
            },
            FaultEvent {
                at_ms: 50,
                action: FaultAction::DelayedCleanup,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("phase".into(), serde_json::json!("finalizers"));
                    m.insert("delay_ms".into(), serde_json::json!(25));
                    m
                },
            },
            FaultEvent {
                at_ms: 60,
                action: FaultAction::ProcessStall,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("host".into(), serde_json::json!("alice"));
                    m.insert("duration_ms".into(), serde_json::json!(40));
                    m
                },
            },
            FaultEvent {
                at_ms: 70,
                action: FaultAction::ProcessResume,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("host".into(), serde_json::json!("alice"));
                    m
                },
            },
            FaultEvent {
                at_ms: 80,
                action: FaultAction::HostCrash,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("host".into(), serde_json::json!("bob"));
                    m
                },
            },
            FaultEvent {
                at_ms: 90,
                action: FaultAction::HostRestart,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("host".into(), serde_json::json!("bob"));
                    m
                },
            },
            FaultEvent {
                at_ms: 100,
                action: FaultAction::ClockSkew,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("host".into(), serde_json::json!("alice"));
                    m.insert("skew_ms".into(), serde_json::json!(5));
                    m
                },
            },
            FaultEvent {
                at_ms: 110,
                action: FaultAction::ClockReset,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("host".into(), serde_json::json!("alice"));
                    m
                },
            },
        ];
        let result = ScenarioRunner::run(&scenario).unwrap();
        assert!(result.passed());
        assert_eq!(result.faults_injected, 11);
        crate::test_complete!("run_with_all_fault_types");
    }

    #[test]
    fn process_stall_counterexample_keeps_causal_event_under_small_cap() {
        init_test("process_stall_counterexample_keeps_causal_event_under_small_cap");
        let mut scenario = minimal_scenario();
        scenario.participants = vec![crate::lab::scenario::Participant {
            name: "alice".to_string(),
            role: "worker".to_string(),
            properties: BTreeMap::new(),
        }];
        scenario.minimization = MinimizationSection {
            enabled: true,
            max_evaluations: Some(4),
            max_counterexample_events: Some(1),
        };
        scenario.faults = vec![
            FaultEvent {
                at_ms: 10,
                action: FaultAction::DiskPressure,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("path".into(), serde_json::json!("target/proof"));
                    m.insert("bytes".into(), serde_json::json!(4096));
                    m
                },
            },
            FaultEvent {
                at_ms: 20,
                action: FaultAction::DelayedCleanup,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("phase".into(), serde_json::json!("finalizers"));
                    m.insert("delay_ms".into(), serde_json::json!(25));
                    m
                },
            },
            FaultEvent {
                at_ms: 30,
                action: FaultAction::ProcessStall,
                args: {
                    let mut m = BTreeMap::new();
                    m.insert("host".into(), serde_json::json!("alice"));
                    m.insert("duration_ms".into(), serde_json::json!(1_000));
                    m
                },
            },
        ];

        let result = ScenarioRunner::run(&scenario).unwrap();
        let counterexample = result
            .minimized_counterexample
            .expect("active process stall should emit a counterexample");

        assert_eq!(counterexample.max_counterexample_events, 1);
        assert_eq!(counterexample.prefix_len, 1);
        assert_eq!(counterexample.fault_log_prefix.len(), 1);
        let retained = &counterexample.fault_log_prefix[0];
        assert_eq!(retained.action, "process_stall");
        assert!(
            retained
                .args_summary
                .split(',')
                .any(|arg| arg == "host=alice"),
            "counterexample must retain the causal stalled host"
        );
        crate::test_complete!("process_stall_counterexample_keeps_causal_event_under_small_cap");
    }

    #[test]
    fn validation_rejects_bad_scenario() {
        init_test("validation_rejects_bad_scenario");
        let mut scenario = minimal_scenario();
        scenario.id = String::new(); // invalid
        let result = ScenarioRunner::run(&scenario);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ScenarioRunnerError::Validation { .. }
        ));
        crate::test_complete!("validation_rejects_bad_scenario");
    }

    #[test]
    fn unknown_oracle_rejected() {
        init_test("unknown_oracle_rejected");
        let mut scenario = minimal_scenario();
        scenario.oracles = vec!["nonexistent_oracle".to_string()];
        let result = ScenarioRunner::run(&scenario);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ScenarioRunnerError::UnknownOracle(_)
        ));
        crate::test_complete!("unknown_oracle_rejected");
    }

    #[test]
    fn oracle_filtering_works() {
        init_test("oracle_filtering_works");
        let mut scenario = minimal_scenario();
        scenario.oracles = vec!["task_leak".to_string(), "obligation_leak".to_string()];
        let result = ScenarioRunner::run(&scenario).unwrap();
        assert_eq!(result.oracle_report.checked.len(), 2);
        assert!(
            result
                .oracle_report
                .checked
                .contains(&"task_leak".to_string())
        );
        assert!(
            result
                .oracle_report
                .checked
                .contains(&"obligation_leak".to_string())
        );
        crate::test_complete!("oracle_filtering_works");
    }

    #[test]
    fn oracle_all_checks_everything() {
        init_test("oracle_all_checks_everything");
        let scenario = minimal_scenario();
        let result = ScenarioRunner::run(&scenario).unwrap();
        // "all" should check every oracle
        assert_eq!(
            result.oracle_report.checked.len(),
            ALL_ORACLE_INVARIANTS.len()
        );
        crate::test_complete!("oracle_all_checks_everything");
    }

    #[test]
    fn replay_determinism() {
        init_test("replay_determinism");
        let scenario = minimal_scenario();
        let result = ScenarioRunner::validate_replay(&scenario).unwrap();
        assert!(result.passed());
        crate::test_complete!("replay_determinism");
    }

    #[test]
    fn explore_seeds_basic() {
        init_test("explore_seeds_basic");
        let scenario = minimal_scenario();
        let result = ScenarioRunner::explore_seeds(&scenario, 0, 5).unwrap();
        assert_eq!(result.seeds_explored, 5);
        assert_eq!(result.passed, 5);
        assert_eq!(result.failed, 0);
        assert!(result.all_passed());
        assert!(result.unique_fingerprints >= 1);
        crate::test_complete!("explore_seeds_basic");
    }

    #[test]
    fn explore_seeds_reports_each_run() {
        init_test("explore_seeds_reports_each_run");
        let scenario = minimal_scenario();
        let result = ScenarioRunner::explore_seeds(&scenario, 100, 3).unwrap();
        assert_eq!(result.runs.len(), 3);
        assert_eq!(result.runs[0].seed, 100);
        assert_eq!(result.runs[1].seed, 101);
        assert_eq!(result.runs[2].seed, 102);
        crate::test_complete!("explore_seeds_reports_each_run");
    }

    #[test]
    fn result_to_json_roundtrip() {
        init_test("result_to_json_roundtrip");
        let scenario = minimal_scenario();
        let result = ScenarioRunner::run(&scenario).unwrap();
        let json = result.to_json();
        assert_eq!(json["scenario_id"], "test-minimal");
        assert_eq!(json["seed"], 42);
        assert!(json["passed"].as_bool().unwrap());
        assert!(json["certificate"]["event_hash"].is_u64());
        crate::test_complete!("result_to_json_roundtrip");
    }

    #[test]
    fn exploration_to_json() {
        init_test("exploration_to_json");
        let scenario = minimal_scenario();
        let result = ScenarioRunner::explore_seeds(&scenario, 0, 2).unwrap();
        let json = result.to_json();
        assert_eq!(json["seeds_explored"], 2);
        assert!(json["runs"].is_array());
        assert_eq!(json["runs"].as_array().unwrap().len(), 2);
        crate::test_complete!("exploration_to_json");
    }

    #[test]
    fn replay_trace_available_when_enabled() {
        init_test("replay_trace_available_when_enabled");
        let mut scenario = minimal_scenario();
        scenario.lab.replay_recording = true;
        let result = ScenarioRunner::run(&scenario).unwrap();
        // ScenarioRunner always enables replay recording
        assert!(result.replay_trace.is_some());
        crate::test_complete!("replay_trace_available_when_enabled");
    }

    #[test]
    fn certificates_stable_across_runs() {
        init_test("certificates_stable_across_runs");
        let scenario = minimal_scenario();
        let r1 = ScenarioRunner::run(&scenario).unwrap();
        let r2 = ScenarioRunner::run(&scenario).unwrap();
        assert_eq!(r1.certificate, r2.certificate);
        crate::test_complete!("certificates_stable_across_runs");
    }

    #[test]
    fn different_seeds_may_differ() {
        init_test("different_seeds_may_differ");
        let scenario = minimal_scenario();
        let r1 = ScenarioRunner::run_with_seed(&scenario, Some(1)).unwrap();
        let r2 = ScenarioRunner::run_with_seed(&scenario, Some(2)).unwrap();
        // Seeds 1 and 2 should both pass (empty scenario)
        assert!(r1.passed());
        assert!(r2.passed());
        // They may or may not have the same fingerprint (empty scenario probably same)
        crate::test_complete!("different_seeds_may_differ");
    }

    #[test]
    fn chaos_scenario_runs() {
        init_test("chaos_scenario_runs");
        let mut scenario = minimal_scenario();
        scenario.chaos = ChaosSection::Light;
        let result = ScenarioRunner::run(&scenario).unwrap();
        // Light chaos with no tasks should still pass
        assert!(result.passed());
        crate::test_complete!("chaos_scenario_runs");
    }

    #[test]
    fn fault_args_summary_formatting() {
        init_test("fault_args_summary_formatting");
        let mut args = BTreeMap::new();
        args.insert("from".to_string(), serde_json::json!("alice"));
        args.insert("to".to_string(), serde_json::json!("bob"));
        let summary = ScenarioRunner::fault_args_summary(&args);
        assert!(summary.contains("from=alice"));
        assert!(summary.contains("to=bob"));
        crate::test_complete!("fault_args_summary_formatting");
    }

    #[test]
    fn error_display_validation() {
        init_test("error_display_validation");
        let err = ScenarioRunnerError::Validation {
            scenario_id: "invalid-smoke".into(),
            errors: vec![ValidationError {
                field: "id".into(),
                message: "empty".into(),
            }],
        };
        let msg = err.to_string();
        assert!(msg.contains("validation failed"));
        assert!(msg.contains("invalid-smoke"));
        assert!(msg.contains("1 issue(s)"));
        assert!(msg.contains("id"));
        crate::test_complete!("error_display_validation");
    }

    #[test]
    fn error_display_unknown_oracle() {
        init_test("error_display_unknown_oracle");
        let err = ScenarioRunnerError::UnknownOracle("bad_oracle".into());
        assert!(err.to_string().contains("bad_oracle"));
        crate::test_complete!("error_display_unknown_oracle");
    }

    #[test]
    fn error_display_divergence() {
        init_test("error_display_divergence");
        let err = ScenarioRunnerError::ReplayDivergence {
            seed: 42,
            first: TraceCertificateSnapshot {
                event_hash: 1,
                schedule_hash: 2,
                steps: 100,
                trace_fingerprint: 3,
            },
            second: TraceCertificateSnapshot {
                event_hash: 4,
                schedule_hash: 5,
                steps: 100,
                trace_fingerprint: 6,
            },
        };
        let msg = err.to_string();
        assert!(msg.contains("seed 42"));
        assert!(msg.contains("divergence"));
        crate::test_complete!("error_display_divergence");
    }

    // ── derive-trait coverage (wave 73) ──────────────────────────────────

    #[test]
    fn trace_certificate_snapshot_debug_clone_copy_eq() {
        let cert = TraceCertificateSnapshot {
            event_hash: 111,
            schedule_hash: 222,
            steps: 333,
            trace_fingerprint: 444,
        };
        let cert2 = cert; // Copy
        let cert3 = cert;
        assert_eq!(cert, cert2);
        assert_eq!(cert2, cert3);
        let dbg = format!("{cert:?}");
        assert!(dbg.contains("TraceCertificateSnapshot"));
        assert!(dbg.contains("111"));
    }

    #[test]
    fn exploration_run_summary_debug_clone() {
        let s = ExplorationRunSummary {
            seed: 42,
            passed: true,
            steps: 100,
            fingerprint: 999,
            failures: vec![],
        };
        let s2 = s;
        assert_eq!(s2.seed, 42);
        assert!(s2.passed);
        assert_eq!(s2.steps, 100);
        assert_eq!(s2.fingerprint, 999);
        assert!(s2.failures.is_empty());
        let dbg = format!("{s2:?}");
        assert!(dbg.contains("ExplorationRunSummary"));
    }

    #[test]
    fn scenario_exploration_result_debug_clone() {
        let r = ScenarioExplorationResult {
            scenario_id: "test-explore".to_string(),
            seeds_explored: 10,
            passed: 8,
            failed: 2,
            unique_fingerprints: 3,
            runs: vec![ExplorationRunSummary {
                seed: 0,
                passed: true,
                steps: 50,
                fingerprint: 1,
                failures: vec![],
            }],
            first_failure_seed: Some(5),
        };
        let r2 = r;
        assert_eq!(r2.scenario_id, "test-explore");
        assert_eq!(r2.seeds_explored, 10);
        assert_eq!(r2.first_failure_seed, Some(5));
        assert_eq!(r2.runs.len(), 1);
        let dbg = format!("{r2:?}");
        assert!(dbg.contains("ScenarioExplorationResult"));
    }
}