Deterministic simulation testing for distributed systems in Rust.
We write the system once against provider traits. In tests, the simulator runs it on logical time, one seeded random stream and a simulated network and disk, and injects faults. In production, the same code runs on Tokio. One seed gives one exact execution, so every failure replays bit for bit.
Moonpool follows FoundationDB's simulation testing, with assertion and exploration ideas from Antithesis.
Note: Moonpool is under active development. It is used to find real bugs in distributed systems, and its API still changes between releases.
Shipped code is never wrapped in a simulation variant. There is no SimDisk,
no SimMachine and no test-only hook in the product.
- Code depends on provider traits, usually through one
Providersbundle:TokioProvidersin production,SimProvidersin tests. - Code names interesting moments with
hint!("label").await. In production it is a no-op. In simulation the simulator decides whether to strike there, for example by rebooting the process. - Code forces its own rare branches with
buggify!,buggify_with_prob!andbuggify_named!. They are inert outside a simulation.
A server process accepts connections. A client workload connects to it
under swarm network chaos. Ten seeds run in milliseconds of wall time. The
same code is the crate-level doc test of moonpool, so it compiles against
the current API.
[dev-dependencies]
moonpool = "0.9"
async-trait = "0.1"use std::time::Duration;
use async_trait::async_trait;
use moonpool::prelude::*;
use moonpool::{Chaos, ChaosMode, SimulationResult, assert_always, assert_sometimes};
/// The system under test. A fresh instance boots on every (re)start.
struct Server;
#[async_trait]
impl Process for Server {
fn name(&self) -> &str {
"server"
}
async fn run(&mut self, ctx: &SimContext) -> SimulationResult<()> {
let listener = ctx.network().bind(ctx.my_ip()).await?;
loop {
// The deterministic select!: the branch order comes from the seed.
moonpool::select! {
accepted = listener.accept() => drop(accepted),
() = ctx.shutdown().cancelled() => return Ok(()),
}
}
}
}
/// The test driver. It survives server reboots and judges the run.
struct Client;
#[async_trait]
impl Workload for Client {
fn name(&self) -> &str {
"client"
}
async fn run(&mut self, ctx: &SimContext) -> SimulationResult<()> {
let servers = ctx.topology().all_process_ips().to_vec();
assert_always!(servers.len() == 1, "one server process per seed");
for _ in 0..20 {
// Bound every step with simulated time, so no fault wedges the client.
let attempt = ctx
.time()
.timeout(Duration::from_millis(500), ctx.network().connect(&servers[0]))
.await;
assert_sometimes!(matches!(attempt, Ok(Ok(_))), "client connects");
let _ = ctx.time().sleep(Duration::from_millis(50)).await;
}
Ok(())
}
}
#[test]
fn server_accepts_under_chaos() -> Result<(), moonpool::SimulationError> {
let report = SimulationBuilder::new()
.processes(1, || Box::new(Server))
.workload(Client)
.enable_chaos([Chaos::Network(ChaosMode::Swarm)])
.set_iterations(10)
.run()?;
assert_eq!(report.failed_runs, 0);
Ok(())
}crates/moonpool/examples/retrying_worker.rs
shows the other half: one function that runs on TokioProviders in main
and under the simulator in its own #[test].
- Six provider traits:
TimeProvider,TaskProvider,NetworkProvider,RandomProvider,StorageProviderandSystemProvider, bundled byProviders. TokioProvidersfor production, behind thetokio-providersfeature.SimProvidersfor simulation.SimulationBuilder::with_providersswaps in your own providers.- Local (non-
Send) forms of the traits for thread-per-core runtimes:LocalStorageProvider,LocalNetworkProvider,LocalTimeProvider,LocalTaskProvider, theLocalProvidersbundle, andThreadProviders(a local bundle with a local task slot). Tokio and the simulator implement them too, so local code runs under simulation. - A compio backend (features
compio-*, off by default): io_uring storage (direct I/O and atomic appends on Linux) and networking for thread-per-core code, bundled byCompioProviders. Resolverforhost:portlookups, outside the bundle:TokioResolverorCompioResolverin production,ScriptedResolverin simulation.SystemProviderreads cumulative CPU and disk counters (getrusage,/proc/stat,/proc/diskstats). The simulator keeps deterministic disk counters per process.select!: tokio's macro in production, and a seeded branch offset in simulation (moonpool_sim::select!).
- Deterministic single-threaded executor. Task order,
select!offsets and every fault coin are draws on one seeded stream. Process(the system under test, rebooted with fresh memory) andWorkload(the test driver, withsetup,runandcheck).SimulationBuilder:processeswith fixed or random counts,clusterwith datacenter, zone and machine locality,tags,workload,workload_factoryandworkloads;seed_plan, one hook per seed that sets a group's count, its attrition budget and its outages together.ctx.deployment(): a workload changes the deployment mid-run.spawn,spawn_inandspawn_groupboot new processes,retirestops one for good, and topology queries and chaos victim pools follow the live membership. An operator is an ordinary workload (max_spawnscaps it).spawnable_groupdeclares a group spawned later, so a gray failure or an outage can name it.- Iteration control:
set_iterations,until_coverage_stable,set_debug_seeds,run_time_budget,replay_timeline,wall_clock_budget(stop a campaign after a wall-clock time),corpus_file(replay a seed corpus first, keep the seeds that grew coverage). check_determinismruns each seed twice and fails it when the draw sequences differ.SimulationReportwith failing seeds, assertion and coverage violations, exploration results and application metrics.
enable_chaostakesChaossurfaces, each sampled per seed byChaosMode::RandomorChaosMode::Swarm.Chaos::Network: latency, clogs, partitions, black holes, bit flips, random closes, connect failures, clock drift and per-pair latency.link_latencysets latency by locality.Chaos::Storage: corruption, EIO, misdirected and phantom writes, sync failures, short transfers, lost directory entries, crash damage, degradation and disk failure. The crash model is bounded by sync barriers, with an oracle for lost synced writes. Each disk has a queue, a sync pays for the bytes it flushes, andopen,rename,deleteandsync_dirare delayed disk operations, so a crash can land between arenameand itssync_dir.Chaos::Attrition: graceful, crash and wipe reboots under amax_deadbudget, scoped per process, machine, zone or datacenter. An optional wipe budget makes wipes roll: a wiped process stays unhealed until the harness signals it healed, and a wipe past the budget becomes a crash. Replicated fault patterns count an unhealed wipe as a lost copy, and a wipe drawn while another domain of its group holds damage becomes a crash.Chaos::Outage: a correlated outage of whole process groups, with an optional straggler. AnOutageVetolets the harness defer it.- A
KillPolicy, FoundationDB'scanKillProcesses: the harness answers every kill and wipe before it runs, and may keep the disk or turn the kill into an in-place restart. Chaos::CpuandChaos::GrayFailure: a CPU model per process and slow but alive machines. Workloads readSimContext::slowness.Chaos::Clocks: each process boot has its ownnow(), which starts near zero, and each machine's clock runs fast or slow, sleeps included.Chaos::BuggifyKnobsmoves network and storage knobs to extremes.SimContext::crash_selfandSelfCrash: a process crashes itself, as a power loss would.- Aimed storage faults: owner-scoped, byte-range targeting through
LayoutRegionandFaultFocus, andreplicated_storage_faultswith minority, striped and rolling patterns that never hit every replica. - Full disks:
set_disk_capacitygives a disk a size (optionally amplified), so growth past it fails withENOSPCand a delete or a truncate frees space.SystemSample::spacereports the free bytes (statvfsin production). - Custom faults:
fault_factorywith aFaultInjectorand itsFaultContext.chaos_durationcloses the chaos window and opens a quiet recovery tail;chaos_until_run_endskeeps chaos on for the whole run phase and runscheck()on the live processes after it.
hint!("label").awaitnames a moment. The simulator may reboot the caller there, under the seed's attrition regime and an optionalHintVeto, which also guards a per-process regime's timed reboots.buggify!,buggify_with_prob!,buggify_fault_with_prob!,buggify_pick!andbuggify_range!: two-phase activation, once per run and then per call.buggify_knob!(inmoonpool-sim) for tunables.buggify_named!withset_activationfor per-seed scenarios. Ahint!is keyed by its label too, soset_activationforces it for a seed.cpu_chargereports CPU work to the CPU model, inert elsewhere.- Swarm testing: each seed enables a random subset of fault families and
workload operations (
ChaosMode::Swarm,network_fault_mask,storage_fault_mask,swarm_operationswithswarm_op_enabled). We prefer one workload with swarm testing over many separate workloads.
Modelholds pure state machines, their disks and the oracles.Walkdraws a schedule from a seed with no executor, no network and no clock: deliver, drop, duplicate, reorder, crash, restart, or a move of the model.- A chaos phase, a quiet tail and a convergence check for each seed.
Safety is
check()after every delivery. Liveness isconverged(). - A failing seed prints its log and replays alone
(
MOONPOOL_WALK_SEED=17).Harnessscripts a schedule by hand. sometimes!coverage over the campaign, seededbuggify!, swarm testing, andtry_runto prove that a mutant is caught.Walk::explore: coverage-driven exploration. A run that passes a site for the first time, or covers new code edges (edge_coverage), is branched, and each child replays it up to that step before it draws a new schedule. A branched run is aTimelineand replays alone (MOONPOOL_WALK_TIMELINE=17@120:ff).Cx::recordandRun::eventsgive the trace of a run to a checker.
- Nine Antithesis-style macros. Boolean:
assert_always!,assert_always_or_unreachable!,assert_sometimes!,assert_reachable!,assert_unreachable!. Numeric:assert_always_less_than_or_equal_to!andassert_sometimes_greater_than!. Compound:assert_sometimes_all!andassert_sometimes_each!. - They record and never panic. Always-failures are bugs. Sometimes-sites that never fire are coverage gaps.
reachable!andsometimes!probes for shipped code.- Events and invariants through plain
tracing:SimulationLayercaptures the timeline,TraceQueryreads it, andinvariant/invariant_fncheck it after every simulation step. Simulator faults appear in the same timeline asSimFaultEvents.
enable_explorationwithExplorationConfig: when an assertion discovers something new, the explorer keeps a replayable recipe and schedules bounded continuations from it.- A fixed pool of forked workers (
workers: 0runs in process), a frontier queue, exemplars per semantic state, andBugRecipereplay. - Optional code-coverage guidance through sancov instrumentation, enabled
by
cargo xtask.
- Raw TCP over
NetworkProvider: test your own protocol byte for byte. moonpool-rpc: typed dynamic endpoints, delivery modes, reply streams, per-endpoint admission queues, buggify points inside the runtime,#[service]derive and TLS (mutual TLS included, simulated bysim-rpc-tls).moonpool-rpc-simholds its simulation campaigns.moonpool-hyper: hyper 1.x, tonic gRPC and axum on the providers, with a reconnecting h2 channel and a per-connection server.
StorageProviderandStorageFile: positioned I/O,sync_allandsync_data, a durable positioned write (write_at_durable, onepwritev2(RWF_DSYNC)on Linux),sync_dir, andOpenOptions::direct_iowithIoConstraintsandAlignedBuf. Zero-copy positioned I/O: the*_alignedmethods move an ownedAlignedBufto the kernel and back, where the borrowed form copies through a bounce buffer.BlockFileadds block addressing, andFileCursoradds sequential reads and writes: a file has no stream I/O of its own.moonpool-journal: a position-keyed CLSTORE journal that tells a crash from corruption and names the damaged entry. Positions in any order,Batch::fits/fits_another,Journal::peek_meta, metadata repair, ambiguous tails, two faults on a witnessed batch or a rolled-back metainfo refused as evidence,Journal::verify_recordsfor a caller's scrub of the persist records, layout regions for aimed faults,hint!points inside each commit, and recycled segments: a dead segment's file becomes the next one with a header write and a rename, and a new segment is allocated (StorageFile::allocate), never zero-filled. It is written against the local provider traits, so it runs on compio as well as Tokio and the simulator, and staysSendover aSendprovider. Batches, headers and metainfo are encoded in place in aligned buffers and written with no copy.
metrics_factorygives each node aMetricsSource.PrometheusSourcerecords every change on the simulated clock.- The report folds every node's counters, gauges and histograms across the successful seeds, and keeps each seed's exact series.
moonpool-simwith--no-default-featurescompiles forwasm32-unknown-unknown.moonpool-wasm-demoruns a replicated register in the browser, the same run as natively: it is the engine of every live run of the website.
cargo xtask sim list | run <filter> | run-allruns the simulation binaries (moonpool-sim-examples, explorer scenarios, RPC campaigns).moonpool-calibratemeasures a real disk and network and emitsLatencyDistributionconstants for the simulator.
| Crate | Purpose | Published |
|---|---|---|
moonpool |
Facade: features sim, tokio, hyper, prometheus, rpc, rpc-derive, rpc-tls, rpc-tls-pki |
yes |
moonpool-core |
Provider traits, TokioProviders, storage and metrics types |
yes |
moonpool-sim |
Simulator, runner, chaos, assertion macros | yes |
moonpool-buggify |
buggify!, hint!, cpu_charge; zero dependencies |
yes |
moonpool-assertions |
Assertion accounting; zero dependencies, wasm-clean | yes |
moonpool-tla |
Check a run's trace against a TLA+ spec with TLC, after the run or live in chunks; zero dependencies | yes |
moonpool-explorer |
Frontier exploration with forked workers (Linux, macOS) | yes |
moonpool-hyper |
hyper 1.x, tonic and axum over the providers | yes |
moonpool-prometheus |
Prometheus registry in the simulation report | yes |
moonpool-rpc |
Typed dynamic-endpoint RPC | yes |
moonpool-rpc-derive |
#[service] interface generation |
yes |
moonpool-journal |
CLSTORE journal: crash vs. corruption | yes |
moonpool-walk |
Seeded random walk over sans-I/O state machines; no simulator | yes |
moonpool-rpc-sim |
RPC simulation campaigns and oracles | no |
moonpool-sim-examples |
Example simulations (maze, dungeon, axum, tonic, journal) | no |
moonpool-wasm-demo |
Website run engine (wasm) | no |
moonpool-calibrate |
Latency calibration tool | no |
xtask |
Simulation binary runner | no |
Keep the simulator and the explorer out of the release binary:
[dependencies]
moonpool = { version = "0.9", default-features = false, features = ["tokio"] }This pulls the provider traits and TokioProviders with real TCP and
filesystem implementations, without moonpool-sim, moonpool-explorer or
the fork machinery. Add hyper, prometheus or rpc when the application
uses them. A crate that only marks fault sites can depend on
moonpool-buggify alone.
nix develop # pinned toolchain and tools
nix develop --command cargo nextest run
nix develop --command cargo xtask sim run-all- The site: a live run of a seed, the quick start and The Sim Book, the user guide from philosophy to fault reference.
- The techniques: one page per technique, each with a live run; the playground runs any seed of the site's small system in your browser; the extras describe moonpool-journal and moonpool-rpc byte by byte.
- API documentation on docs.rs:
moonpool,moonpool-core,moonpool-sim,moonpool-buggify,moonpool-assertions,moonpool-walk. - Repository
Apache 2.0