hermit-run 0.4.0

Hermit: a deterministic Linux execution engine for reproducible runs, record and replay, and concurrency-race search.
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
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

//! Everything to do with the configuration, inputs, and outputs of a single run: a single point in
//! the search space that `hermit analyze` must navigate.

use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;

use anyhow::Context;
use anyhow::bail;
use clap::Parser;
use colored::Colorize;
use detcore::preemptions::PreemptionReader;
use detcore::preemptions::PreemptionRecord;
use detcore::preemptions::strip_times_from_events_file;
use detcore::types::SchedEvent;
use hermit::process::Bind;
use reverie::process::Output;
use tracing::metadata::LevelFilter;

use crate::analyze::consts::*;
use crate::analyze::types::AnalyzeOpts;
use crate::global_opts::GlobalOpts;
use crate::run::RunOpts;

/// A single run plus the results of the run, either in memory or on disk.
pub struct RunData {
    /// A unique name for this run.
    runname: String,
    /// An immutable snapshot of the options.
    analyze_opts: AnalyzeOpts, // Could use an Rc to share 1 copy.

    pub runopts: RunOpts, // TEMP: make private.

    preempts_path_in: Option<PathBuf>,
    sched_path_in: Option<PathBuf>,
    sched_path_out: Option<PathBuf>,

    /// How much logging to enable in the guest.
    log_level: LevelFilter,
    /// Where to write the guest log too (otherwise stderr).
    log_path: Option<PathBuf>,

    /// The input preemptions, if it has been read to memory.
    in_mem_preempts_in: Option<PreemptionRecord>,
    in_mem_sched_out: Option<PreemptionRecord>,

    is_a_match: Option<bool>,
}

impl RunData {
    pub fn root_path(&self) -> PathBuf {
        let tmp_dir = self.analyze_opts.tmp_dir.as_ref().unwrap();
        tmp_dir.join(&self.runname)
    }

    fn out_path(&self) -> PathBuf {
        let tmp_dir = self.analyze_opts.tmp_dir.as_ref().unwrap();
        tmp_dir.join(self.runname.clone() + "_out")
    }

    #[allow(dead_code)]
    pub fn preempts_path_in(&mut self) -> &Path {
        if self.preempts_path_in.is_none() {
            let path = if let Some(p) = &self.runopts.det_opts.det_config.replay_preemptions_from {
                p.to_owned()
            } else {
                self.root_path().with_extension(PREEMPTS_EXT)
            };
            self.preempts_path_in = Some(path);
        }
        self.preempts_path_in.as_ref().unwrap()
    }

    pub fn preempts_path_out(&mut self) -> &Path {
        // TODO: split these apart:
        self.sched_path_out()
    }

    // Return a reference to the in-memory preemption record, reading it from disk if it isn't read
    // already. Errors if the file doesn't exist.
    pub fn preempts_out(&mut self) -> &PreemptionRecord {
        if self.in_mem_sched_out.is_none() {
            let path = self.sched_path_out();
            let pr = PreemptionReader::new(path);
            self.in_mem_sched_out = Some(pr.load_all());
        }
        self.in_mem_sched_out.as_ref().unwrap()
    }

    pub fn sched_path_out(&mut self) -> &Path {
        if self.sched_path_out.is_none() {
            let path = if let Some(p) = &self.runopts.det_opts.det_config.record_preemptions_to {
                p.to_owned()
            } else {
                self.out_path().with_extension(PREEMPTS_EXT)
            };
            self.sched_path_out = Some(path);
        }
        self.sched_path_out.as_ref().unwrap()
    }

    pub fn sched_path_in(&mut self) -> &Path {
        if self.sched_path_in.is_none() {
            let path = if let Some(p) = &self.runopts.det_opts.det_config.replay_schedule_from {
                p.to_owned()
            } else {
                self.root_path().with_extension(PREEMPTS_EXT)
            };
            self.sched_path_in = Some(path);
        }
        self.sched_path_in.as_ref().unwrap()
    }

    /// Convenience function
    pub fn sched_out_file_name(&mut self) -> String {
        self.sched_path_out()
            .file_name()
            .unwrap()
            .to_string_lossy()
            .to_string()
    }

    pub fn sched_out(&mut self) -> &Vec<SchedEvent> {
        let pr = self.preempts_out();
        pr.schedevents()
    }

    /// Only set after launch.
    pub fn log_path(&mut self) -> Option<&PathBuf> {
        if self.has_launched() {
            if self.log_path.is_none() {
                self.log_path = Some(self.root_path().with_extension(LOG_EXT))
            }
            self.log_path.as_ref()
        } else {
            None
        }
    }

    /// Only set after launch.
    pub fn is_a_match(&self) -> bool {
        self.is_a_match.expect("only called after launch method")
    }

    pub fn has_launched(&self) -> bool {
        self.is_a_match.is_some()
    }

    /// Called after the run has been launched, normalize the output preemptions and swap around so
    /// that our output file points to the normalized version.
    pub fn normalize_preempts_out(&mut self) {
        assert!(self.has_launched());
        let preempts_path = self.preempts_path_out();
        let normalized_path = preempts_path.with_extension("normalized");

        let normalized = self.preempts_out().normalize();
        normalized
            .write_to_disk(&normalized_path)
            .expect("write of preempts file to succeed");
        self.in_mem_sched_out = Some(normalized);
        self.sched_path_out = Some(normalized_path);
    }

    /// The global options a trial run is launched with. Trials go through
    /// `RunOpts::run`, which dispatches on the trial `RunOpts`' own backend (set
    /// from `hermit --backend <BACKEND> analyze` by `get_raw_runopts`); this
    /// copy keeps the trial's global options consistent with it.
    fn trial_global_opts(&self) -> GlobalOpts {
        let log_path = self.root_path().with_extension(LOG_EXT);
        GlobalOpts {
            log: Some(self.log_level),
            log_file: if self.analyze_opts.verbose || self.analyze_opts.selfcheck {
                Some(log_path)
            } else {
                None
            },
            backend: self.analyze_opts.backend,
            log_file_handle: None,
            run_evidence_log_handle: None,
            run_evidence_write_error: None,
        }
    }

    /// Execute the run. (Including setting up logging and temp dir binding.)
    pub fn launch(&mut self) -> anyhow::Result<()> {
        let root = self.root_path();
        let gopts = self.trial_global_opts();
        // Open it HERE, on the host, for the same reason `main` does: `launch` runs
        // before the container exists, and opening later would resolve this path in
        // the guest namespace. Analyze's log lands under the run's own directory, so
        // it is only exposed when that directory is itself inside the container's
        // /tmp -- but the fix is the same and costs nothing.
        let mut gopts = gopts;
        gopts.open_log_file()?;
        let final_record_path = self
            .runopts
            .det_opts
            .det_config
            .record_preemptions_to
            .take();

        // Some last-minute sleight-of-hand to record to a temporary location instead.
        if final_record_path.is_some() {
            let temp_path = root.with_extension(PREEMPTS_EXT_PRESTRIPPED);
            self.runopts.det_opts.det_config.record_preemptions_to = Some(temp_path);
        }

        self.runopts.validate_args()?;

        let repro_file = self.root_path().with_extension("repro");
        std::fs::write(repro_file, self.to_repro() + "\n")?;

        let (_, output) = self.runopts.run(&gopts, true)?;
        let output: Output = output.context("expected captured output")?;

        File::create(root.with_extension("stdout"))
            .unwrap()
            .write_all(&output.stdout)
            .unwrap();
        File::create(root.with_extension("stderr"))
            .unwrap()
            .write_all(&output.stderr)
            .unwrap();

        let temp_path = self
            .runopts
            .det_opts
            .det_config
            .record_preemptions_to
            .take();
        if let Some(temp_path) = temp_path {
            Self::post_process_events_file(&temp_path, final_record_path.as_ref().unwrap())?;
            // Restore the setting:
            self.runopts.det_opts.det_config.record_preemptions_to = final_record_path;
        }

        self.is_a_match = Some(self.analyze_opts.output_matches(&output));

        if self.analyze_opts.verbose {
            println!(
                "Guest stdout:\n{}",
                String::from_utf8(output.stdout).unwrap()
            );
            println!(
                "Guest stderr:\n{}",
                String::from_utf8(output.stderr).unwrap()
            );
        }
        Ok(())
    }

    /// Any post-processing that needs to be applied to a recorded file of SchedEvents
    pub fn post_process_events_file(sched_path: &Path, dest: &Path) -> anyhow::Result<()> {
        let _ = strip_times_from_events_file(sched_path, Some(dest.to_owned()))?;
        Ok(())
    }

    fn log_level(aopts: &AnalyzeOpts) -> LevelFilter {
        let mut lvl = if let Some(l) = &aopts.guest_log {
            *l
        } else {
            LevelFilter::WARN
        };

        // Ensure a minum level for these functionalities:
        if aopts.verbose || aopts.selfcheck && lvl < LevelFilter::DEBUG {
            if aopts.guest_log.is_some() {
                eprintln!(
                    "WARNING: manually set log lvl to {} but need DEBUG for selfcheck/verbose functionality",
                    lvl
                );
            }
            lvl = LevelFilter::DEBUG;
        }

        lvl
    }

    pub fn new(aopts: &AnalyzeOpts, runname: String, runopts: RunOpts) -> Self {
        let log_level: LevelFilter = Self::log_level(aopts);
        let mut rd = RunData {
            runname,
            analyze_opts: aopts.clone(),
            runopts,
            preempts_path_in: None,
            sched_path_in: None,
            sched_path_out: None,
            log_path: None,
            in_mem_preempts_in: None,
            in_mem_sched_out: None,
            is_a_match: None,
            log_level,
        };

        // By default we save the config for every run.
        let conf_file = rd.root_path().with_extension("config");
        rd.runopts.save_config = Some(conf_file);

        let summary_file = rd.root_path().with_extension("summary");
        rd.runopts.summary_json = Some(summary_file);

        rd
    }

    /// Create a new run with the baseline RunOpts created from the AnalyzeOpts
    pub fn new_baseline(aopts: &AnalyzeOpts, runname: String) -> anyhow::Result<Self> {
        let ro = Self::get_base_runopts(aopts)?;
        Ok(Self::new(aopts, runname, ro))
    }

    /// Create a run for the initial on-target execution.
    pub fn new_run1_target(aopts: &AnalyzeOpts, runname: String) -> anyhow::Result<Self> {
        let ro = Self::get_run1_runopts(aopts)?;
        Ok(Self::new(aopts, runname, ro))
    }

    /// Replay with the selected run's seeds and the original replay policy.
    pub fn new_run1_replay(
        aopts: &AnalyzeOpts,
        runname: String,
        selected: &RunOpts,
    ) -> anyhow::Result<Self> {
        let mut replay = Self::new_run1_target(aopts, runname)?;
        let target = &selected.det_opts.det_config;
        let config = &mut replay.runopts.det_opts.det_config;
        // Search chooses an effective scheduler seed independently of the
        // initial command line. Preserve all selected seed inputs, without
        // copying search-only overrides such as --imprecise-search into replay.
        config.seed = target.seed;
        config.rng_seed = target.rng_seed;
        config.fuzz_seed = target.fuzz_seed;
        config.sched_seed = target.sched_seed;
        Ok(replay)
    }

    /// The baseline RunOpts based on user flags plus some sanitation/validation.
    fn get_base_runopts(aopts: &AnalyzeOpts) -> anyhow::Result<RunOpts> {
        let mut ro = Self::get_raw_runopts(aopts);
        if ro.no_sequentialize_threads {
            bail!(
                "Error, cannot search through executions with --no-sequentialize-threads.  Determinism required.",
            )
        }

        // We could add a flag for analyze-without chaos, but it's a rare use case that isn't
        // usefully supported now anyway.  Exploring with RNG alone doesn't make sense, but we may
        // want to make it possible to do analyze with the stick random scheduler instead of the
        // one.
        ro.det_opts.det_config.chaos = true;

        ro.validate_args()?;
        assert!(ro.det_opts.det_config.sequentialize_threads);
        if aopts.run1_seed.is_some() && !ro.det_opts.det_config.chaos {
            eprintln!(
                "{}",
                "WARNING: --chaos not in supplied hermit run args, but --run1-seed is.  Usually this is an error."
                    .bold()
                    .red()
            )
        }
        Self::runopts_add_binds(aopts, &mut ro)?;

        Ok(ro)
    }

    fn runopts_add_binds(aopts: &AnalyzeOpts, runopts: &mut RunOpts) -> anyhow::Result<()> {
        let bind_dir: Bind = Bind::from_str(aopts.get_tmp()?.to_str().unwrap())?;
        runopts.bind.push(bind_dir);
        runopts.validate_args()?;
        Ok(())
    }

    /// The raw, unvarnished, RunOpts.
    fn get_raw_runopts(aopts: &AnalyzeOpts) -> RunOpts {
        // Bogus arg 0 for CLI argument parsing:
        let mut run_cmd: Vec<String> = vec!["hermit-run".to_string()];

        for arg in &aopts.run_arg {
            run_cmd.push(arg.to_string());
        }
        for arg in &aopts.run_args {
            run_cmd.push(arg.to_string());
        }
        let mut runopts = RunOpts::try_parse_from(run_cmd.iter()).unwrap_or_else(|error| {
            if crate::misplaced_backend_argument(&error).is_some() {
                // `--backend` is global. Point at the spelling that selects the
                // trials' backend instead of letting clap suggest the unrelated
                // `--backend-engagement-json`. clap reports only the flag name,
                // so read the value from the run arguments themselves.
                // The first `--backend` is the one clap refused; later tokens may
                // be the guest's own arguments.
                let value = run_cmd
                    .iter()
                    .enumerate()
                    .find_map(|(index, arg)| {
                        if arg == "--backend" {
                            Some(run_cmd.get(index + 1).map(String::as_str).unwrap_or(""))
                        } else {
                            arg.strip_prefix("--backend=")
                        }
                    })
                    .filter(|value| !value.is_empty() && !value.starts_with('-'))
                    .unwrap_or("<BACKEND>");
                clap::Error::raw(
                    clap::error::ErrorKind::UnknownArgument,
                    format!(
                        "`--backend` is not a `run` option, so it cannot be passed through \
                         the run arguments of `hermit analyze` or `hermit bisect`. It is a \
                         global option: select the backend for every trial with `hermit \
                         --backend={value} analyze ...` or `hermit --backend={value} bisect \
                         ...`.\n"
                    ),
                )
                .exit()
            }
            error.exit()
        });
        // Apply the global backend before `get_base_runopts` validates these
        // options, so backend-specific validation sees the backend the trials
        // will run on.
        runopts.set_backend(aopts.backend);
        runopts
    }

    /// Extract the (initial) RunOpts for target/run1 that are implied by all of hermit analyze's arguments.
    fn get_run1_runopts(aopts: &AnalyzeOpts) -> anyhow::Result<RunOpts> {
        let mut ro = Self::get_base_runopts(aopts)?;

        // If there was a --sched-seed specified in run_args, it is overridden by this setting:
        if let Some(seed) = aopts.run1_seed {
            ro.det_opts.det_config.seed = seed;
        } else if let Some(path) = &aopts.run1_preemptions {
            ro.det_opts.det_config.replay_preemptions_from = Some(path.clone());
        }
        Ok(ro)
    }

    /// A temporary constructor method until minimize overhaul is complete and it returns a RunData directly.
    pub fn from_minimize_output(
        aopts: &AnalyzeOpts,
        runname: String,
        runopts: RunOpts,
        in_mem_preempts: PreemptionRecord,
        preempts_path: PathBuf,
        log_path: PathBuf,
    ) -> Self {
        let log_level: LevelFilter = Self::log_level(aopts);
        RunData {
            runname,
            analyze_opts: aopts.clone(),
            runopts,
            preempts_path_in: None,
            sched_path_in: None,
            sched_path_out: Some(preempts_path),
            log_path: Some(log_path),
            log_level,
            in_mem_sched_out: Some(in_mem_preempts),
            in_mem_preempts_in: None,
            // Invariant: minimize should always return an on-target configuration:
            is_a_match: Some(true),
        }
    }

    /// Another fake run that stores a result without actually launching anything.
    pub fn from_schedule_trace(
        aopts: &AnalyzeOpts,
        runname: String,
        runopts: RunOpts,
        sched_path: PathBuf,
    ) -> Self {
        let log_level: LevelFilter = Self::log_level(aopts);
        RunData {
            runname,
            analyze_opts: aopts.clone(),
            runopts,
            preempts_path_in: None,
            sched_path_in: None,
            sched_path_out: Some(sched_path),
            log_path: None,
            log_level,
            in_mem_sched_out: None,
            in_mem_preempts_in: None,
            // Don't claim that it was run:
            is_a_match: None,
        }
    }

    pub fn with_preempts_path_in(mut self, path: PathBuf) -> Self {
        self.runopts.det_opts.det_config.replay_preemptions_from = Some(path);
        self
    }

    pub fn with_preempts_in(mut self, pr: PreemptionRecord) -> Self {
        let path = self.preempts_path_in().to_path_buf();
        pr.write_to_disk(&path)
            .expect("write of preempts file to succeed");
        self.in_mem_preempts_in = Some(pr);
        self.with_preempts_path_in(path)
    }

    pub fn with_preemption_recording(self) -> Self {
        let path = self.out_path().with_extension(PREEMPTS_EXT);
        self.with_preemption_recording_to(path)
    }

    pub fn with_preemption_recording_to(mut self, path: PathBuf) -> Self {
        self.runopts.det_opts.det_config.record_preemptions_to = Some(path);
        self
    }

    // TODO: separate from preemption recording
    pub fn with_schedule_recording(self) -> Self {
        self.with_preemption_recording()
    }

    // TODO: separate from preemption recording
    pub fn with_schedule_recording_to(self, path: PathBuf) -> Self {
        self.with_preemption_recording_to(path)
    }

    /// Replay from the default location, as returned by sched_path_in
    pub fn with_schedule_replay(mut self) -> Self {
        let path = self.sched_path_in().to_owned();
        self.with_schedule_replay_from(path)
    }

    pub fn with_schedule_replay_from(mut self, path: PathBuf) -> Self {
        self.runopts.det_opts.det_config.replay_schedule_from = Some(path);
        self
    }

    pub fn to_repro(&self) -> String {
        let logging = if let Some(path) = &self.log_path {
            format!(" --log=debug --log-file={}", path.display())
        } else {
            "".to_string()
        };
        // let logging = if self.analyze_opts.verbose || self.analyze_opts.selfcheck {
        //     let path = self.log_path().unwrap();
        //     format!(" --log=debug --log-file={}", path.display())
        // } else {
        //     "".to_string()
        // };
        format!(
            "hermit{}{} run {}",
            logging,
            self.runopts.global_backend_arg(),
            self.runopts
        )
    }

    pub fn into_runopts(self) -> RunOpts {
        self.runopts
    }
}

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

    /// `run` has no `--backend`, so `hermit --backend <BACKEND> analyze` is the
    /// only way to choose the trials' backend. The selection must pass the
    /// scope check and reach the options every trial is launched with: the
    /// `GlobalOpts` that `RunOpts::main` takes its backend from, the validated
    /// trial `RunOpts`, and the printed reproducer.
    #[test]
    fn global_backend_reaches_every_trial_run() {
        for flag in ["ptrace", "kvm"] {
            let argv = [
                "hermit".to_owned(),
                format!("--backend={flag}"),
                "analyze".to_owned(),
                "--".to_owned(),
                "/bin/true".to_owned(),
            ];
            let args = crate::Args::try_parse_from(&argv).unwrap();
            args.command
                .validate_backend_scope(args.global.backend)
                .unwrap_or_else(|error| panic!("{argv:?} must be in scope: {error:#}"));
            let crate::Subcommand::Analyze(mut options) = args.command else {
                panic!("{argv:?} is not analyze")
            };
            options.apply_global(&args.global);
            let workspace = tempfile::tempdir().unwrap();
            options.tmp_dir = Some(workspace.path().to_path_buf());
            let run = RunData::new_baseline(&options, "backend".to_owned())
                .unwrap_or_else(|error| panic!("{flag}: {error:#}"));
            assert_eq!(
                run.trial_global_opts().backend,
                args.global.backend,
                "{flag}"
            );
            assert_eq!(
                run.runopts.global_backend_arg(),
                format!(" --backend={flag}")
            );
            let repro = run.to_repro();
            assert!(
                repro.contains(&format!(" --backend={flag} run ")),
                "{flag}: reproducer does not select the backend: {repro}"
            );
        }
    }

    #[test]
    fn analyzer_reproducer_retains_actual_default_and_fractional_epoch() {
        use clap::CommandFactory;
        for epoch in ["2026-01-01T00:00:00Z", "2000-12-31T23:59:59.123456789Z"] {
            let mut options = AnalyzeOpts::try_parse_from([
                "analyze",
                "--",
                "--epoch",
                epoch,
                "--seed=71",
                "/bin/true",
            ])
            .unwrap();
            let workspace = tempfile::tempdir().unwrap();
            options.tmp_dir = Some(workspace.path().to_path_buf());
            let run = RunData::new_baseline(&options, "epoch-repro".to_owned()).unwrap();
            let repro = run.to_repro();
            assert_eq!(repro.matches("--epoch=").count(), 1, "{repro}");
            let matches = crate::Args::command()
                .try_get_matches_from(shell_words::split(&repro).unwrap())
                .unwrap();
            let args = crate::args_from_matches_with_clock(&matches, || {
                panic!("analyzer reproduction must retain its actual fixed input")
            })
            .unwrap();
            let crate::Subcommand::Run(parsed) = args.command else {
                panic!("expected run")
            };
            assert_eq!(
                parsed.det_opts.det_config.epoch,
                run.runopts.det_opts.det_config.epoch
            );
            assert_eq!(
                parsed.det_opts.det_config.seed,
                run.runopts.det_opts.det_config.seed
            );
        }
    }

    #[test]
    fn preemption_replay_preserves_selected_seeds_and_original_timer_policy() {
        for explicit_imprecise_timers in [false, true] {
            let mut args = vec![
                "analyze",
                "--selfcheck",
                "--search",
                "--imprecise-search",
                "--run1-seed=211",
                "--",
            ];
            if explicit_imprecise_timers {
                args.push("--imprecise-timers");
            }
            args.push("/bin/true");
            let mut options = AnalyzeOpts::try_parse_from(args).unwrap();
            let workspace = tempfile::tempdir().unwrap();
            options.tmp_dir = Some(workspace.path().to_path_buf());
            let mut selected = RunData::new_baseline(&options, "selected".to_owned()).unwrap();
            let selected_config = &mut selected.runopts.det_opts.det_config;
            selected_config.seed = 101;
            selected_config.rng_seed = Some(102);
            selected_config.fuzz_seed = Some(103);
            selected_config.sched_seed = Some(104);
            // This is the override launch_search applies, not a replay option.
            selected_config.imprecise_timers = true;
            let preempts = workspace.path().join("selected.preempts");
            let replay = RunData::new_run1_replay(&options, "replay".to_owned(), &selected.runopts)
                .unwrap()
                .with_preempts_path_in(preempts.clone())
                .with_preemption_recording();
            let config = &replay.runopts.det_opts.det_config;
            assert_eq!(config.seed, 101);
            assert_eq!(config.rng_seed, Some(102));
            assert_eq!(config.fuzz_seed, Some(103));
            assert_eq!(config.sched_seed, Some(104));
            assert_eq!(config.imprecise_timers, explicit_imprecise_timers);
            assert_eq!(config.replay_preemptions_from.as_ref(), Some(&preempts));
            assert_ne!(replay.runopts.save_config, selected.runopts.save_config);
            assert_ne!(replay.runopts.summary_json, selected.runopts.summary_json);
            assert_eq!(
                config.record_preemptions_to.as_ref(),
                Some(&workspace.path().join("replay_out.preempts")),
            );
        }
    }
}