Sub topic 13
Writing tests that run well under Miri
Miri executes your tests inside an interpreter, so a test suite that takes a second natively can take minutes. This chapter shows how to shape tests so Miri finishes in reasonable time and still checks the unsafe code that matters.
This chapter assumes you can run cargo miri test (covered earlier), read a Miri error report, and write basic unsafe code with raw pointers and MaybeUninit.
What makes a test Miri-friendly
A good Miri test has four properties:
- It exercises the unsafe code directly. Miri only checks code paths that actually run, so a test that never reaches your
unsafeblock proves nothing. - It is small. Miri is much slower than native execution, so a handful of iterations usually exposes the same bugs as thousands.
- It is deterministic. It does not depend on the clock, the file system, the network, or the environment, all of which Miri restricts by default.
- It uses types that make bugs visible. Heap-owning types such as
String,Vec, andRcturn double drops, leaks, and use-after-free into reportable errors. Plain integers often hide them.
A worked example
The following library type stores up to N values in an array of MaybeUninit<T>. Put it in src/lib.rs of a fresh library crate.
use std::mem::MaybeUninit;
pub struct FixedStack<T, const N: usize> {
items: [MaybeUninit<T>; N],
len: usize,
}
impl<T, const N: usize> FixedStack<T, N> {
pub fn new() -> Self {
Self {
items: std::array::from_fn(|_| MaybeUninit::uninit()),
len: 0,
}
}
pub fn push(&mut self, value: T) -> Result<(), T> {
if self.len == N {
return Err(value);
}
self.items[self.len].write(value);
self.len += 1;
Ok(())
}
pub fn pop(&mut self) -> Option<T> {
if self.len == 0 {
return None;
}
self.len -= 1;
// SAFETY: slot `len` was written by `push` and has not been read since.
Some(unsafe { self.items[self.len].assume_init_read() })
}
}
impl<T, const N: usize> Drop for FixedStack<T, N> {
fn drop(&mut self) {
while self.pop().is_some() {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::rc::Rc;
#[cfg(miri)]
const ROUNDS: usize = 20;
#[cfg(not(miri))]
const ROUNDS: usize = 10_000;
#[test]
fn push_pop_strings() {
let mut s: FixedStack<String, 4> = FixedStack::new();
for i in 0..ROUNDS {
s.push(i.to_string()).unwrap();
assert_eq!(s.pop(), Some(i.to_string()));
}
}
#[test]
fn full_stack_returns_the_value() {
let mut s = FixedStack::<String, 2>::new();
s.push("a".into()).unwrap();
s.push("b".into()).unwrap();
assert_eq!(s.push("c".into()), Err("c".to_string()));
}
#[test]
fn drop_releases_remaining_items() {
let marker = Rc::new(());
{
let mut s = FixedStack::<Rc<()>, 3>::new();
s.push(marker.clone()).unwrap();
s.push(marker.clone()).unwrap();
assert_eq!(Rc::strong_count(&marker), 3);
}
assert_eq!(Rc::strong_count(&marker), 1);
}
#[test]
#[cfg_attr(miri, ignore)]
fn large_workload() {
let mut s: FixedStack<u64, 1024> = FixedStack::new();
for i in 0..1024 {
s.push(i).unwrap();
}
assert_eq!(s.pop(), Some(1023));
}
}Run it with cargo +nightly miri test. Each test earns its place:
push_pop_stringsusesStringrather thanu32. Ifpopread a slot twice, Miri would report a double free, which an integer would never show. Its loop is bounded byROUNDS, which is 20 under Miri and 10,000 natively.full_stack_returns_the_valuecovers the early-return path, wherepushmust hand the value back without writing it.drop_releases_remaining_itemschecks thatDropdrops only the initialized slots. If it dropped allNslots, Miri would flag reading uninitialized memory. TheRccount gives you a native assertion on the same property.large_workloadis a native stress test that adds little under Miri, so#[cfg_attr(miri, ignore)]skips it. The test still runs in a normalcargo test.
Shrinking and skipping work
Two attributes handle most cases.
| Tool | Use it when | Effect |
|---|---|---|
| `#[cfg(miri)]` / `#[cfg(not(miri))]` | A constant or code path should differ under Miri | Compiles one version only when running under Miri |
| `#[cfg_attr(miri, ignore)]` | A test is too slow or cannot work under Miri | Test is marked `ignored` under Miri only |
| `cargo miri test name` | You want one test or a subset | Standard test-name filtering applies |
| `cargo miri test -- --skip slow` | You want to exclude by name | Passes the argument to the test harness |
Prefer shrinking a workload to ignoring a test. An ignored test is invisible to Miri, so anything unsafe it touches goes unchecked. Ignore a test only when it cannot run under Miri at all, or when a smaller test already covers the same unsafe code.
Isolation: files, clocks, and the environment
By default Miri runs in isolation. Operations that reach outside the interpreted program fail with an "unsupported operation" error. This covers reading files, reading environment variables, and getting the current time or randomness from the host.
You have two options:
- Remove the dependency from the test. Pass data in as a
&[u8]or an in-memoryCursorinstead of opening a file. This is the best choice because the test also becomes faster and more portable. - Turn isolation off. Set
MIRIFLAGS="-Zmiri-disable-isolation"so the program can use the host file system and clock.
MIRIFLAGS="-Zmiri-disable-isolation" cargo +nightly miri testForeign functions and unsupported code
Miri interprets Rust, so it cannot call arbitrary C functions. A test that calls into a C library through extern "C" fails when it reaches the call. Common fixes:
- Put the foreign call behind a trait or a function, and substitute a pure-Rust fake with
#[cfg(miri)]. - Ignore the specific test with
#[cfg_attr(miri, ignore)]and rely on native testing for that boundary.
Keep the unsafe logic that surrounds the foreign call testable on its own, such as buffer management and pointer arithmetic. That logic is where Miri finds bugs.
Concurrency tests
Miri runs threads, but it schedules them deterministically for a given seed. One run therefore explores one interleaving. A data race can hide in a run that happens to schedule threads in a safe order.
Run the same test under many seeds:
MIRIFLAGS="-Zmiri-many-seeds=0..16" cargo +nightly miri testThe -Zmiri-many-seeds flag reruns the whole test command once per seed in the range and stops at the first failure. If a run fails, the report names the failing seed. Replay that seed with -Zmiri-seed=<N> while you debug. Keep concurrent tests small, with two or three threads and a few operations each. More threads multiply the cost of every seed.
Leaks and other end-of-run checks
Miri reports memory that is still allocated when the program ends, if nothing reachable from a static still points to it. This makes leak bugs in unsafe code visible. If a test leaks on purpose, for example with Box::leak to get a 'static reference, you can silence the report with -Zmiri-ignore-leaks. Use that flag sparingly, because it also hides real leaks everywhere else.
Randomized and property-based tests
Randomized tests multiply Miri's cost, so shrink their case counts under Miri with the same cfg(miri) technique. Libraries that persist failures to disk can also trip the isolation rules, so check their documentation for an option to turn persistence off. A few well-chosen cases under Miri, plus thousands natively, is a sound split.
Common mistakes
- Testing only with integers. Bugs such as double drops and leaks need types with destructors.
- Never reaching the unsafe path. A passing Miri run only covers the code that executed. Check that your tests hit the branches containing
unsafe, including error and edge cases like a full or empty container. - Ignoring too much. Each
cfg_attr(miri, ignore)is a blind spot. Review them periodically. - Reading a pass as proof. A clean run means no problem was found on the paths and seeds that ran. A later chapter covers what Miri cannot detect.
Exercise
A test pushes 100,000 u8 values into a container that uses unsafe code, then checks the length. It takes over ten minutes under Miri. Name two changes that keep the unsafe code checked, and explain why replacing the values with String would also improve the test's bug-finding power.
Show answer
First, shrink the workload under Miri with a #[cfg(miri)] constant (for example 50 iterations instead of 100,000) and keep the large count under #[cfg(not(miri))]. Second, add a separate small test for the edge cases, such as an empty or full container, so the unsafe branches run even with few iterations. Using String helps because it owns heap memory and has a destructor. A double drop, a use-after-free, or a leak in the container then becomes an error Miri reports, whereas a u8 has no destructor and hides those bugs.