asupersync 0.3.1

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
//! FrankenLab scenario format (bd-1hu19.1).
//!
//! A scenario file describes a deterministic test execution:
//! participants, fault schedule, assertions, seed, and virtual time
//! configuration.  The canonical on-disk format is YAML, but JSON and
//! TOML roundtrip cleanly via serde.
//!
//! # Format overview
//!
//! ```yaml
//! schema_version: 1
//! id: smoke-sendpermit-ack
//! description: Happy-path SendPermit/Ack under light chaos
//!
//! lab:
//!   seed: 42
//!   worker_count: 2
//!   trace_capacity: 8192
//!   max_steps: 100000
//!   panic_on_obligation_leak: true
//!   panic_on_futurelock: true
//!   futurelock_max_idle_steps: 10000
//!
//! chaos:
//!   preset: light           # off | light | heavy | custom
//!
//! network:
//!   preset: lan             # ideal | local | lan | wan | satellite | congested | lossy
//!
//! faults:
//!   - at_ms: 100
//!     action: partition
//!     args: { from: alice, to: bob }
//!   - at_ms: 500
//!     action: heal
//!     args: { from: alice, to: bob }
//!
//! participants:
//!   - name: alice
//!     role: sender
//!   - name: bob
//!     role: receiver
//!
//! oracles:
//!   - all
//!
//! cancellation:
//!   strategy: random_sample
//!   count: 100
//! ```
//!
//! # Composability
//!
//! Scenarios may include other scenarios via `include`:
//!
//! ```yaml
//! include:
//!   - path: base_config.yaml
//! ```
//!
//! Included fields are merged with the current file; the current file
//! wins on conflict.
//!
//! # Determinism
//!
//! All randomness is seeded via `lab.seed`.  Given the same YAML + the
//! same runtime binary, execution is bit-identical.

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

// ---------------------------------------------------------------------------
// Top-level scenario
// ---------------------------------------------------------------------------

/// Current scenario schema version.
pub const SCENARIO_SCHEMA_VERSION: u32 = 1;

/// A complete FrankenLab test scenario.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Scenario {
    /// Schema version (must be 1).
    #[serde(default = "default_schema_version")]
    pub schema_version: u32,

    /// Stable, unique scenario identifier (e.g. `"smoke-sendpermit-ack"`).
    pub id: String,

    /// Human-readable description.
    #[serde(default)]
    pub description: String,

    /// Lab runtime configuration.
    #[serde(default)]
    pub lab: LabSection,

    /// Chaos injection configuration.
    #[serde(default)]
    pub chaos: ChaosSection,

    /// Network simulation configuration.
    #[serde(default)]
    pub network: NetworkSection,

    /// Timed fault injection events.
    #[serde(default)]
    pub faults: Vec<FaultEvent>,

    /// Named participants (actors/tasks).
    #[serde(default)]
    pub participants: Vec<Participant>,

    /// Oracle names to enable.  `["all"]` enables every oracle.
    #[serde(default = "default_oracles")]
    pub oracles: Vec<String>,

    /// Cancellation injection strategy.
    #[serde(default)]
    pub cancellation: Option<CancellationSection>,

    /// Optional includes (for composability).
    #[serde(default)]
    pub include: Vec<IncludeRef>,

    /// Arbitrary key-value metadata (git sha, author, tags).
    #[serde(default)]
    pub metadata: BTreeMap<String, String>,
}

fn default_schema_version() -> u32 {
    SCENARIO_SCHEMA_VERSION
}

fn default_oracles() -> Vec<String> {
    vec!["all".to_string()]
}

// ---------------------------------------------------------------------------
// Lab section
// ---------------------------------------------------------------------------

/// Lab runtime knobs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LabSection {
    /// PRNG seed for deterministic scheduling.
    #[serde(default = "default_seed")]
    pub seed: u64,

    /// Optional separate entropy seed (defaults to `seed`).
    pub entropy_seed: Option<u64>,

    /// Number of virtual workers.
    #[serde(default = "default_worker_count")]
    pub worker_count: usize,

    /// Trace event buffer capacity.
    #[serde(default = "default_trace_capacity")]
    pub trace_capacity: usize,

    /// Maximum scheduler steps before forced termination.
    #[serde(default = "default_max_steps")]
    pub max_steps: Option<u64>,

    /// Panic on obligation leak.
    #[serde(default = "default_true")]
    pub panic_on_obligation_leak: bool,

    /// Panic on futurelock detection.
    #[serde(default = "default_true")]
    pub panic_on_futurelock: bool,

    /// Idle steps before futurelock fires.
    #[serde(default = "default_futurelock_max_idle")]
    pub futurelock_max_idle_steps: u64,

    /// Enable replay recording.
    #[serde(default)]
    pub replay_recording: bool,
}

impl Default for LabSection {
    fn default() -> Self {
        Self {
            seed: 42,
            entropy_seed: None,
            worker_count: 1,
            trace_capacity: 4096,
            max_steps: Some(100_000),
            panic_on_obligation_leak: true,
            panic_on_futurelock: true,
            futurelock_max_idle_steps: 10_000,
            replay_recording: false,
        }
    }
}

fn default_seed() -> u64 {
    42
}
fn default_worker_count() -> usize {
    1
}
fn default_trace_capacity() -> usize {
    4096
}
#[allow(clippy::unnecessary_wraps)]
fn default_max_steps() -> Option<u64> {
    Some(100_000)
}
fn default_true() -> bool {
    true
}
fn default_futurelock_max_idle() -> u64 {
    10_000
}

// ---------------------------------------------------------------------------
// Chaos section
// ---------------------------------------------------------------------------

/// Chaos injection configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(tag = "preset", rename_all = "snake_case")]
pub enum ChaosSection {
    /// Chaos disabled.
    #[default]
    Off,
    /// CI-friendly defaults (1% cancel, 5% delay, 2% I/O error).
    Light,
    /// Thorough testing (10% cancel, 20% delay, 15% I/O error).
    Heavy,
    /// Fully specified probabilities.
    Custom {
        /// Cancellation injection probability (0.0-1.0).
        #[serde(default)]
        cancel_probability: f64,
        /// Delay injection probability (0.0-1.0).
        #[serde(default)]
        delay_probability: f64,
        /// Minimum injected delay (milliseconds).
        #[serde(default)]
        delay_min_ms: u64,
        /// Maximum injected delay (milliseconds).
        #[serde(default = "default_delay_max_ms")]
        delay_max_ms: u64,
        /// I/O error injection probability (0.0-1.0).
        #[serde(default)]
        io_error_probability: f64,
        /// Wakeup storm probability (0.0-1.0).
        #[serde(default)]
        wakeup_storm_probability: f64,
        /// Budget exhaustion probability (0.0-1.0).
        #[serde(default)]
        budget_exhaustion_probability: f64,
    },
}

fn default_delay_max_ms() -> u64 {
    10
}

// ---------------------------------------------------------------------------
// Network section
// ---------------------------------------------------------------------------

/// Network simulation configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkSection {
    /// Preset network conditions.
    #[serde(default = "default_network_preset")]
    pub preset: NetworkPreset,

    /// Per-link overrides (key = "alice->bob").
    #[serde(default)]
    pub links: BTreeMap<String, LinkConditions>,
}

impl Default for NetworkSection {
    fn default() -> Self {
        Self {
            preset: NetworkPreset::Ideal,
            links: BTreeMap::new(),
        }
    }
}

fn default_network_preset() -> NetworkPreset {
    NetworkPreset::Ideal
}

/// Named network condition presets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NetworkPreset {
    /// No latency, loss, or corruption.
    Ideal,
    /// ~1ms latency.
    Local,
    /// 1-5ms latency, 0.01% loss.
    Lan,
    /// 20-100ms latency, 0.1% loss.
    Wan,
    /// ~600ms latency, 1% loss.
    Satellite,
    /// ~100ms latency with congestion effects.
    Congested,
    /// 10% packet loss.
    Lossy,
}

/// Per-link network condition overrides.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinkConditions {
    /// Latency model.
    #[serde(default)]
    pub latency: Option<LatencySpec>,
    /// Packet loss probability (0.0-1.0).
    #[serde(default)]
    pub packet_loss: Option<f64>,
    /// Packet corruption probability (0.0-1.0).
    #[serde(default)]
    pub packet_corrupt: Option<f64>,
    /// Packet duplication probability (0.0-1.0).
    #[serde(default)]
    pub packet_duplicate: Option<f64>,
    /// Packet reordering probability (0.0-1.0).
    #[serde(default)]
    pub packet_reorder: Option<f64>,
    /// Bandwidth limit (bytes/second).
    #[serde(default)]
    pub bandwidth: Option<u64>,
}

/// Latency model specification.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "model", rename_all = "snake_case")]
pub enum LatencySpec {
    /// Fixed latency.
    Fixed {
        /// Latency in milliseconds.
        ms: u64,
    },
    /// Uniform distribution \[min_ms, max_ms\].
    Uniform {
        /// Minimum latency in milliseconds.
        min_ms: u64,
        /// Maximum latency in milliseconds.
        max_ms: u64,
    },
    /// Normal distribution (mean +/- stddev), clamped to \[0, inf).
    Normal {
        /// Mean latency in milliseconds.
        mean_ms: u64,
        /// Standard deviation in milliseconds.
        stddev_ms: u64,
    },
}

// ---------------------------------------------------------------------------
// Fault events
// ---------------------------------------------------------------------------

/// A timed fault injection event.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FaultEvent {
    /// Virtual time (milliseconds) at which the fault fires.
    pub at_ms: u64,

    /// The fault action.
    pub action: FaultAction,

    /// Action arguments.
    #[serde(default)]
    pub args: BTreeMap<String, serde_json::Value>,
}

/// Fault action types.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FaultAction {
    /// Network partition between two participants.
    Partition,
    /// Heal a previously applied partition.
    Heal,
    /// Crash a host (stop processing).
    HostCrash,
    /// Restart a previously crashed host.
    HostRestart,
    /// Inject clock skew on a participant.
    ClockSkew,
    /// Reset clock skew to zero on a participant.
    ClockReset,
}

// ---------------------------------------------------------------------------
// Participants
// ---------------------------------------------------------------------------

/// A named participant in the scenario.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Participant {
    /// Unique name within the scenario.
    pub name: String,

    /// Role hint (free-form: "sender", "receiver", "coordinator", ...).
    #[serde(default)]
    pub role: String,

    /// Arbitrary properties for the participant.
    #[serde(default)]
    pub properties: BTreeMap<String, serde_json::Value>,
}

// ---------------------------------------------------------------------------
// Cancellation injection
// ---------------------------------------------------------------------------

/// Cancellation injection configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CancellationSection {
    /// The injection strategy.
    pub strategy: CancellationStrategy,

    /// Parameter for strategies that take a count.
    #[serde(default)]
    pub count: Option<usize>,

    /// Probability parameter (for `probabilistic` strategy).
    #[serde(default)]
    pub probability: Option<f64>,
}

/// Cancellation injection strategies.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CancellationStrategy {
    /// No cancellation injection (recording only).
    Never,
    /// Test all await points (N+1 runs).
    AllPoints,
    /// Random sample of await points.
    RandomSample,
    /// First N await points.
    FirstN,
    /// Last N await points.
    LastN,
    /// Every Nth await point.
    EveryNth,
    /// Probabilistic per-point injection.
    Probabilistic,
}

// ---------------------------------------------------------------------------
// Include
// ---------------------------------------------------------------------------

/// Reference to an included scenario file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IncludeRef {
    /// Relative path to the included YAML.
    pub path: String,
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

/// Validation error for a scenario file.
#[derive(Debug, Clone)]
pub struct ValidationError {
    /// Path within the scenario (e.g. "lab.seed").
    pub field: String,
    /// What is wrong.
    pub message: String,
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.field, self.message)
    }
}

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

impl Scenario {
    /// Validate the scenario for structural correctness.
    ///
    /// Returns an empty `Vec` if valid.
    #[must_use]
    pub fn validate(&self) -> Vec<ValidationError> {
        let mut errors = Vec::new();
        self.validate_header(&mut errors);
        self.validate_chaos(&mut errors);
        self.validate_network(&mut errors);
        self.validate_faults(&mut errors);
        self.validate_participants(&mut errors);
        self.validate_cancellation(&mut errors);
        errors
    }

    fn validate_header(&self, errors: &mut Vec<ValidationError>) {
        if self.schema_version != SCENARIO_SCHEMA_VERSION {
            errors.push(ValidationError {
                field: "schema_version".into(),
                message: format!(
                    "unsupported version {}, expected {SCENARIO_SCHEMA_VERSION}",
                    self.schema_version
                ),
            });
        }
        if self.id.is_empty() {
            errors.push(ValidationError {
                field: "id".into(),
                message: "scenario id must not be empty".into(),
            });
        }
        if self.lab.worker_count == 0 {
            errors.push(ValidationError {
                field: "lab.worker_count".into(),
                message: "worker_count must be >= 1".into(),
            });
        }
        if self.lab.trace_capacity == 0 {
            errors.push(ValidationError {
                field: "lab.trace_capacity".into(),
                message: "trace_capacity must be > 0".into(),
            });
        }
    }

    fn validate_chaos(&self, errors: &mut Vec<ValidationError>) {
        if let ChaosSection::Custom {
            cancel_probability,
            delay_probability,
            delay_min_ms,
            delay_max_ms,
            io_error_probability,
            wakeup_storm_probability,
            budget_exhaustion_probability,
        } = &self.chaos
        {
            for (name, val) in [
                ("chaos.cancel_probability", cancel_probability),
                ("chaos.delay_probability", delay_probability),
                ("chaos.io_error_probability", io_error_probability),
                ("chaos.wakeup_storm_probability", wakeup_storm_probability),
                (
                    "chaos.budget_exhaustion_probability",
                    budget_exhaustion_probability,
                ),
            ] {
                if !(0.0..=1.0).contains(val) {
                    errors.push(ValidationError {
                        field: name.into(),
                        message: format!("probability must be in [0.0, 1.0], got {val}"),
                    });
                }
            }
            if *delay_min_ms > *delay_max_ms {
                errors.push(ValidationError {
                    field: "chaos.delay_min_ms".into(),
                    message: format!(
                        "delay_min_ms ({delay_min_ms}) must be <= delay_max_ms ({delay_max_ms})"
                    ),
                });
            }
        }
    }

    fn validate_network(&self, errors: &mut Vec<ValidationError>) {
        for (key, link) in &self.network.links {
            let key_valid = key
                .split_once("->")
                .is_some_and(|(from, to)| !from.is_empty() && !to.is_empty() && !to.contains("->"));
            if !key_valid {
                errors.push(ValidationError {
                    field: format!("network.links.{key}"),
                    message: "link key must be in format \"from->to\"".into(),
                });
            }

            for (name, value) in [
                ("packet_loss", link.packet_loss),
                ("packet_corrupt", link.packet_corrupt),
                ("packet_duplicate", link.packet_duplicate),
                ("packet_reorder", link.packet_reorder),
            ] {
                if let Some(probability) = value {
                    if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
                        errors.push(ValidationError {
                            field: format!("network.links.{key}.{name}"),
                            message: format!(
                                "probability must be finite and in [0.0, 1.0], got {probability}"
                            ),
                        });
                    }
                }
            }

            if let Some(LatencySpec::Uniform { min_ms, max_ms }) = &link.latency {
                if min_ms > max_ms {
                    errors.push(ValidationError {
                        field: format!("network.links.{key}.latency"),
                        message: format!(
                            "uniform latency min_ms ({min_ms}) must be <= max_ms ({max_ms})"
                        ),
                    });
                }
            }
        }
    }

    fn validate_faults(&self, errors: &mut Vec<ValidationError>) {
        for window in self.faults.windows(2) {
            if window[1].at_ms < window[0].at_ms {
                errors.push(ValidationError {
                    field: "faults".into(),
                    message: format!(
                        "fault events must be ordered by at_ms: {} comes before {}",
                        window[0].at_ms, window[1].at_ms
                    ),
                });
            }
        }
    }

    fn validate_participants(&self, errors: &mut Vec<ValidationError>) {
        let mut seen_names = std::collections::HashSet::new();
        for p in &self.participants {
            if !seen_names.insert(&p.name) {
                errors.push(ValidationError {
                    field: format!("participants.{}", p.name),
                    message: "duplicate participant name".into(),
                });
            }
        }
    }

    fn validate_cancellation(&self, errors: &mut Vec<ValidationError>) {
        let Some(ref cancel) = self.cancellation else {
            return;
        };
        match cancel.strategy {
            CancellationStrategy::RandomSample
            | CancellationStrategy::FirstN
            | CancellationStrategy::LastN
            | CancellationStrategy::EveryNth => {
                if cancel.count.is_none() {
                    errors.push(ValidationError {
                        field: "cancellation.count".into(),
                        message: format!(
                            "strategy {:?} requires a count parameter",
                            cancel.strategy
                        ),
                    });
                } else if cancel.count == Some(0) {
                    errors.push(ValidationError {
                        field: "cancellation.count".into(),
                        message: "count must be >= 1".into(),
                    });
                }
            }
            CancellationStrategy::Probabilistic => {
                if let Some(p) = cancel.probability {
                    if !p.is_finite() || !(0.0..=1.0).contains(&p) {
                        errors.push(ValidationError {
                            field: "cancellation.probability".into(),
                            message: format!("probability must be in [0.0, 1.0], got {p}"),
                        });
                    }
                } else {
                    errors.push(ValidationError {
                        field: "cancellation.probability".into(),
                        message: "strategy probabilistic requires a probability parameter".into(),
                    });
                }
            }
            CancellationStrategy::Never | CancellationStrategy::AllPoints => {}
        }
    }

    /// Convert this scenario to a [`super::config::LabConfig`].
    #[must_use]
    pub fn to_lab_config(&self) -> super::config::LabConfig {
        let mut config = super::config::LabConfig::new(self.lab.seed)
            .worker_count(self.lab.worker_count)
            .trace_capacity(self.lab.trace_capacity)
            .panic_on_leak(self.lab.panic_on_obligation_leak)
            .panic_on_futurelock(self.lab.panic_on_futurelock)
            .futurelock_max_idle_steps(self.lab.futurelock_max_idle_steps);

        if let Some(entropy) = self.lab.entropy_seed {
            config = config.entropy_seed(entropy);
        }

        if let Some(max) = self.lab.max_steps {
            config = config.max_steps(max);
        } else {
            config = config.no_step_limit();
        }

        // Apply chaos preset
        config = match &self.chaos {
            ChaosSection::Off => config,
            ChaosSection::Light => config.with_light_chaos(),
            ChaosSection::Heavy => config.with_heavy_chaos(),
            ChaosSection::Custom {
                cancel_probability,
                delay_probability,
                delay_min_ms,
                delay_max_ms,
                io_error_probability,
                wakeup_storm_probability,
                budget_exhaustion_probability,
            } => {
                use std::time::Duration;
                let chaos_seed = self.lab.entropy_seed.unwrap_or(self.lab.seed);
                let chaos = crate::lab::chaos::ChaosConfig::new(chaos_seed)
                    .with_cancel_probability(*cancel_probability)
                    .with_delay_probability(*delay_probability)
                    .with_delay_range(
                        Duration::from_millis(*delay_min_ms)..Duration::from_millis(*delay_max_ms),
                    )
                    .with_io_error_probability(*io_error_probability)
                    .with_wakeup_storm_probability(*wakeup_storm_probability)
                    .with_budget_exhaust_probability(*budget_exhaustion_probability);
                config.with_chaos(chaos)
            }
        };

        if self.lab.replay_recording {
            config = config.with_default_replay_recording();
        }

        config
    }

    /// Parse a scenario from a JSON string.
    ///
    /// # Errors
    ///
    /// Returns a `serde_json::Error` if the JSON is malformed.
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }

    /// Serialize this scenario to pretty-printed JSON.
    ///
    /// # Errors
    ///
    /// Returns a `serde_json::Error` if serialization fails.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    fn minimal_json() -> &'static str {
        r#"{
            "id": "test-scenario",
            "description": "minimal test"
        }"#
    }

    #[test]
    fn parse_minimal_scenario() {
        let s: Scenario = serde_json::from_str(minimal_json()).unwrap();
        assert_eq!(s.id, "test-scenario");
        assert_eq!(s.schema_version, 1);
        assert_eq!(s.lab.seed, 42);
        assert_eq!(s.lab.worker_count, 1);
        assert!(s.faults.is_empty());
        assert!(s.participants.is_empty());
        assert_eq!(s.oracles, vec!["all"]);
    }

    #[test]
    fn validate_minimal_scenario() {
        let s: Scenario = serde_json::from_str(minimal_json()).unwrap();
        let errors = s.validate();
        assert!(errors.is_empty(), "unexpected errors: {errors:?}");
    }

    #[test]
    fn validate_empty_id_rejected() {
        let json = r#"{"id": "", "description": "bad"}"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let errors = s.validate();
        assert!(errors.iter().any(|e| e.field == "id"));
    }

    #[test]
    fn validate_bad_schema_version() {
        let json = r#"{"schema_version": 99, "id": "x"}"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let errors = s.validate();
        assert!(errors.iter().any(|e| e.field == "schema_version"));
    }

    #[test]
    fn parse_chaos_preset_light() {
        let json = r#"{"id": "x", "chaos": {"preset": "light"}}"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        assert!(matches!(s.chaos, ChaosSection::Light));
    }

    #[test]
    fn parse_chaos_custom() {
        let json = r#"{
            "id": "x",
            "chaos": {
                "preset": "custom",
                "cancel_probability": 0.05,
                "delay_probability": 0.3,
                "io_error_probability": 0.1
            }
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        match s.chaos {
            ChaosSection::Custom {
                cancel_probability,
                delay_probability,
                io_error_probability,
                ..
            } => {
                assert!((cancel_probability - 0.05).abs() < f64::EPSILON);
                assert!((delay_probability - 0.3).abs() < f64::EPSILON);
                assert!((io_error_probability - 0.1).abs() < f64::EPSILON);
            }
            other => panic!("expected Custom, got {other:?}"),
        }
    }

    #[test]
    fn validate_chaos_bad_probability() {
        let json = r#"{
            "id": "x",
            "chaos": {"preset": "custom", "cancel_probability": 1.5}
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let errors = s.validate();
        assert!(errors.iter().any(|e| e.field == "chaos.cancel_probability"));
    }

    #[test]
    fn parse_network_preset_wan() {
        let json = r#"{"id": "x", "network": {"preset": "wan"}}"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        assert_eq!(s.network.preset, NetworkPreset::Wan);
    }

    #[test]
    fn parse_network_link_override() {
        let json = r#"{
            "id": "x",
            "network": {
                "preset": "lan",
                "links": {
                    "alice->bob": { "packet_loss": 0.5 }
                }
            }
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let link = s.network.links.get("alice->bob").unwrap();
        assert!((link.packet_loss.unwrap() - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn validate_bad_link_key() {
        let json = r#"{
            "id": "x",
            "network": {"links": {"alice_bob": {}}}
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let errors = s.validate();
        assert!(errors.iter().any(|e| e.field.contains("network.links")));
    }

    #[test]
    fn validate_link_probability_out_of_range() {
        let json = r#"{
            "id": "x",
            "network": {
                "links": {
                    "alice->bob": { "packet_loss": 1.5 }
                }
            }
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let errors = s.validate();
        assert!(
            errors
                .iter()
                .any(|e| e.field == "network.links.alice->bob.packet_loss")
        );
    }

    #[test]
    fn validate_uniform_latency_min_max_order() {
        let json = r#"{
            "id": "x",
            "network": {
                "links": {
                    "alice->bob": {
                        "latency": { "model": "uniform", "min_ms": 20, "max_ms": 10 }
                    }
                }
            }
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let errors = s.validate();
        assert!(
            errors
                .iter()
                .any(|e| e.field == "network.links.alice->bob.latency")
        );
    }

    #[test]
    fn parse_fault_events() {
        let json = r#"{
            "id": "x",
            "faults": [
                {"at_ms": 100, "action": "partition", "args": {"from": "a", "to": "b"}},
                {"at_ms": 500, "action": "heal", "args": {"from": "a", "to": "b"}}
            ]
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        assert_eq!(s.faults.len(), 2);
        assert_eq!(s.faults[0].at_ms, 100);
        assert!(matches!(s.faults[0].action, FaultAction::Partition));
        assert_eq!(s.faults[1].at_ms, 500);
        assert!(matches!(s.faults[1].action, FaultAction::Heal));
    }

    #[test]
    fn validate_unordered_faults() {
        let json = r#"{
            "id": "x",
            "faults": [
                {"at_ms": 500, "action": "partition"},
                {"at_ms": 100, "action": "heal"}
            ]
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let errors = s.validate();
        assert!(errors.iter().any(|e| e.field == "faults"));
    }

    #[test]
    fn parse_participants() {
        let json = r#"{
            "id": "x",
            "participants": [
                {"name": "alice", "role": "sender"},
                {"name": "bob", "role": "receiver"}
            ]
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        assert_eq!(s.participants.len(), 2);
        assert_eq!(s.participants[0].name, "alice");
        assert_eq!(s.participants[1].role, "receiver");
    }

    #[test]
    fn validate_duplicate_participant() {
        let json = r#"{
            "id": "x",
            "participants": [
                {"name": "alice"},
                {"name": "alice"}
            ]
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let errors = s.validate();
        assert!(errors.iter().any(|e| e.message.contains("duplicate")));
    }

    #[test]
    fn parse_cancellation_strategy() {
        let json = r#"{
            "id": "x",
            "cancellation": {
                "strategy": "random_sample",
                "count": 100
            }
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let cancel = s.cancellation.as_ref().unwrap();
        assert!(matches!(
            cancel.strategy,
            CancellationStrategy::RandomSample
        ));
        assert_eq!(cancel.count, Some(100));
    }

    #[test]
    fn validate_missing_count() {
        let json = r#"{
            "id": "x",
            "cancellation": {"strategy": "random_sample"}
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let errors = s.validate();
        assert!(errors.iter().any(|e| e.field == "cancellation.count"));
    }

    #[test]
    fn to_lab_config_defaults() {
        let s: Scenario = serde_json::from_str(minimal_json()).unwrap();
        let config = s.to_lab_config();
        assert_eq!(config.seed, 42);
        assert_eq!(config.worker_count, 1);
        assert_eq!(config.trace_capacity, 4096);
        assert!(config.panic_on_obligation_leak);
    }

    #[test]
    fn to_lab_config_chaos_light() {
        let json = r#"{"id": "x", "chaos": {"preset": "light"}}"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let config = s.to_lab_config();
        assert!(config.has_chaos());
    }

    #[test]
    fn to_lab_config_custom_seed() {
        let json = r#"{"id": "x", "lab": {"seed": 12345, "worker_count": 4}}"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        let config = s.to_lab_config();
        assert_eq!(config.seed, 12345);
        assert_eq!(config.worker_count, 4);
    }

    #[test]
    fn json_roundtrip() {
        let json = r#"{
            "id": "roundtrip-test",
            "description": "full roundtrip",
            "lab": {"seed": 99, "worker_count": 2},
            "chaos": {"preset": "heavy"},
            "network": {"preset": "wan"},
            "participants": [{"name": "alice", "role": "sender"}],
            "faults": [{"at_ms": 100, "action": "partition"}]
        }"#;
        let s1: Scenario = serde_json::from_str(json).unwrap();
        let serialized = s1.to_json().unwrap();
        let s2: Scenario = Scenario::from_json(&serialized).unwrap();
        assert_eq!(s1.id, s2.id);
        assert_eq!(s1.lab.seed, s2.lab.seed);
        assert_eq!(s1.participants.len(), s2.participants.len());
        assert_eq!(s1.faults.len(), s2.faults.len());
    }

    #[test]
    fn parse_metadata() {
        let json = r#"{
            "id": "x",
            "metadata": {"git_sha": "abc123", "author": "bot"}
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        assert_eq!(s.metadata.get("git_sha").unwrap(), "abc123");
    }

    #[test]
    fn parse_latency_models() {
        let json = r#"{
            "id": "x",
            "network": {
                "preset": "ideal",
                "links": {
                    "a->b": {"latency": {"model": "fixed", "ms": 5}},
                    "b->c": {"latency": {"model": "uniform", "min_ms": 1, "max_ms": 10}},
                    "c->d": {"latency": {"model": "normal", "mean_ms": 50, "stddev_ms": 10}}
                }
            }
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        assert_eq!(s.network.links.len(), 3);
        let ab = s.network.links.get("a->b").unwrap();
        assert!(matches!(ab.latency, Some(LatencySpec::Fixed { ms: 5 })));
    }

    #[test]
    fn parse_include() {
        let json = r#"{
            "id": "x",
            "include": [{"path": "base.yaml"}]
        }"#;
        let s: Scenario = serde_json::from_str(json).unwrap();
        assert_eq!(s.include.len(), 1);
        assert_eq!(s.include[0].path, "base.yaml");
    }

    #[test]
    fn network_preset_debug_clone_copy_eq() {
        let p = NetworkPreset::Wan;
        let dbg = format!("{p:?}");
        assert!(dbg.contains("Wan"));

        let p2 = p;
        assert_eq!(p, p2);

        let p3 = p;
        assert_eq!(p, p3);

        assert_ne!(NetworkPreset::Ideal, NetworkPreset::Lossy);
    }

    #[test]
    fn chaos_section_debug_clone_default() {
        let c = ChaosSection::default();
        let dbg = format!("{c:?}");
        assert!(dbg.contains("Off"));

        let c2 = c;
        let dbg2 = format!("{c2:?}");
        assert_eq!(dbg, dbg2);
    }

    #[test]
    fn fault_action_debug_clone() {
        let a = FaultAction::Partition;
        let dbg = format!("{a:?}");
        assert!(dbg.contains("Partition"));

        let a2 = a;
        let dbg2 = format!("{a2:?}");
        assert_eq!(dbg, dbg2);
    }

    #[test]
    fn validation_error_debug_clone() {
        let e = ValidationError {
            field: "lab.seed".into(),
            message: "must be positive".into(),
        };
        let dbg = format!("{e:?}");
        assert!(dbg.contains("lab.seed"));

        let e2 = e;
        assert_eq!(e2.field, "lab.seed");
        assert_eq!(e2.message, "must be positive");
    }
}