The problem
A simulator that tests a model of your system finds the bugs of the model. When the test runs a copy of the code, or the code with test-only hooks, the copy and the shipped code go apart. After some time, the test tests itself.
The technique
The code does all its I/O through providers: the time, the tasks, the network, the disk and the random numbers. In production, the Tokio providers do real I/O. In a simulation, the simulated providers do it on one thread, and a seed decides each delay and each fault. The code above the providers is the same compiled code.
Two marks let the code help the simulator. buggify!() is a rare choice that is legal, for example "drop this reply". hint!("…") names a moment where a reboot hurts most, and attrition can reboot the process there. In production both are inert: buggify!() is false and hint! resolves at once.
The live run
Each row is one line of the register's server. The middle column is what it does in production. The right column counts what it did in this run, up to the cursor. At 364 ms the simulator reboots 10.0.1.1 at its first hint, between the write and the sync. Select a hint and find the next seed that strikes there.
| line of register.rs | in production | in this simulation |
|---|---|---|
.open(FILE, OpenOptions::new().read(true).write(true).create(true)) | TokioStorageProvider opens a file on the real disk. | not yet |
result = listener.accept() => result, | TokioNetworkProvider accepts a TCP connection. | not yet |
.write_at(sector * SECTOR as u64, &record) | The kernel copies the record to its page cache. | not yet |
hint!("register: record written, not synced").await; | Resolves at once. It draws nothing and asks no one. | not yet |
file.sync_all().await.map_err(|e| io_error(&e))?; | fsync: the record is on the disk. | not yet |
hint!("register: write durable, ack not sent").await; | Resolves at once. | not yet |
if buggify!() { | Always false. No draw. | not yet |
let _ = stream.write_all(&reply.encode()).await; | TokioNetworkProvider sends the reply. | not yet |
The code
The server gets its providers from its context. It does not know if they are real or simulated:
async fn run(&mut self, ctx: &SimContext) -> SimulationResult<()> {
let storage = ctx.storage();
let file = storage
.open(FILE, OpenOptions::new().read(true).write(true).create(true))
.await
.map_err(|e| io_error(&e))?;
storage.sync_dir(".").await.map_err(|e| io_error(&e))?;
let (mut version, mut value) = Self::load(&file).await?;
assert_sometimes!(version > 0, "a server boots with a stored value");
tracing::info!(version, "server_boot");
let listener = ctx.network().bind(ctx.my_ip()).await?;The register runs only in the simulator, so it gets its providers from SimContext. A library that ships takes P: Providers and gets TokioProviders in production. The Guide chapter shows how a crate keeps the simulator out of its release build.