Lesson 11 of 14 · 20m
Testing Concurrency: Races on Demand
Therac-25 killed patients on a race only fast typists hit — find races with detectors and model checkers, not by re-running until something breaks.
Between 1985 and 1987, the Therac-25 radiation machine delivered massive overdoses to at least six patients. Nancy Leveson's investigation found the mechanism: a shared flag raced a counter — an operator who typed fast enough could finish correcting an entry inside a window the software assumed couldn't happen, leaving the machine armed with the wrong parameters. The bug reproduced only for fast typists. Re-running the test suite never catches a race; the scheduler has to hit the unlucky interleaving.
The wrong mental model: "I ran it a hundred times with no failure — there's no race." Absence of failure is a probability statement, not a proof. Race testing means forcing interleavings or detecting unsynchronized access — not hoping.
The tools that actually find races
- Race detectors.
go test -racebuilds with ThreadSanitizer's algorithm: every memory access is tracked, and unsynchronized access is reported deterministically — the race fails the first time it's executed, not the thousandth time it's unlucky. Roughly 10× slower; worth it on every concurrency-touching test. Clang and GCC get TSan via-fsanitize=thread, Rust nightly via-Zsanitizer=thread;helgrind/DRDdo the same job for pthreads. - Model checkers. Rust's
loomswapsstd::syncfor model types and exhaustively explores interleavings — every legal ordering runs, not a random sample. The cost is exponential: keep the checked model to a few threads and a few operations. Shuttle does the same at the scheduler level. - Deterministic simulation. FoundationDB rebuilt the database on a single-threaded deterministic simulator — every socket, disk, and RNG simulated — and ran thousands of randomized failure injections nightly. TigerBeetle copied the architecture. It's how you test a consensus layer, and it costs what it costs.
- Stress + perturbation. The cheap version:
go test -count=200,pytest-repeat, and injectedyield_now()/sleep(0)at suspension points to bias the scheduler toward interleavings it wouldn't choose.
In C and C++ the stakes are higher than a wrong value: a data race is undefined behavior under the C11 memory model — the compiler is allowed to assume the race never happens and optimize accordingly, which is how races produce bugs no test output can explain. The fix is std::atomic or the mutex; the detector's job is proving you found every place that needs one.
Forcing the unlucky ordering
You can make the scheduler deterministic without tooling: a threading.Barrier(2) releases two threads simultaneously into the racing section, and an Event lets one thread park mid-operation while the other runs — you choreograph the exact interleaving that breaks. The test doesn't hope for the race; it stages it:
barrier = threading.Barrier(2)
def thread_a():
barrier.wait()
cache.invalidate(key) # lands inside worker B's read window
def thread_b():
barrier.wait()
assert cache.get(key) is not None or cache.get(key) == expectedA watchdog belongs in every concurrency test — wait_for on the barrier, a timeout on the assertion — because the failure mode of a real deadlock is a hang, and a hang in CI is a thirty-minute timeout and a killed job, not a failure message. Bound every wait; the deadlock should report itself in two seconds.
The testable shapes
- TOCTOU.
if path.exists(): open(path)is two calls — test it by deleting the file between the check and the use. The fix istry: open()and handleFileNotFoundError; the test proves the handling. - Lock ordering. Deadlock needs opposite acquisition orders. Hold both locks in both orders in parallel with a watchdog
wait_for— or better, enforce ordering by construction and test that the constructor refuses a cycle. - Mutex poisoning. In Rust, a panic while holding a
Mutexpoisons it andlock()returnsErr. That's a testable outcome — assert the recovery path instead of discovering it at 3 AM. - Goroutine leaks.
goleak.VerifyNone(t)fails the test when a goroutine outlives it — leaks are races that haven't fired yet. - Jepsen is the same idea aimed at distributed systems: Kyle Kingsbury's harness found real correctness bugs in etcd, MongoDB, CockroachDB, and a dozen others by partitioning networks and checking claimed invariants.
Field notes
go test -racein CI is close to free insurance; the 10× slowdown belongs on the concurrency tests at minimum.- Races get prevented by construction — immutable data, channels over shared memory — then the suite verifies the construction. You cannot test your way out of a design that shares mutable state.
- A test that "never fails" on shared mutable state isn't evidence; run it under a detector before believing it.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Your Container Is Running SerialGC and Nobody Told You
You tuned G1 flags for a week. Your pod has one CPU, which means the JVM quietly picked a single-threaded collector at startup and ignored every flag you set. Here is the OpenJDK source that made that decision.
Java Pulled Primitive Patterns After Five Previews. JDK 28 Won't Compile Them.
Primitive types in patterns, instanceof, and switch previewed in every JDK from 23 to 27. On November 9 the Amber team withdrew the feature, and it won't be in JDK 28 even with --enable-preview. Here's why Valhalla changed the plan, what replaces it, and how to rewrite code that used it.
Minecraft Runs on One Thread Because Nobody Wrote It for Two
Every entity, every block update, every redstone pulse — one thread, twenty times a second, 50 milliseconds a pass. Folia's answer is to stop sharing the kitchen. Here is the tick budget and the ownership rules, read from the PaperMC source.
Ask Java for AES and You Get ECB. Nobody Warns You.
Cipher.getInstance("AES") compiles, runs, encrypts, decrypts, and hands you the weakest mode in the box. Here is the OpenJDK source that makes that decision, and the line where ECB gets chosen for you.