Skip to content

Commit 38715f7

Browse files
committed
Auto merge of rust-lang#3548 - RalfJung:many-seeds, r=RalfJung
make many-seeds a mode of ./miri run rather than a separate command Also parallelize it so we use all cores to try seeds at the same time. Fixes rust-lang/miri#3509 by not alternating between different build modes (with/without dev-dependencies) all the time.
2 parents 74701dc + f7a3aa9 commit 38715f7

File tree

6 files changed

+134
-96
lines changed

6 files changed

+134
-96
lines changed

src/tools/miri/ci/ci.sh

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,6 @@ function endgroup {
1313

1414
begingroup "Building Miri"
1515

16-
# Special Windows hacks
17-
if [ "$HOST_TARGET" = i686-pc-windows-msvc ]; then
18-
# The $BASH variable is `/bin/bash` here, but that path does not actually work. There are some
19-
# hacks in place somewhere to try to paper over this, but the hacks dont work either (see
20-
# <https://github.com/rust-lang/miri/pull/3402>). So we hard-code the correct location for Github
21-
# CI instead.
22-
BASH="C:/Program Files/Git/usr/bin/bash"
23-
fi
24-
2516
# Global configuration
2617
export RUSTFLAGS="-D warnings"
2718
export CARGO_INCREMENTAL=0
@@ -71,10 +62,9 @@ function run_tests {
7162
time MIRIFLAGS="${MIRIFLAGS-} -O -Zmir-opt-level=4 -Cdebug-assertions=yes" MIRI_SKIP_UI_CHECKS=1 ./miri test -- tests/{pass,panic}
7263
fi
7364
if [ -n "${MANY_SEEDS-}" ]; then
74-
# Also run some many-seeds tests. 64 seeds means this takes around a minute per test.
75-
# (Need to invoke via explicit `bash -c` for Windows.)
65+
# Also run some many-seeds tests.
7666
time for FILE in tests/many-seeds/*.rs; do
77-
MIRI_SEEDS=$MANY_SEEDS ./miri many-seeds "$BASH" -c "./miri run '$FILE'"
67+
./miri run "--many-seeds=0..$MANY_SEEDS" "$FILE"
7868
done
7969
fi
8070
if [ -n "${TEST_BENCH-}" ]; then
@@ -135,7 +125,7 @@ case $HOST_TARGET in
135125
GC_STRESS=1 MIR_OPT=1 MANY_SEEDS=64 TEST_BENCH=1 CARGO_MIRI_ENV=1 run_tests
136126
# Extra tier 1
137127
# With reduced many-seed count to avoid spending too much time on that.
138-
# (All OSes are run with 64 seeds at least once though via the macOS runner.)
128+
# (All OSes and ABIs are run with 64 seeds at least once though via the macOS runner.)
139129
MANY_SEEDS=16 MIRI_TEST_TARGET=i686-unknown-linux-gnu run_tests
140130
MANY_SEEDS=16 MIRI_TEST_TARGET=aarch64-unknown-linux-gnu run_tests
141131
MANY_SEEDS=16 MIRI_TEST_TARGET=x86_64-apple-darwin run_tests
@@ -164,9 +154,9 @@ case $HOST_TARGET in
164154
;;
165155
i686-pc-windows-msvc)
166156
# Host
167-
# Only smoke-test `many-seeds`; 64 runs of just the scoped-thread-leak test take 15min here!
168-
# See <https://github.com/rust-lang/miri/issues/3509>.
169-
GC_STRESS=1 MIR_OPT=1 MANY_SEEDS=1 TEST_BENCH=1 run_tests
157+
# With reduced many-seeds count as this is the slowest runner already.
158+
# (The macOS runner checks windows-msvc with full many-seeds count.)
159+
GC_STRESS=1 MIR_OPT=1 MANY_SEEDS=16 TEST_BENCH=1 run_tests
170160
# Extra tier 1
171161
# We really want to ensure a Linux target works on a Windows host,
172162
# and a 64bit target works on a 32bit host.

src/tools/miri/miri-script/Cargo.lock

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -466,15 +466,15 @@ checksum = "0770833d60a970638e989b3fa9fd2bb1aaadcf88963d1659fd7d9990196ed2d6"
466466

467467
[[package]]
468468
name = "xshell"
469-
version = "0.2.5"
469+
version = "0.2.6"
470470
source = "registry+https://github.com/rust-lang/crates.io-index"
471-
checksum = "ce2107fe03e558353b4c71ad7626d58ed82efaf56c54134228608893c77023ad"
471+
checksum = "6db0ab86eae739efd1b054a8d3d16041914030ac4e01cd1dca0cf252fd8b6437"
472472
dependencies = [
473473
"xshell-macros",
474474
]
475475

476476
[[package]]
477477
name = "xshell-macros"
478-
version = "0.2.5"
478+
version = "0.2.6"
479479
source = "registry+https://github.com/rust-lang/crates.io-index"
480-
checksum = "7e2c411759b501fb9501aac2b1b2d287a6e93e5bdcf13c25306b23e1b716dd0e"
480+
checksum = "9d422e8e38ec76e2f06ee439ccc765e9c6a9638b9e7c9f2e8255e4d41e8bd852"

src/tools/miri/miri-script/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ itertools = "0.11"
1919
path_macro = "1.0"
2020
shell-words = "1.1"
2121
anyhow = "1.0"
22-
xshell = "0.2"
22+
xshell = "0.2.6"
2323
rustc_version = "0.4"
2424
dunce = "1.0.4"
2525
directories = "5"

src/tools/miri/miri-script/src/commands.rs

Lines changed: 42 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::env;
22
use std::ffi::OsString;
33
use std::io::Write;
44
use std::ops::Not;
5+
use std::ops::Range;
56
use std::path::PathBuf;
67
use std::process;
78
use std::thread;
@@ -150,7 +151,6 @@ impl Command {
150151
| Command::Fmt { .. }
151152
| Command::Clippy { .. }
152153
| Command::Cargo { .. } => Self::auto_actions()?,
153-
| Command::ManySeeds { .. }
154154
| Command::Toolchain { .. }
155155
| Command::Bench { .. }
156156
| Command::RustcPull { .. }
@@ -162,11 +162,11 @@ impl Command {
162162
Command::Build { flags } => Self::build(flags),
163163
Command::Check { flags } => Self::check(flags),
164164
Command::Test { bless, flags } => Self::test(bless, flags),
165-
Command::Run { dep, verbose, flags } => Self::run(dep, verbose, flags),
165+
Command::Run { dep, verbose, many_seeds, flags } =>
166+
Self::run(dep, verbose, many_seeds, flags),
166167
Command::Fmt { flags } => Self::fmt(flags),
167168
Command::Clippy { flags } => Self::clippy(flags),
168169
Command::Cargo { flags } => Self::cargo(flags),
169-
Command::ManySeeds { command } => Self::many_seeds(command),
170170
Command::Bench { benches } => Self::bench(benches),
171171
Command::Toolchain { flags } => Self::toolchain(flags),
172172
Command::RustcPull { commit } => Self::rustc_pull(commit.clone()),
@@ -367,43 +367,6 @@ impl Command {
367367
Ok(())
368368
}
369369

370-
fn many_seeds(command: Vec<OsString>) -> Result<()> {
371-
let seed_start: u64 = env::var("MIRI_SEED_START")
372-
.unwrap_or_else(|_| "0".into())
373-
.parse()
374-
.context("failed to parse MIRI_SEED_START")?;
375-
let seed_end: u64 = match (env::var("MIRI_SEEDS"), env::var("MIRI_SEED_END")) {
376-
(Ok(_), Ok(_)) => bail!("Only one of MIRI_SEEDS and MIRI_SEED_END may be set"),
377-
(Ok(seeds), Err(_)) =>
378-
seed_start + seeds.parse::<u64>().context("failed to parse MIRI_SEEDS")?,
379-
(Err(_), Ok(seed_end)) => seed_end.parse().context("failed to parse MIRI_SEED_END")?,
380-
(Err(_), Err(_)) => seed_start + 256,
381-
};
382-
if seed_end <= seed_start {
383-
bail!("the end of the seed range must be larger than the start.");
384-
}
385-
386-
let Some((command_name, trailing_args)) = command.split_first() else {
387-
bail!("expected many-seeds command to be non-empty");
388-
};
389-
let sh = Shell::new()?;
390-
sh.set_var("MIRI_AUTO_OPS", "no"); // just in case we get recursively invoked
391-
for seed in seed_start..seed_end {
392-
println!("Trying seed: {seed}");
393-
let mut miriflags = env::var_os("MIRIFLAGS").unwrap_or_default();
394-
miriflags.push(format!(" -Zlayout-seed={seed} -Zmiri-seed={seed}"));
395-
let status = cmd!(sh, "{command_name} {trailing_args...}")
396-
.env("MIRIFLAGS", miriflags)
397-
.quiet()
398-
.run();
399-
if let Err(err) = status {
400-
println!("Failing seed: {seed}");
401-
return Err(err.into());
402-
}
403-
}
404-
Ok(())
405-
}
406-
407370
fn bench(benches: Vec<OsString>) -> Result<()> {
408371
// The hyperfine to use
409372
let hyperfine = env::var("HYPERFINE");
@@ -495,7 +458,12 @@ impl Command {
495458
Ok(())
496459
}
497460

498-
fn run(dep: bool, verbose: bool, mut flags: Vec<OsString>) -> Result<()> {
461+
fn run(
462+
dep: bool,
463+
verbose: bool,
464+
many_seeds: Option<Range<u32>>,
465+
mut flags: Vec<OsString>,
466+
) -> Result<()> {
499467
let mut e = MiriEnv::new()?;
500468
// Scan for "--target" to overwrite the "MIRI_TEST_TARGET" env var so
501469
// that we set the MIRI_SYSROOT up the right way. We must make sure that
@@ -526,26 +494,46 @@ impl Command {
526494
flags.push("--sysroot".into());
527495
flags.push(miri_sysroot.into());
528496

529-
// Then run the actual command. Also add MIRIFLAGS.
497+
// Compute everything needed to run the actual command. Also add MIRIFLAGS.
530498
let miri_manifest = path!(e.miri_dir / "Cargo.toml");
531499
let miri_flags = e.sh.var("MIRIFLAGS").unwrap_or_default();
532500
let miri_flags = flagsplit(&miri_flags);
533501
let toolchain = &e.toolchain;
534502
let extra_flags = &e.cargo_extra_flags;
535503
let quiet_flag = if verbose { None } else { Some("--quiet") };
536-
let mut cmd = if dep {
537-
cmd!(
538-
e.sh,
539-
"cargo +{toolchain} {quiet_flag...} test {extra_flags...} --manifest-path {miri_manifest} --test ui -- --miri-run-dep-mode {miri_flags...} {flags...}"
540-
)
541-
} else {
542-
cmd!(
543-
e.sh,
544-
"cargo +{toolchain} {quiet_flag...} run {extra_flags...} --manifest-path {miri_manifest} -- {miri_flags...} {flags...}"
545-
)
504+
// This closure runs the command with the given `seed_flag` added between the MIRIFLAGS and
505+
// the `flags` given on the command-line.
506+
let run_miri = |sh: &Shell, seed_flag: Option<String>| -> Result<()> {
507+
// The basic command that executes the Miri driver.
508+
let mut cmd = if dep {
509+
cmd!(
510+
sh,
511+
"cargo +{toolchain} {quiet_flag...} test {extra_flags...} --manifest-path {miri_manifest} --test ui -- --miri-run-dep-mode"
512+
)
513+
} else {
514+
cmd!(
515+
sh,
516+
"cargo +{toolchain} {quiet_flag...} run {extra_flags...} --manifest-path {miri_manifest} --"
517+
)
518+
};
519+
cmd.set_quiet(!verbose);
520+
// Add Miri flags
521+
let cmd = cmd.args(&miri_flags).args(seed_flag).args(&flags);
522+
// And run the thing.
523+
Ok(cmd.run()?)
546524
};
547-
cmd.set_quiet(!verbose);
548-
cmd.run()?;
525+
// Run the closure once or many times.
526+
if let Some(seed_range) = many_seeds {
527+
e.run_many_times(seed_range, |sh, seed| {
528+
eprintln!("Trying seed: {seed}");
529+
run_miri(sh, Some(format!("-Zmiri-seed={seed}"))).map_err(|err| {
530+
eprintln!("FAILING SEED: {seed}");
531+
err
532+
})
533+
})?;
534+
} else {
535+
run_miri(&e.sh, None)?;
536+
}
549537
Ok(())
550538
}
551539

src/tools/miri/miri-script/src/main.rs

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
mod commands;
44
mod util;
55

6-
use std::env;
76
use std::ffi::OsString;
7+
use std::{env, ops::Range};
88

9-
use anyhow::{anyhow, bail, Result};
9+
use anyhow::{anyhow, bail, Context, Result};
1010

1111
#[derive(Clone, Debug)]
1212
pub enum Command {
@@ -39,6 +39,7 @@ pub enum Command {
3939
Run {
4040
dep: bool,
4141
verbose: bool,
42+
many_seeds: Option<Range<u32>>,
4243
/// Flags that are passed through to `miri`.
4344
flags: Vec<OsString>,
4445
},
@@ -55,10 +56,6 @@ pub enum Command {
5556
/// Runs just `cargo <flags>` with the Miri-specific environment variables.
5657
/// Mainly meant to be invoked by rust-analyzer.
5758
Cargo { flags: Vec<OsString> },
58-
/// Runs <command> over and over again with different seeds for Miri. The MIRIFLAGS
59-
/// variable is set to its original value appended with ` -Zmiri-seed=$SEED` for
60-
/// many different seeds.
61-
ManySeeds { command: Vec<OsString> },
6259
/// Runs the benchmarks from bench-cargo-miri in hyperfine. hyperfine needs to be installed.
6360
Bench {
6461
/// List of benchmarks to run. By default all benchmarks are run.
@@ -91,9 +88,11 @@ Just check miri. <flags> are passed to `cargo check`.
9188
Build miri, set up a sysroot and then run the test suite. <flags> are passed
9289
to the final `cargo test` invocation.
9390
94-
./miri run [--dep] [-v|--verbose] <flags>:
91+
./miri run [--dep] [-v|--verbose] [--many-seeds|--many-seeds=..to|--many-seeds=from..to] <flags>:
9592
Build miri, set up a sysroot and then run the driver with the given <flags>.
9693
(Also respects MIRIFLAGS environment variable.)
94+
If `--many-seeds` is present, Miri is run many times in parallel with different seeds.
95+
The range defaults to `0..256`.
9796
9897
./miri fmt <flags>:
9998
Format all sources and tests. <flags> are passed to `rustfmt`.
@@ -111,13 +110,6 @@ install`. Sets up the rpath such that the installed binary should work in any
111110
working directory. Note that the binaries are placed in the `miri` toolchain
112111
sysroot, to prevent conflicts with other toolchains.
113112
114-
./miri many-seeds <command>:
115-
Runs <command> over and over again with different seeds for Miri. The MIRIFLAGS
116-
variable is set to its original value appended with ` -Zmiri-seed=$SEED` for
117-
many different seeds. MIRI_SEED_START controls the first seed to try (default: 0).
118-
MIRI_SEEDS controls how many seeds are being tried (default: 256);
119-
alternatively, MIRI_SEED_END controls the end of the (exclusive) seed range to try.
120-
121113
./miri bench <benches>:
122114
Runs the benchmarks from bench-cargo-miri in hyperfine. hyperfine needs to be installed.
123115
<benches> can explicitly list the benchmarks to run; by default, all of them are run.
@@ -165,22 +157,37 @@ fn main() -> Result<()> {
165157
Some("run") => {
166158
let mut dep = false;
167159
let mut verbose = false;
168-
while let Some(arg) = args.peek().and_then(|a| a.to_str()) {
169-
match arg {
170-
"--dep" => dep = true,
171-
"-v" | "--verbose" => verbose = true,
172-
_ => break, // not for us
160+
let mut many_seeds = None;
161+
while let Some(arg) = args.peek().and_then(|s| s.to_str()) {
162+
if arg == "--dep" {
163+
dep = true;
164+
} else if arg == "-v" || arg == "--verbose" {
165+
verbose = true;
166+
} else if arg == "--many-seeds" {
167+
many_seeds = Some(0..256);
168+
} else if let Some(val) = arg.strip_prefix("--many-seeds=") {
169+
let (from, to) = val.split_once("..").ok_or_else(|| {
170+
anyhow!("invalid format for `--many-seeds`: expected `from..to`")
171+
})?;
172+
let from: u32 = if from.is_empty() {
173+
0
174+
} else {
175+
from.parse().context("invalid `from` in `--many-seeds=from..to")?
176+
};
177+
let to: u32 = to.parse().context("invalid `to` in `--many-seeds=from..to")?;
178+
many_seeds = Some(from..to);
179+
} else {
180+
break; // not for us
173181
}
174182
// Consume the flag, look at the next one.
175183
args.next().unwrap();
176184
}
177-
Command::Run { dep, verbose, flags: args.collect() }
185+
Command::Run { dep, verbose, many_seeds, flags: args.collect() }
178186
}
179187
Some("fmt") => Command::Fmt { flags: args.collect() },
180188
Some("clippy") => Command::Clippy { flags: args.collect() },
181189
Some("cargo") => Command::Cargo { flags: args.collect() },
182190
Some("install") => Command::Install { flags: args.collect() },
183-
Some("many-seeds") => Command::ManySeeds { command: args.collect() },
184191
Some("bench") => Command::Bench { benches: args.collect() },
185192
Some("toolchain") => Command::Toolchain { flags: args.collect() },
186193
Some("rustc-pull") => {

src/tools/miri/miri-script/src/util.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
use std::ffi::{OsStr, OsString};
2+
use std::ops::Range;
23
use std::path::{Path, PathBuf};
4+
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
5+
use std::thread;
36

47
use anyhow::{anyhow, Context, Result};
58
use dunce::canonicalize;
@@ -189,4 +192,54 @@ impl MiriEnv {
189192

190193
Ok(())
191194
}
195+
196+
/// Run the given closure many times in parallel with access to the shell, once for each value in the `range`.
197+
pub fn run_many_times(
198+
&self,
199+
range: Range<u32>,
200+
run: impl Fn(&Shell, u32) -> Result<()> + Sync,
201+
) -> Result<()> {
202+
// `next` is atomic so threads can concurrently fetch their next value to run.
203+
let next = AtomicU32::new(range.start);
204+
let end = range.end; // exclusive!
205+
let failed = AtomicBool::new(false);
206+
thread::scope(|s| {
207+
let mut handles = Vec::new();
208+
// Spawn one worker per core.
209+
for _ in 0..thread::available_parallelism()?.get() {
210+
// Create a copy of the shell for this thread.
211+
let local_shell = self.sh.clone();
212+
let handle = s.spawn(|| -> Result<()> {
213+
let local_shell = local_shell; // move the copy into this thread.
214+
// Each worker thread keeps asking for numbers until we're all done.
215+
loop {
216+
let cur = next.fetch_add(1, Ordering::Relaxed);
217+
if cur >= end {
218+
// We hit the upper limit and are done.
219+
break;
220+
}
221+
// Run the command with this seed.
222+
run(&local_shell, cur).map_err(|err| {
223+
// If we failed, tell everyone about this.
224+
failed.store(true, Ordering::Relaxed);
225+
err
226+
})?;
227+
// Check if some other command failed (in which case we'll stop as well).
228+
if failed.load(Ordering::Relaxed) {
229+
return Ok(());
230+
}
231+
}
232+
Ok(())
233+
});
234+
handles.push(handle);
235+
}
236+
// Wait for all workers to be done.
237+
for handle in handles {
238+
handle.join().unwrap()?;
239+
}
240+
// If all workers succeeded, we can't have failed.
241+
assert!(!failed.load(Ordering::Relaxed));
242+
Ok(())
243+
})
244+
}
192245
}

0 commit comments

Comments
 (0)