simvar_harness 0.3.0

Simulator Harness package
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
//! Simulation configuration and result types.
//!
//! This module defines the core data structures used to configure simulation runs
//! and report their outcomes, including [`SimConfig`], [`SimProperties`],
//! [`SimRunProperties`], and [`SimResult`].

use std::{sync::LazyLock, time::Duration};

use switchy::random::{rng, simulator::seed};

use crate::{RUNS, formatting::TimeFormat as _};

/// Configuration for a simulation run.
///
/// Controls various aspects of the simulation environment including randomness,
/// failure rates, network properties, and timing.
#[derive(Debug, Clone, Copy)]
pub struct SimConfig {
    /// Random seed for reproducible simulations.
    pub seed: u64,
    /// Probability (0.0 to 1.0) that a component will fail.
    pub fail_rate: f64,
    /// Probability (0.0 to 1.0) that a failed component will be repaired.
    pub repair_rate: f64,
    /// Maximum number of TCP messages in flight.
    pub tcp_capacity: u64,
    /// Maximum number of UDP messages in flight.
    pub udp_capacity: u64,
    /// Whether to randomize the order of actor execution.
    pub enable_random_order: bool,
    /// Minimum simulated network latency.
    pub min_message_latency: Duration,
    /// Maximum simulated network latency.
    pub max_message_latency: Duration,
    /// How long the simulation should run (`Duration::MAX` for unlimited).
    pub duration: Duration,
    /// Duration of each simulation tick.
    pub tick_duration: Duration,
    /// Offset from Unix epoch for simulated time.
    #[cfg(feature = "time")]
    pub epoch_offset: u64,
    /// Time multiplier for simulation steps.
    #[cfg(feature = "time")]
    pub step_multiplier: u64,
}

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

impl SimConfig {
    /// Creates a new `SimConfig` with default values.
    ///
    /// Returns a configuration with reasonable defaults for testing.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            seed: 0,
            fail_rate: 0.0,
            repair_rate: 1.0,
            tcp_capacity: 64,
            udp_capacity: 64,
            enable_random_order: false,
            min_message_latency: Duration::from_millis(0),
            max_message_latency: Duration::from_secs(1),
            duration: Duration::MAX,
            tick_duration: Duration::from_millis(1),
            #[cfg(feature = "time")]
            epoch_offset: 0,
            #[cfg(feature = "time")]
            step_multiplier: 1,
        }
    }

    /// Creates a new `SimConfig` with randomized values.
    ///
    /// Uses the current RNG to generate configuration values suitable for
    /// testing. The `SIMULATOR_DURATION` environment variable can be used
    /// to override the duration.
    ///
    /// # Panics
    ///
    /// * If `SIMULATOR_DURATION` is set but cannot be parsed as a supported
    ///   duration format.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use simvar_harness::SimConfig;
    ///
    /// let config = SimConfig::from_rng();
    /// assert!(config.max_message_latency >= config.min_message_latency);
    /// ```
    #[must_use]
    pub fn from_rng() -> Self {
        static DURATION: LazyLock<Duration> = LazyLock::new(|| {
            std::env::var("SIMULATOR_DURATION")
                .ok()
                .map_or(Duration::MAX, |x| {
                    #[allow(clippy::option_if_let_else)]
                    if let Some(x) = x.strip_suffix("µs") {
                        Duration::from_micros(x.parse::<u64>().unwrap())
                    } else if let Some(x) = x.strip_suffix("ns") {
                        Duration::from_nanos(x.parse::<u64>().unwrap())
                    } else if let Some(x) = x.strip_suffix("ms") {
                        Duration::from_millis(x.parse::<u64>().unwrap())
                    } else if let Some(x) = x.strip_suffix("s") {
                        Duration::from_secs(x.parse::<u64>().unwrap())
                    } else {
                        Duration::from_millis(x.parse::<u64>().unwrap())
                    }
                })
        });

        let mut config = Self::new();
        config.seed = seed();

        let min_message_latency = rng().gen_range_dist(0..=1000, 1.0);

        let config = config
            .fail_rate(0.0)
            .repair_rate(1.0)
            .tcp_capacity(64)
            .udp_capacity(64)
            .enable_random_order(true)
            .min_message_latency(Duration::from_millis(min_message_latency))
            .max_message_latency(Duration::from_millis(
                rng().gen_range(min_message_latency..2000),
            ))
            .duration(*DURATION);

        #[cfg(feature = "time")]
        {
            config.epoch_offset = switchy::time::simulator::epoch_offset();
            config.step_multiplier = switchy::time::simulator::step_multiplier();
        }

        #[cfg(feature = "time")]
        let config = config.tick_duration(Duration::from_millis(
            switchy::time::simulator::step_multiplier(),
        ));

        *config
    }

    /// Sets the failure rate (0.0 to 1.0) and returns a mutable reference to self.
    #[must_use]
    pub const fn fail_rate(&mut self, fail_rate: f64) -> &mut Self {
        self.fail_rate = fail_rate;
        self
    }

    /// Sets the repair rate (0.0 to 1.0) and returns a mutable reference to self.
    #[must_use]
    pub const fn repair_rate(&mut self, repair_rate: f64) -> &mut Self {
        self.repair_rate = repair_rate;
        self
    }

    /// Sets the TCP capacity and returns a mutable reference to self.
    #[must_use]
    pub const fn tcp_capacity(&mut self, tcp_capacity: u64) -> &mut Self {
        self.tcp_capacity = tcp_capacity;
        self
    }

    /// Sets the UDP capacity and returns a mutable reference to self.
    #[must_use]
    pub const fn udp_capacity(&mut self, udp_capacity: u64) -> &mut Self {
        self.udp_capacity = udp_capacity;
        self
    }

    /// Sets whether to enable random actor execution order and returns a mutable reference to self.
    #[must_use]
    pub const fn enable_random_order(&mut self, enable_random_order: bool) -> &mut Self {
        self.enable_random_order = enable_random_order;
        self
    }

    /// Sets the minimum message latency and returns a mutable reference to self.
    #[must_use]
    pub const fn min_message_latency(&mut self, min_message_latency: Duration) -> &mut Self {
        self.min_message_latency = min_message_latency;
        self
    }

    /// Sets the maximum message latency and returns a mutable reference to self.
    #[must_use]
    pub const fn max_message_latency(&mut self, max_message_latency: Duration) -> &mut Self {
        self.max_message_latency = max_message_latency;
        self
    }

    /// Sets the simulation duration and returns a mutable reference to self.
    #[must_use]
    pub const fn duration(&mut self, duration: Duration) -> &mut Self {
        self.duration = duration;
        self
    }

    /// Sets the tick duration and returns a mutable reference to self.
    #[must_use]
    pub const fn tick_duration(&mut self, tick_duration: Duration) -> &mut Self {
        self.tick_duration = tick_duration;
        self
    }
}

/// Properties describing a simulation run.
///
/// Contains the configuration and metadata about a specific simulation run.
#[derive(Debug, Clone)]
pub struct SimProperties {
    /// Configuration used for this simulation run.
    pub config: SimConfig,
    /// Run number (1-indexed).
    pub run_number: u64,
    /// Worker thread ID, if running in parallel mode.
    pub thread_id: Option<u64>,
    /// Additional custom properties from the bootstrap.
    pub extra: Vec<(String, String)>,
}

/// Runtime metrics from a simulation run.
///
/// Captures timing and step count information after a simulation completes.
#[derive(Debug, Clone)]
pub struct SimRunProperties {
    /// Number of simulation steps executed.
    pub steps: u64,
    /// Real-world time elapsed in milliseconds.
    pub real_time_millis: u128,
    /// Simulated time elapsed in milliseconds.
    pub sim_time_millis: u128,
}

/// Result of a simulation run.
///
/// Indicates whether the simulation succeeded or failed, along with properties
/// and runtime metrics.
#[derive(Debug)]
pub enum SimResult {
    /// Simulation completed successfully.
    Success {
        /// Properties of the simulation run.
        props: SimProperties,
        /// Runtime metrics from the run.
        run: SimRunProperties,
    },
    /// Simulation failed with an error or panic.
    Fail {
        /// Properties of the simulation run.
        props: SimProperties,
        /// Runtime metrics from the run.
        run: SimRunProperties,
        /// Error message, if the failure was due to a returned error.
        error: Option<String>,
        /// Panic message, if the failure was due to a panic.
        panic: Option<String>,
    },
}

impl SimResult {
    /// Returns the simulation properties.
    #[must_use]
    pub const fn props(&self) -> &SimProperties {
        match self {
            Self::Success { props, .. } | Self::Fail { props, .. } => props,
        }
    }

    /// Returns the simulation configuration.
    #[must_use]
    pub const fn config(&self) -> &SimConfig {
        &self.props().config
    }

    /// Returns the runtime properties.
    #[must_use]
    pub const fn run(&self) -> &SimRunProperties {
        match self {
            Self::Success { run, .. } | Self::Fail { run, .. } => run,
        }
    }

    /// Returns `true` if the simulation succeeded.
    #[must_use]
    pub const fn is_success(&self) -> bool {
        matches!(self, Self::Success { .. })
    }
}

impl std::fmt::Display for SimResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let props = self.props();
        let config = &props.config;
        let run = self.run();

        let run_from_seed = if *RUNS == 1 && switchy::random::simulator::contains_fixed_seed() {
            String::new()
        } else {
            #[cfg(feature = "time")]
            let failed_epoch_offset = Some(config.epoch_offset);
            #[cfg(not(feature = "time"))]
            let failed_epoch_offset = None;

            let cmd = get_run_command(
                &[
                    "SIMULATOR_SEED",
                    "SIMULATOR_RUNS",
                    "SIMULATOR_DURATION",
                    "SIMULATOR_MAX_PARALLEL",
                ],
                config.seed,
                failed_epoch_offset,
            );
            format!("\n\nTo run again with this seed: `{cmd}`")
        };
        let run_from_start = if !switchy::random::simulator::contains_fixed_seed() && *RUNS > 1 {
            let cmd = get_run_command(
                &["SIMULATOR_SEED"],
                switchy::random::simulator::initial_seed(),
                None,
            );
            format!("\nTo run entire simulation again from the first run: `{cmd}`")
        } else {
            String::new()
        };

        let (error, panic) = match self {
            Self::Success { .. } => (String::new(), String::new()),
            Self::Fail { error, panic, .. } => (
                error
                    .as_ref()
                    .map_or_else(String::new, |x| format!("\n\nError:\n{x}")),
                panic
                    .as_ref()
                    .map_or_else(String::new, |x| format!("\n\nPanic:\n{x}")),
            ),
        };

        #[allow(clippy::cast_precision_loss)]
        f.write_fmt(format_args!(
            "\
            =========================== FINISH ===========================\n\
            Server simulator finished\n\n\
            {run_info}\n\
            steps={steps}\n\
            real_time_elapsed={real_time}\n\
            simulated_time_elapsed={simulated_time} ({simulated_time_x:.2}x)\n\n\
            successful={successful}\
            {error}{panic}{run_from_seed}{run_from_start}\n\
            ==============================================================\
            ",
            successful = self.is_success(),
            run_info = run_info(props),
            steps = run.steps,
            real_time = run.real_time_millis.into_formatted(),
            simulated_time = run.sim_time_millis.into_formatted(),
            simulated_time_x = run.sim_time_millis as f64 / run.real_time_millis as f64,
        ))
    }
}

/// Formats simulation properties as a human-readable string.
///
/// Used for logging and displaying simulation configuration details.
#[must_use]
pub fn run_info(props: &SimProperties) -> String {
    use std::fmt::Write as _;

    let config = &props.config;

    let mut extra_top = String::new();
    if let Some(thread_id) = props.thread_id {
        write!(extra_top, "\nthread_id={thread_id}").unwrap();
    }
    #[cfg(feature = "time")]
    write!(extra_top, "\nepoch_offset={}", config.epoch_offset).unwrap();
    #[cfg(feature = "time")]
    write!(extra_top, "\nstep_multiplier={}", config.step_multiplier).unwrap();

    let mut extra_str = String::new();
    for (k, v) in &props.extra {
        write!(extra_str, "\n{k}={v}").unwrap();
    }

    let duration = if config.duration == Duration::MAX {
        "forever".to_string()
    } else {
        config.duration.as_millis().to_string()
    };

    let run_number = props.run_number;
    let runs = *RUNS;
    let runs = if runs > 1 {
        format!("{run_number}/{runs}")
    } else {
        runs.to_string()
    };

    format!(
        "\
        seed={seed}\n\
        run={runs}{extra_top}\n\
        tick_duration={tick_duration}\n\
        fail_rate={fail_rate}\n\
        repair_rate={repair_rate}\n\
        tcp_capacity={tcp_capacity}\n\
        udp_capacity={udp_capacity}\n\
        enable_random_order={enable_random_order}\n\
        min_message_latency={min_message_latency}\n\
        max_message_latency={max_message_latency}\n\
        duration={duration}{extra_str}\
        ",
        seed = config.seed,
        tick_duration = config.tick_duration.as_millis(),
        fail_rate = config.fail_rate,
        repair_rate = config.repair_rate,
        tcp_capacity = config.tcp_capacity,
        udp_capacity = config.udp_capacity,
        enable_random_order = config.enable_random_order,
        min_message_latency = config.min_message_latency.as_millis(),
        max_message_latency = config.max_message_latency.as_millis(),
    )
}

fn get_cargoified_args() -> Vec<String> {
    let mut args = std::env::args().collect::<Vec<_>>();

    let Some(cmd) = args.first() else {
        return args;
    };

    let mut components = cmd.split('/');

    if matches!(components.next(), Some("target")) {
        let Some(profile) = components.next() else {
            return args;
        };
        let profile = profile.to_string();

        let Some(binary_name) = components.next() else {
            return args;
        };
        let binary_name = binary_name.to_string();

        args.remove(0);
        args.insert(0, binary_name);
        args.insert(0, "-p".to_string());

        if profile == "release" {
            args.insert(0, "--release".to_string());
        } else if profile != "debug" {
            args.insert(0, profile);
            args.insert(0, "--profile".to_string());
        }

        args.insert(0, "run".to_string());
        args.insert(0, "cargo".to_string());
    }

    args
}

fn get_run_command(skip_env: &[&str], seed: u64, epoch_offset: Option<u64>) -> String {
    let args = get_cargoified_args();
    let quoted_args = args
        .iter()
        .map(|x| shell_words::quote(x.as_str()))
        .collect::<Vec<_>>();
    let cmd = quoted_args.join(" ");

    let mut env_vars = String::new();

    for (name, value) in std::env::vars() {
        use std::fmt::Write as _;

        if !name.starts_with("SIMULATOR_") && name != "RUST_LOG" {
            continue;
        }
        if skip_env.iter().any(|x| *x == name) {
            continue;
        }

        write!(env_vars, "{name}={} ", shell_words::quote(value.as_str())).unwrap();
    }

    let mut prefix = format!("SIMULATOR_SEED={seed} ");
    if let Some(epoch_offset) = epoch_offset {
        use std::fmt::Write as _;
        write!(prefix, "SIMULATOR_EPOCH_OFFSET={epoch_offset} ").unwrap();
    }

    format!("{prefix}{env_vars}{cmd}")
}

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

    #[cfg(feature = "time")]
    struct EnvGuard {
        name: &'static str,
        value: Option<String>,
    }

    #[cfg(feature = "time")]
    impl EnvGuard {
        fn new(name: &'static str) -> Self {
            Self {
                name,
                value: std::env::var(name).ok(),
            }
        }

        fn remove(&self) {
            unsafe {
                std::env::remove_var(self.name);
            }
        }
    }

    #[cfg(feature = "time")]
    impl Drop for EnvGuard {
        fn drop(&mut self) {
            match &self.value {
                Some(value) => unsafe {
                    std::env::set_var(self.name, value);
                },
                None => unsafe {
                    std::env::remove_var(self.name);
                },
            }
        }
    }

    #[test_log::test]
    #[allow(clippy::float_cmp)]
    fn test_simconfig_default() {
        let config = SimConfig::default();
        assert_eq!(config.seed, 0);
        assert_eq!(config.fail_rate, 0.0);
        assert_eq!(config.repair_rate, 1.0);
        assert_eq!(config.tcp_capacity, 64);
        assert_eq!(config.udp_capacity, 64);
        assert!(!config.enable_random_order);
        assert_eq!(config.min_message_latency, Duration::from_millis(0));
        assert_eq!(config.max_message_latency, Duration::from_secs(1));
        assert_eq!(config.duration, Duration::MAX);
        assert_eq!(config.tick_duration, Duration::from_millis(1));
    }

    #[test_log::test]
    #[allow(clippy::float_cmp)]
    fn test_simconfig_new() {
        let config = SimConfig::new();
        assert_eq!(config.seed, 0);
        assert_eq!(config.fail_rate, 0.0);
        assert_eq!(config.repair_rate, 1.0);
    }

    #[test_log::test]
    #[allow(clippy::float_cmp)]
    fn test_simconfig_builder_methods() {
        let mut config = SimConfig::new();

        let _ = config
            .fail_rate(0.5)
            .repair_rate(0.8)
            .tcp_capacity(128)
            .udp_capacity(256)
            .enable_random_order(true)
            .min_message_latency(Duration::from_millis(10))
            .max_message_latency(Duration::from_secs(2))
            .duration(Duration::from_mins(1))
            .tick_duration(Duration::from_millis(5));

        assert_eq!(config.fail_rate, 0.5);
        assert_eq!(config.repair_rate, 0.8);
        assert_eq!(config.tcp_capacity, 128);
        assert_eq!(config.udp_capacity, 256);
        assert!(config.enable_random_order);
        assert_eq!(config.min_message_latency, Duration::from_millis(10));
        assert_eq!(config.max_message_latency, Duration::from_secs(2));
        assert_eq!(config.duration, Duration::from_mins(1));
        assert_eq!(config.tick_duration, Duration::from_millis(5));
    }

    #[test_log::test]
    #[allow(clippy::float_cmp)]
    fn test_simconfig_builder_method_chaining() {
        let mut config = SimConfig::new();
        let _ = config
            .fail_rate(0.3)
            .tcp_capacity(100)
            .enable_random_order(true);

        assert_eq!(config.fail_rate, 0.3);
        assert_eq!(config.tcp_capacity, 100);
        assert!(config.enable_random_order);
    }

    #[test_log::test]
    fn test_simresult_is_success() {
        let props = SimProperties {
            config: SimConfig::new(),
            run_number: 1,
            thread_id: None,
            extra: vec![],
        };

        let run = SimRunProperties {
            steps: 100,
            real_time_millis: 1000,
            sim_time_millis: 5000,
        };

        let success = SimResult::Success {
            props: props.clone(),
            run: run.clone(),
        };
        assert!(success.is_success());

        let fail = SimResult::Fail {
            props,
            run,
            error: Some("test error".to_string()),
            panic: None,
        };
        assert!(!fail.is_success());
    }

    #[test_log::test]
    fn test_simresult_props() {
        let props = SimProperties {
            config: SimConfig::new(),
            run_number: 42,
            thread_id: Some(3),
            extra: vec![("key".to_string(), "value".to_string())],
        };

        let run = SimRunProperties {
            steps: 100,
            real_time_millis: 1000,
            sim_time_millis: 5000,
        };

        let result = SimResult::Success { props, run };

        let result_props = result.props();
        assert_eq!(result_props.run_number, 42);
        assert_eq!(result_props.thread_id, Some(3));
        assert_eq!(result_props.extra.len(), 1);
    }

    #[test_log::test]
    fn test_simresult_config() {
        let mut config = SimConfig::new();
        let _ = config.tcp_capacity(256);

        let props = SimProperties {
            config,
            run_number: 1,
            thread_id: None,
            extra: vec![],
        };

        let run = SimRunProperties {
            steps: 100,
            real_time_millis: 1000,
            sim_time_millis: 5000,
        };

        let result = SimResult::Success { props, run };

        assert_eq!(result.config().tcp_capacity, 256);
    }

    #[test_log::test]
    fn test_simresult_run() {
        let props = SimProperties {
            config: SimConfig::new(),
            run_number: 1,
            thread_id: None,
            extra: vec![],
        };

        let run = SimRunProperties {
            steps: 12345,
            real_time_millis: 9876,
            sim_time_millis: 54321,
        };

        let result = SimResult::Success { props, run };

        let result_run = result.run();
        assert_eq!(result_run.steps, 12345);
        assert_eq!(result_run.real_time_millis, 9876);
        assert_eq!(result_run.sim_time_millis, 54321);
    }

    #[test_log::test]
    fn test_get_cargoified_args_with_target_path() {
        // Note: This test depends on the actual command line arguments,
        // so we're just checking that it doesn't panic
        let args = get_cargoified_args();
        assert!(!args.is_empty());
    }

    #[test_log::test]
    fn test_simresult_props_for_fail_variant() {
        let props = SimProperties {
            config: SimConfig::new(),
            run_number: 10,
            thread_id: Some(5),
            extra: vec![("debug".to_string(), "true".to_string())],
        };

        let run = SimRunProperties {
            steps: 500,
            real_time_millis: 2000,
            sim_time_millis: 10000,
        };

        let fail = SimResult::Fail {
            props,
            run,
            error: Some("test error".to_string()),
            panic: Some("test panic".to_string()),
        };

        let result_props = fail.props();
        assert_eq!(result_props.run_number, 10);
        assert_eq!(result_props.thread_id, Some(5));
        assert_eq!(result_props.extra.len(), 1);
    }

    #[test_log::test]
    fn test_simresult_run_for_fail_variant() {
        let props = SimProperties {
            config: SimConfig::new(),
            run_number: 1,
            thread_id: None,
            extra: vec![],
        };

        let run = SimRunProperties {
            steps: 999,
            real_time_millis: 5555,
            sim_time_millis: 8888,
        };

        let fail = SimResult::Fail {
            props,
            run,
            error: Some("error".to_string()),
            panic: None,
        };

        let result_run = fail.run();
        assert_eq!(result_run.steps, 999);
        assert_eq!(result_run.real_time_millis, 5555);
        assert_eq!(result_run.sim_time_millis, 8888);
    }

    #[test_log::test]
    fn test_simresult_config_for_fail_variant() {
        let mut config = SimConfig::new();
        let _ = config.udp_capacity(512);

        let props = SimProperties {
            config,
            run_number: 1,
            thread_id: None,
            extra: vec![],
        };

        let run = SimRunProperties {
            steps: 100,
            real_time_millis: 1000,
            sim_time_millis: 5000,
        };

        let fail = SimResult::Fail {
            props,
            run,
            error: None,
            panic: Some("panic message".to_string()),
        };

        assert_eq!(fail.config().udp_capacity, 512);
    }

    #[test_log::test]
    fn test_run_info_contains_config_values() {
        let mut config = SimConfig::new();
        let _ = config
            .fail_rate(0.5)
            .tcp_capacity(128)
            .enable_random_order(true);

        let props = SimProperties {
            config,
            run_number: 1,
            thread_id: None,
            extra: vec![],
        };

        let info = run_info(&props);

        assert!(info.contains("seed=0"));
        assert!(info.contains("fail_rate=0.5"));
        assert!(info.contains("tcp_capacity=128"));
        assert!(info.contains("enable_random_order=true"));
    }

    #[test_log::test]
    fn test_run_info_includes_thread_id_when_present() {
        let props = SimProperties {
            config: SimConfig::new(),
            run_number: 1,
            thread_id: Some(42),
            extra: vec![],
        };

        let info = run_info(&props);

        assert!(info.contains("thread_id=42"));
    }

    #[test_log::test]
    fn test_run_info_excludes_thread_id_when_none() {
        let props = SimProperties {
            config: SimConfig::new(),
            run_number: 1,
            thread_id: None,
            extra: vec![],
        };

        let info = run_info(&props);

        assert!(!info.contains("thread_id="));
    }

    #[test_log::test]
    fn test_run_info_includes_extra_properties() {
        let props = SimProperties {
            config: SimConfig::new(),
            run_number: 1,
            thread_id: None,
            extra: vec![
                ("custom_key".to_string(), "custom_value".to_string()),
                ("another_key".to_string(), "another_value".to_string()),
            ],
        };

        let info = run_info(&props);

        assert!(info.contains("custom_key=custom_value"));
        assert!(info.contains("another_key=another_value"));
    }

    #[test_log::test]
    fn test_run_info_duration_forever_when_max() {
        let props = SimProperties {
            config: SimConfig::new(), // duration defaults to Duration::MAX
            run_number: 1,
            thread_id: None,
            extra: vec![],
        };

        let info = run_info(&props);

        assert!(info.contains("duration=forever"));
    }

    #[test_log::test]
    fn test_run_info_duration_value_when_finite() {
        let mut config = SimConfig::new();
        let _ = config.duration(Duration::from_mins(2));

        let props = SimProperties {
            config,
            run_number: 1,
            thread_id: None,
            extra: vec![],
        };

        let info = run_info(&props);

        // 120 seconds = 120000 milliseconds
        assert!(info.contains("duration=120000"));
    }

    #[cfg(feature = "time")]
    #[test_log::test]
    fn test_fail_output_includes_seed_and_epoch_offset_rerun_command() {
        let seed_guard = EnvGuard::new("SIMULATOR_SEED");
        let epoch_guard = EnvGuard::new("SIMULATOR_EPOCH_OFFSET");
        seed_guard.remove();
        epoch_guard.remove();

        let mut config = SimConfig::new();
        config.seed = 4242;
        config.epoch_offset = 1_700_000_000_000;

        let props = SimProperties {
            config,
            run_number: 1,
            thread_id: None,
            extra: vec![],
        };

        let run = SimRunProperties {
            steps: 10,
            real_time_millis: 100,
            sim_time_millis: 200,
        };

        let result = SimResult::Fail {
            props,
            run,
            error: Some("failure".to_string()),
            panic: None,
        };

        let output = result.to_string();
        assert!(output.contains("To run again with this seed:"));
        assert!(output.contains("SIMULATOR_SEED=4242"));
        assert!(output.contains("SIMULATOR_EPOCH_OFFSET=1700000000000"));
    }
}