simloom
Deterministic simulation testing for Python's asyncio.
Find the race before it ships. Replay it forever from a seed.
Your async code is tested one interleaving at a time — the polite one your laptop happened to schedule. Races ship. Flakes get retried. "Works on my machine" is the state of the art.
simloom runs your unmodified asyncio program inside a fully simulated world — a seeded scheduler that owns every interleaving, a virtual clock, an in-memory network with injectable latency, loss, partitions, and crashes — and explores thousands of hostile schedules looking for the one that breaks your invariants. It doesn't just find crashes: it asserts safety and liveness properties, proves correctness by exhaustive systematic search, and catches wrong answers (a store that returns a stale or impossible read) with serializability checking. When it finds a problem, it hands you a seed that replays the failure byte-for-byte, forever, shrinks it to the minimal schedule that still triggers the bug, and lets you walk the causal trace of what woke what.
FAILED test_lease_exclusivity — simloom found a failing universe
seed: 17 (re-run: pytest -k lease --simloom-seed=17)
error: AssertionError: two holders of an exclusive lease
shrunk: 31 draws → 29, schedule deviations 25 → 1 (106 candidate runs)
minimal schedule: FIFO everywhere except:
draw #0: sched.pick = 1 (of 4)
artifacts: .sim/failures/test_lease_exclusivity-seed17.tape.json, …
The entire bug, above, is "one callback ran out of order, once." No more staring at a flake that reproduces every thousandth CI run.
Install
pip install simloom # or: uv add simloom
Python 3.12+. Zero runtime dependencies. The pytest plugin loads automatically.
Quickstart
Write an ordinary async test, decorate it, and let simloom explore the schedule space:
import asyncio
import simloom
@simloom.test(runs=2000) # explores 2000 schedules; pytest collects this
async def test_counter_is_atomic():
state = {"value": 0}
async def worker():
for _ in range(3):
current = state["value"]
await asyncio.sleep(0) # a scheduling point — the race lives here
state["value"] = current + 1
await asyncio.gather(*(worker() for _ in range(3)))
assert state["value"] == 9 # a plain assert: it fires under exploration
pytest # finds the lost-update race, shrinks it, prints the seed
pytest --simloom-seed=42 # replay one exact universe
Need a distributed system? Ask for a world and you get hosts, a network, and faults:
@simloom.test(runs=5000)
async def test_leader_election(world):
nodes = [world.host(f"n{i}") for i in range(5)]
for h in nodes:
h.spawn(lambda h=h: run_node(h, peers=nodes)) # your real, unmodified asyncio code
world.net.partition(nodes[:2], nodes[2:]) # faults are first-class
await world.sleep(30) # virtual seconds — wall time ≈ 0
world.net.heal()
nodes[0].crash() # a real power cut: no finally blocks
nodes[0].restart() # comes back against fsynced disk only
await world.until(lambda: exactly_one_leader(nodes), timeout=120)
Beyond crashes
Assert what should hold, prove it can't be violated, and catch wrong answers:
@simloom.test(runs=5000)
async def test_lease_safety(world):
cluster = start_cluster(world)
# safety: never two leaders. liveness: one eventually emerges.
world.always("≤1 leader", lambda: sum(n.is_leader for n in cluster) <= 1)
world.eventually("a leader", lambda: any(n.is_leader for n in cluster), within=120)
await world.sleep(300)
@simloom.test(systematic=True, max_delays=3) # exhaustive, not sampled
async def test_critical_section():
... # passes ⇒ a bounded PROOF of correctness
@simloom.test(runs=5000)
async def test_store_is_serializable(world):
await run_transactions(world) # records ops into world.history
world.assert_serializable() # finds lost updates / write skew, with the cycle
And once it finds something, replay and walk it:
pytest --simloom-seed=17 -k lease # replay the exact failing universe
simloom trace failure.jsonl --step 42 # reconstruct state + the happens-before stack
simloom diff run_a.jsonl run_b.jsonl # first divergence between two universes
Why this didn't exist before
Rust has loom,
turmoil,
madsim, and
shuttle. .NET had
Coyote. FoundationDB built a company-defining
simulator; Antithesis sells the methodology at the hypervisor
level. Python — where a huge share of backend glue and agent orchestration is written —
had nothing.
And asyncio is structurally perfect for it: every interleaving decision happens at an
await, under a replaceable event loop. simloom swaps in a deterministic one — no
forked interpreter, no hypervisor, no recompilation. Because the ecosystem (aiohttp,
httpx, redis, the streams API) bottoms out in loop primitives, real, unmodified
libraries run inside the simulation. Our CI runs an unmodified aiohttp HTTPS server
against an unmodified aiohttp client over a memory-BIO TLS handshake, and an unmodified
redis.asyncio.Redis against an in-sim Redis — all over the simulated network, with
faults injected, replayable byte-for-byte from a seed.
What you get
Run it. Your real asyncio code, unchanged, inside the simulation.
- 🎲 Seeded scheduling — a single choice tape (the Hypothesis trick, applied to schedules) drives every decision. One seed → one exact universe.
- ⏱ Virtual time — an hour of simulated
asyncio.sleeptraffic runs in milliseconds; opt-in patching makestime.time()and the stdlib RNG tape-driven too, so an unmodified library that timestamps or rolls a random timeout replays byte-for-byte. - 🌐 A simulated network — in-memory streams (loss modeled as TCP retransmit delay — bytes never corrupt), UDP datagrams with real loss/reorder/duplication, partitions, asymmetric per-link latency/loss shaping, resets, and TLS in-sim (memory-BIO SSL, so aiohttp HTTPS just works).
- 💥 Honest crashes & disk —
host.crash()is a power cut: tasks stop with nofinallyblocks, unsynced disk writes are lost or torn, peers see resets. - 🧩 Stand-in services —
world.run_service(...)gives you an in-sim Redis (SET/GET, WATCH/MULTI/EXEC, for unmodified redis-py) and an in-sim NATS broker (pub/sub, wildcards, queue groups, for unmodified nats-py) — with wire faults applied, and queue-group delivery choices explored from the tape.
Break it. Explore the schedules and faults your laptop never will.
- 🔬 Fault injection —
simloom.sometimes("drop_cache")is tape-driven inside the sim and a constantFalsein production. Annotate rare branches; explore them. - 🧭 Pluggable search — uniform random walk,
pct:auto(auto-tuned Probabilistic Concurrency Testing that finds deep-ordering and starvation bugs random walk never hits), andsimloom.soak(resumable, shardable continuous exploration).
Check it. Assertions far past "didn't crash."
- 🛡 Safety & liveness oracles —
world.always("one leader", …),world.eventually("elects a leader", …, within=120),world.leads_to(…), plus a livelock detector and replica-convergence checks. - ✅ Prove it —
@simloom.test(systematic=True)switches from sampling seeds to exhaustive delay-bounded model checking: it finds a deep interleaving bug deterministically, or passes as a bounded proof of correctness. - 🧾 Find wrong answers — an Elle-style serializability checker
(
world.check_serializable) reports the cyclic read/write dependency behind a lost update, and a Wing-Gong linearizability checker (world.check_linearizable) catches the stale read serializability would excuse — including may-or-may-not-have- applied writes from crashed clients.
Reproduce & debug it.
- 🪓 Automatic shrinking — failures reduce to the minimal schedule deviation, with a replayable artifact on disk.
- 🔁 Determinism guarantees — a per-test self-check (run twice, locate the first
diverging event),
PYTHONHASHSEEDauto-pin, and a queryable boundary registry. - 🕰 Causal trace & time travel — record with
causal=Trueand walk it:simloom trace LOG --step Nreconstructs state and the happens-before stack that woke it;simloom diff A Bfinds the first divergence between two universes. Record withdebug=Trueand query everything:simloom debug LOG --var balanceprints every value a local variable ever held — a lost update's double stale read is one query. - 🚨 Escape detection — touch a real socket, signal, subprocess, or (un-patched) wall
clock from inside the sim and you get an
EscapedSimulationErrorat the exact call site instead of silent nondeterminism.
It finds real bugs
A multi-year CPython race. Pre-3.12 asyncio.wait_for could swallow a delivered
cancellation when the inner future completed in the same window as the cancel
(bpo-42130). In production it took an
exact wall-clock collision; under simloom the timeout boundary is just another
scheduling choice, so exploration finds the interleaving from a seed and replays it
exactly. The modern implementation survives the identical torture. → examples/bpo42130.py
The canonical demo. A toy Raft over the simulated network — persisted term/votedFor,
JSON-RPC, the works — tortured with partitions, crashes, and restarts. Plant the classic
double-vote bug and exploration elects two leaders in one term in ~1 seed of 5; the fixed
version survives, with coverage counters proving the faults actually fired.
→ examples/toy_raft.py
The harness is tested harder than your code
A correctness tool's worst failure mode is false confidence, so simloom attacks itself the way it attacks your code. Beyond the 10,000-seed determinism torture, every CI run:
- differentially validates both consistency checkers against independent brute-force references (the offline campaign — 450k+ serializability and 320k+ linearizability histories — found and fixed four checker incompleteness bugs before you ever saw them);
- fuzzes determinism with generated programs — random workers, queues, locks,
cancellation, fault scripts against hosts and the network — every one must satisfy
run == run == replaybyte-for-byte (20k programs + 2k fault-scripted worlds offline); - checks semantics parity against stock asyncio — programs with interleaving- independent results must behave identically on the real loop (4k programs offline);
- cross-validates every
proven_correctclaim against random exploration, runs the determinism-critical suites withPYTHONHASHSEEDunpinned, property-tests the shrinker, and asserts every API misuse is a clean, named error.
Honesty first
A determinism claim is only as good as its disclosed limits. simloom raises a loud error
when your code reaches outside the simulation, and docs/determinism.md
states exactly what is and isn't deterministic — now machine-readable via
simloom.boundary(). Known boundaries: blocking C-extension I/O (psycopg2, requests,
grpc's C core) can't run in-sim; a from time import … alias or the C-accelerated
datetime.now() isn't redirected by the clock patch; real subprocesses and external
servers need stand-ins. None of these fail silently — and the per-test determinism
self-check locates anything that slips through.
Status
Alpha, and built in the open. The deterministic core, the simulated world and fault matrix (streams, UDP, TLS, partitions, crashes, torn disk writes), the explorer, shrinker, property oracles, systematic verifier, serializability checker, causal-trace CLI, and the pytest plugin all exist — exercised by a 10,000-seed determinism torture on every CI run (the harness holds itself to the same hostility it applies to your code) across Python 3.12/3.13/3.14. The API may still shift before 1.0. If you try it, open an issue — early feedback shapes it.
Learn more
docs/determinism.md— the honest boundary of the simulationdocs/event-log.md— the versioned event-log and tape formatsCHANGELOG.md— every capability, phase by phaseexamples/— the toy Raft and the bpo-42130 reproduction, both runnable
Development
uv run --all-extras pytest # tests (incl. the determinism torture)
uv run --all-extras mypy src # strict typing
uv run --all-extras ruff check . # lint
License
Apache-2.0. See LICENSE.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file simloom-0.5.0.tar.gz.
File metadata
- Download URL: simloom-0.5.0.tar.gz
- Upload date:
- Size: 94.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ce98ea1761b6280236edc40ebc85525e3b0e7aa4a92d7d87570f082728b2bec4
|
|
| MD5 |
7f420570158ead187e7dbf795ab358a1
|
|
| BLAKE2b-256 |
bd10e9ba4cdeee88a7a13d94eb5716eda222b763a85c324c3a565f62c7e38451
|
Provenance
The following attestation bundles were made for simloom-0.5.0.tar.gz:
Publisher:
release.yml on mandipadk/simloom
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
simloom-0.5.0.tar.gz -
Subject digest:
ce98ea1761b6280236edc40ebc85525e3b0e7aa4a92d7d87570f082728b2bec4 - Sigstore transparency entry: 2157384958
- Sigstore integration time:
-
Permalink:
mandipadk/simloom@5d025a856e91f260be557ee44b771e15afeb04ef -
Branch / Tag:
refs/tags/v0.5.0 - Owner: https://github.com/mandipadk
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@5d025a856e91f260be557ee44b771e15afeb04ef -
Trigger Event:
release
-
Statement type:
File details
Details for the file simloom-0.5.0-py3-none-any.whl.
File metadata
- Download URL: simloom-0.5.0-py3-none-any.whl
- Upload date:
- Size: 99.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b6ae0f896f2ffee0b633e9db1e15434cbc8a8f7d1cae8d15421bb0b542117a3e
|
|
| MD5 |
0756991762a0b5f4dac30c9c682d2f89
|
|
| BLAKE2b-256 |
dd4fad2c5bd71cb0a8d6f3f0e0d344c6f048a4181769c4fce9c896e754626419
|
Provenance
The following attestation bundles were made for simloom-0.5.0-py3-none-any.whl:
Publisher:
release.yml on mandipadk/simloom
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
simloom-0.5.0-py3-none-any.whl -
Subject digest:
b6ae0f896f2ffee0b633e9db1e15434cbc8a8f7d1cae8d15421bb0b542117a3e - Sigstore transparency entry: 2157385103
- Sigstore integration time:
-
Permalink:
mandipadk/simloom@5d025a856e91f260be557ee44b771e15afeb04ef -
Branch / Tag:
refs/tags/v0.5.0 - Owner: https://github.com/mandipadk
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@5d025a856e91f260be557ee44b771e15afeb04ef -
Trigger Event:
release
-
Statement type: