Skip to content

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 -race builds 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/DRD do the same job for pthreads.
  • Model checkers. Rust's loom swaps std::sync for 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 injected yield_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) == expected

A 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 is try: open() and handle FileNotFoundError; 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 Mutex poisons it and lock() returns Err. 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 -race in 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?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.