SENIORCHAPTER 18

Testing time, randomness and concurrency

Three inputs your test does not control: the clock, the dice and the scheduler. Hold each one still, print the seed, and make two threads arrive on the same beat

65 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-24
PREDICT

A test builds its start time as datetime(2026, 12, 31, 23, 30), with no time zone, and asks whether a promo that runs to the end of 31 December (Lagos days, UTC+1) is still live. It passes on a developer's laptop in Lagos. The CI runner's clock is set to UTC. What does CI report?

Run a test twice and you expect the same answer. That expectation holds only if the test fixes every input the code reads. Most inputs are obvious: the cart, the price, the stock. Three are not, because the machine supplies them: the time (the clock and the zone), randomness (anything seeded from the clock or the operating system) and ordering (which thread, or which request, gets there first). A test that leaves one of them to chance is flaky by design. The chapter on flaky tests measured that as a rate and cured the sleep, the shared state and the product race. This one is the craft behind all three: how you hold each input still, and, where the bug is in the product, how you make it fail on demand.

Time: put the instant in the test’s hand

The first rule is the one the test-driven development chapter used without arguing for it. Code that depends on “now” should be handed now. In the lab, promo_applies(promo, now) and price_cart(..., now, ...) take the instant as an argument. They never read a clock. Only the edge of the system, place_order through the Clock it is given, decides what “now” is. In production that is SystemClock, which returns datetime.now(timezone.utc). In a test it is FakeClock from checkout/clock.py, which holds one time and moves only when you call advance.

Once the instant is yours, the question changes. You stop asking “what time is it when the test runs?” and ask “which instants does this rule care about?” For a rule with a window the answer is the edges, on both sides, in every zone that reads the clock. The lab’s promo HARMATTAN is live on Lagos days from 1 to 31 December 2026, inclusive. Lagos is UTC+1 all year, with no daylight saving. So the window in UTC runs from 23:00 on 30 November to 23:00 on 31 December. Every day there is an hour, 23:00 to 23:59 UTC, when the Lagos date is one ahead of the UTC date, and twice in the promo’s life it decides the answer: on 30 November, when it is already 1 December in Lagos, and on 31 December, when it is already 1 January. A test that only ever runs at noon cannot see either hour. Six instants cover the window: a minute before the start, the first minute, a half-hour into the first Lagos day, the last minute, the first minute after, and half an hour after. Write them as a table.

▶ SIMULATION
CALENDAR
now: not started
user zone: —
THE SUITE
setup: the code and the test both read the system clock
builds run: 0 · red: 0
green with a wrong report: 0
THE TEAM SEES
last build: —
edge cases driven each run: 0
last—
✓ the build is green exactly when the report is right for the user✓ the same commit gets the same verdict on every day it runs
SCHEDULE
01[CI]test setup: the code and the test both read the system clock
02[CALENDAR]the nightly job runs: an ordinary Tuesday
03[CALENDAR]the nightly job runs: the next day
04[CALENDAR]the nightly job runs: a mid-July afternoon
05[CI]report
Start of ordinary days scenario. 5 steps.
// reads the system clock, and the day number is arithmetic on a string
function reportRange() {
  const now = new Date();                      // CI's clock, in CI's time zone
  const y = now.getUTCFullYear(), m = now.getUTCMonth() + 1, d = now.getUTCDate();
  return { from: `${y}-${pad(m)}-01`, to: `${y}-${pad(m)}-${pad(d - 1)}` };   // day 0 on the 1st
}
// the test: expected = the same expression with the same clock

Watch the sim move a fake calendar across the edges. On an ordinary day the code and the test agree. The disagreement appears only on the edge, and only in a zone that is not the one CI runs in. What the sim proves is that nobody has to wait for the edge: a test that holds the clock can stand on it. The lab does this with FakeClock and then asks for the one thing a fake cannot give you, an honest zone.

The zone is part of the input

A datetime has two shapes. An aware one carries a zone (tzinfo) and names one instant. A naive one has none and names nothing: it is a wall-clock reading, to be interpreted by whoever holds it. Python’s astimezone interprets a naive value as local time on the machine running the code. So a test that builds datetime(2026, 12, 31, 23, 30) means 23:30 in Lagos on a laptop there and 23:30 UTC on a CI runner, and the two instants are an hour apart. The lab step runs the same test with the TZ environment variable set to four zones and it passes in two and fails in two. The cure is not to set the zone on the runner. It is to never let a test instant be naive: build every one with tzinfo, UTC for most, ZoneInfo("Africa/Lagos") when the Lagos wall clock is the point.

Lagos makes this easy because it has no daylight saving. A zone that does has two more edges, and zoneinfo shows both. In the UK the clocks go back at 02:00 BST on 25 October 2026, so 01:30 happens twice. Python marks which one with the fold attribute:

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

london = ZoneInfo("Europe/London")
for fold in (0, 1):
    t = datetime(2026, 10, 25, 1, 30, tzinfo=london, fold=fold)
    print(fold, t.isoformat(), t.astimezone(timezone.utc).isoformat())
# 0 2026-10-25T01:30:00+01:00 2026-10-25T00:30:00+00:00
# 1 2026-10-25T01:30:00+00:00 2026-10-25T01:30:00+00:00

In spring there is an hour that never happens. If you sell in a zone that shifts its clocks, the edge cases are the repeated hour, the missing hour and a day that is 23 or 25 hours long, and each needs a test with an explicit instant. The Python zoneinfo documentation covers fold, and PEP 495 defines how a time in the missing hour is treated. Keep your own rule simple: store and compare in UTC, convert to a zone only to show a person or to decide a calendar day, and test the conversion at its edges.

When you cannot pass the clock in

Passing a clock is a design choice. Code you did not write, or code from before you owned it, may call datetime.now() or time.time() directly. For that the lab pins time-machine (version 2.19.0). It patches the time functions at a low level for the length of a test, so code that reads the clock directly sees the instant you chose. time_machine.travel(instant, tick=False) holds time still; leave tick at its default of true and the clock moves forward from your instant at normal speed. It is a good tool for a legacy function and a poor excuse for new code. A fake you pass in shows in the signature and works in every thread and process you give it to. A patch is global and invisible. Use the first for code you can change and the second for code you cannot.

One more rule: a test never sleeps to cross a time boundary. If a token expires in 15 minutes, advance the clock by 15 minutes and 1 second. A test that sleeps for real is slow, flaky and wrong in the same breath.

Randomness: a failure you cannot replay is an anecdote

Random inputs are valuable. They find the case you did not think of, and the property-based testing chapter, the first in this module, builds a whole method on them. They also create the worst kind of failure: one that happens in CI at 02:00 and never again. The fix is one habit. Every random test gets a seed, the seed is printed when the test fails, and one environment variable replays it.

pytest-randomly, pinned in the lab, already does part of this. It prints Using --randomly-seed=N in the header, shuffles the test order from it, and resets Python’s random module before every test from that seed and the test’s id, so random.random() in a test returns the same numbers when you replay the seed. That covers the global generator. Two cases need more. A test that wants its own generator, so that it works under any runner and does not depend on a plugin, should create random.Random(seed) and hold it. And a failure report should carry the seed next to the assertion, not three screens up in a header. The fixture in the lab does both in six lines, and it uses pytest’s add_report_section, which attaches a labelled block to the failure output.

Random tests have a second weakness that has nothing to do with seeds: the oracle. If a test compares the code to the same arithmetic the code uses, it can never fail. If it compares the code to an independent statement of the rule, it can fail for two reasons, and one of them is that the test is wrong. The lab test below is wrong on purpose. It draws twenty random instants from the 48 hours around the end of the promo and compares promo_applies with the UTC calendar day. The mistake is thin: it matters only in the hour between 23:00 and 23:59 UTC on 31 December, one draw in 48. Twenty draws catch it about a third of the time. You will run it twenty times, see roughly that, read the seed from a red run, replay it, and then correct the oracle. That is what randomness is for, and what the seed is for.

A last warning. A fixed seed hides the case you did not draw, and a fresh seed every run finds new ones. Many teams run with a fresh seed on every CI run and print it, and keep each failing seed as an ordinary named test afterwards, so the regression stays whether or not the dice land that way again.

Concurrency: why a test misses a race, and how to make it fail on demand

Time and randomness live inside one thread. Concurrency does not, and it is the input hardest to hold still, because the scheduler is not yours. Two threads make progress in slices, switching whenever the operating system or the interpreter chooses. A race condition is a result that depends on which interleaving occurred. The ATLAS lesson Data race shows the smallest one, counter++, which is three steps (load, add, store), and a pair of threads that can interleave to lose an update.

▶ SIMULATION
THREAD A
tmp_A = —
pc: load
SHARED MEMORY
counter = 0
lock: free
THREAD B
tmp_B = —
pc: load
✓ counter == increments completed✓ at most one thread between its load and its store
SCHEDULE
01[A]A: load tmp_A ← counter
02[B]B: load tmp_B ← counter
03[A]A: add tmp_A + 1
04[A]A: store counter ← tmp_A
05[B]B: add tmp_B + 1
06[B]B: store counter ← tmp_B
Start of lost update scenario. 6 steps.
// Thread A and B both run:
int tmp = counter;   // load
tmp = tmp + 1;       // add
counter = tmp;       // store

In the sim, run the lost-update schedule, the lucky one and the two fixes. What it proves: the same code, with the same inputs, is right under one schedule and wrong under another, and a fix has to hold under the schedule that breaks the unfixed code, not under the lucky one. A test that finds the lucky schedule tells you nothing.

That is why races pass in tests and fail in production. The window is the span between the check and the act. If a request spends a millisecond in the window and the next one arrives two milliseconds later, they never overlap. A load test with thousands of requests overlaps them often. A unit test that calls the function twice in a row never does. The flaky test race lesson shows the sibling case in a test: a wait that guesses the finish time, a seeded generator for the delay, and a replay that is exact.

▶ SIMULATION
THE TEST
waits: 100 ms, fixed
deadline: none
THE JOB (CORRECT)
machine load: x2
—
WHAT THE TEAM SEES
red builds: 0 of 0
wrong alarms: 0
last—
✓ the build is red exactly when the code is wrong
SCHEDULE
01[TEST]test: start job, sleep 100 ms, assert it finished
02[CI]run 1: start the job, wait, assert
03[CI]run 2: start the job, wait, assert
04[CI]run 3: start the job, wait, assert
05[CI]run 4: start the job, wait, assert
06[CI]run 5: start the job, wait, assert
07[CI]run 6: start the job, wait, assert
08[CI]run 7: start the job, wait, assert
09[CI]run 8: start the job, wait, assert
10[CI]run 9: start the job, wait, assert
11[CI]run 10: start the job, wait, assert
12[CI]run 11: start the job, wait, assert
13[CI]run 12: start the job, wait, assert
14[TEST]report
Start of sleep 100 ms, loaded ci scenario. 14 steps.
test('job finishes', () => {
  startJob();
  sleep(100);            // a guess about how long the job takes
  expect(job.isDone()).toBe(true);
});

Read this sim for the replay. Every run there draws its delay from a seeded generator, so the red runs come back when you replay the seed. A concurrency test needs the same property, and has a harder way to get it. You cannot seed the scheduler. You can do two other things: line the threads up so they arrive on the same beat, and repeat the round enough times to see the rare overlap.

The harness: a barrier and a loop

threading.Barrier(n) holds every thread that calls wait() until n of them have arrived, then releases them together. It removes thread start-up skew, which is a large part of the gap between two threads. Wrap it in a small helper that returns each thread’s result or exception (an exception inside a thread is otherwise lost), and give wait a timeout so a thread that never arrives fails the test instead of hanging the build:

def race(n, fn):
    barrier = threading.Barrier(n)
    results = [None] * n

    def run(i):
        try:
            barrier.wait(timeout=5)
            results[i] = fn(i)
        except Exception as exc:
            results[i] = exc

    threads = [threading.Thread(target=run, args=(i,)) for i in range(n)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return results

Then assert an invariant, not an interleaving. You do not know which thread went first and should not care. You care that exactly one of two buyers gets the last unit, that stock never goes below zero, that a key never has two orders. Those hold under every schedule, so the same assertion works whether the race occurs or not. If the race exists, the invariant breaks in some rounds and you see it.

The lab has two concurrent paths worth testing. The first is two buyers for the last unit. inventory.reserve calls db.take_stock, which is one statement: UPDATE stock SET on_hand = on_hand - ? WHERE product_id = ? AND on_hand >= ?. The check and the write are the same step, and SQLite will not run two writers through it at once, so the test should pass. That does not make it a waste. It is the evidence that the pattern works, and it pins it for whoever edits inventory.py next. The second path is place_order itself. It looks up the idempotency key, then reserves stock, charges, and saves. Two requests with the same key that arrive together both pass the lookup. The provider de-duplicates the charge by Idempotency-Key, so the card is charged once, but the lab’s own README records what the database ends up with: two orders, and stock taken twice. That is the check-then-act race the chapter on flaky tests described, and the lab step here makes it fail every time and then fixes it. The Payments chapter on idempotency explains why the key exists. Here the question is how to test that it works.

What a green result means

A concurrency test that passes is weaker evidence than any other test you write. It says the race did not occur in these rounds on this machine. The unit-test rule from the test-driven development chapter, that a test you have never seen red has not shown it can fail, matters more here, not less. The first buyers-for-the-last-unit test passes on the first run, so you cannot tell from it whether the harness could catch a fault. The second test uses the same race helper and fails at once on the unfixed code. That is your proof that the helper sees overlaps, and it is the order to build in: get a red test with the harness first, then trust a green one.

Three habits keep the test honest. Widen the window when you can: a fake provider that takes 50 ms to answer stretches the gap between check and act. Repeat the round: the lab uses 300 rounds, each with its own keys and a freshly set stock, so a doubled round cannot use up the shelf and hide the next. Keep the rounds independent: a test whose second round replays the first round’s key is testing replay, not the race.

The cure: let the database decide

A check-then-act race is cured by making the check and the act one step. In application code that means a lock, which works in one process and not across servers. In the database it means a constraint. The orders table already has an index on idempotency_key, but not a unique one. Make it unique and the second insert fails with an IntegrityError, because the database enforces it whichever process asks. That is the same shape as take_stock: the database owns the check.

The fix is not finished at the index. The losing request has already reserved stock and called the provider. So place_order must catch the conflict, put the stock back, and return the winner’s order, flagged as a replay. Forgetting that step turns a double order into a stock leak, which the test will also catch if it asserts stock as well as the order count. Two cautions. A database that already exists keeps its old index, because CREATE UNIQUE INDEX IF NOT EXISTS skips an index of that name; a real change needs a migration that checks for existing duplicates first, which is the subject of the later chapter on testing data pipelines and migrations. And a unique index decides what to do about two requests, not how to test the decision. Only the harness shows it holds.

This is a small slice of a bigger subject. Tests that explore interleavings systematically, instead of by luck, exist: the CHESS tool in the OSDI paper in the reading list takes over the scheduler and walks the interleavings. The chapter on testing across services and the one on formal methods, later in the course, return to that. For one service and one race, a barrier and a loop go a long way.

What to carry away

Hold each input still. Pass the time in, build every instant with a zone and test both sides of each edge. Give every random test a seed and print it where the failure is. Line threads up with a barrier, repeat the round, assert an invariant, and see the harness fail before you trust it green.

LAB Hold the clock, replay the dice, make two requests collide ~45 MIN
YOU NEEDPython 3.9 or laterlabs/testing set up as in its README (a .venv with the pinned requirements)a text editorno Docker, no servers, no ports

You write four small test files against Ojaline’s checkout service, run a promo window under FakeClock, break and fix a zone assumption, replay a seeded failure, and then make the idempotency race fail on demand, fix it with a unique index and run the harness again. Everything runs from labs/testing with the tests’ own temporary databases (tmp_path), so nothing touches data/. Output is trimmed; times and seeds will differ.

1. Check the starting point and back up the two files you will edit in step 8.

cd labs/testing
.venv/bin/pytest -q
mkdir -p scratch && cp checkout/db.py checkout/orders.py scratch/
23 passed, 1 skipped, 1 deselected. The skip is the browser test (no Chromium) and the deselected one is the quarantined flaky test.

2. Test the promo window at its edges with FakeClock. HARMATTAN is live on Lagos days 1 to 31 December 2026, inclusive. Create tests/unit/test_promo_window.py:

from datetime import datetime, timezone

import pytest

from checkout.clock import FakeClock
from checkout.pricing import PROMOS, Line, price_cart, promo_applies

HARMATTAN = PROMOS["HARMATTAN"]  # live on Lagos days 1 to 31 December 2026, inclusive

def utc(y, m, d, h, mi=0):
    return datetime(y, m, d, h, mi, tzinfo=timezone.utc)

@pytest.mark.parametrize(
    "instant, live",
    [
        pytest.param(utc(2026, 11, 30, 22, 59), False, id="23:59 on 30 Nov in Lagos"),
        pytest.param(utc(2026, 11, 30, 23, 0), True, id="00:00 on 1 Dec in Lagos, the first minute"),
        pytest.param(utc(2026, 11, 30, 23, 30), True, id="still 30 Nov in UTC, 1 Dec in Lagos"),
        pytest.param(utc(2026, 12, 31, 22, 59), True, id="23:59 on 31 Dec in Lagos, the last minute"),
        pytest.param(utc(2026, 12, 31, 23, 0), False, id="00:00 on 1 Jan in Lagos"),
        pytest.param(utc(2026, 12, 31, 23, 30), False, id="still 31 Dec in UTC, 1 Jan in Lagos"),
    ],
)
def test_the_promo_window_follows_the_lagos_day(instant, live):
    clock = FakeClock(instant)
    assert promo_applies(HARMATTAN, clock.now()) is live

def test_advancing_the_clock_crosses_the_edge_without_waiting():
    clock = FakeClock(utc(2026, 12, 31, 22, 58))
    cart = [Line(1_000_000, 1)]  # N10,000: the 5% tier applies, so the promo is 10% of 950,000
    before = price_cart(cart, 3, clock.now(), "HARMATTAN").promo_discount
    clock.advance(minutes=2)
    after = price_cart(cart, 3, clock.now(), "HARMATTAN").promo_discount
    assert (before, after) == (95_000, 0)
.venv/bin/pytest tests/unit/test_promo_window.py -v -p no:randomly

Seven lines ending PASSED, named by the ids above, and 7 passed. The second test crosses midnight in Lagos in two simulated minutes: at 23:58 UTC the promo takes 95,000 kobo (₦950) off a ₦10,000 basket, and at 00:00 on 1 January in Lagos it takes nothing. Nothing slept.

3. See a naive datetime change meaning with the machine. Create tests/unit/test_naive_clock.py. The start has no tzinfo:

from datetime import datetime

from checkout.clock import FakeClock
from checkout.pricing import PROMOS, promo_applies

def test_promo_at_23_30_on_its_last_day_with_a_naive_start():
    clock = FakeClock(datetime(2026, 12, 31, 23, 30))  # no tzinfo: which zone is this?
    assert promo_applies(PROMOS["HARMATTAN"], clock.now())

Run it under four zones with the TZ variable:

for z in Africa/Lagos UTC Pacific/Auckland America/Los_Angeles; do
  echo "$z: $(TZ=$z .venv/bin/pytest tests/unit/test_naive_clock.py -q -p no:randomly 2>&1 | tail -1)"
done
Africa/Lagos: 1 passed in 0.08s
UTC: 1 failed in 0.10s
Pacific/Auckland: 1 passed in 0.07s
America/Los_Angeles: 1 failed in 0.10s

The same file is green in two zones and red in two. On a UTC runner the failure is assert False with datetime.datetime(2026, 12, 31, 23, 30) printed, which is 00:30 on 1 January in Lagos. A laptop in Lagos hides the fault, because the machine’s zone happens to be the one the rule uses.

Fix the test, not the machine. Replace the file with an aware start:

from datetime import datetime
from zoneinfo import ZoneInfo

from checkout.clock import FakeClock
from checkout.pricing import PROMOS, promo_applies

def test_promo_at_23_30_on_its_last_day_with_an_aware_start():
    clock = FakeClock(datetime(2026, 12, 31, 23, 30, tzinfo=ZoneInfo("Africa/Lagos")))
    assert promo_applies(PROMOS["HARMATTAN"], clock.now())

Run the same loop again.

1 passed in all four zones. The test now names one instant, so the runner’s zone cannot change it.

4. Hold the real clock with time-machine, for code you cannot pass a clock to. Create tests/unit/test_system_clock.py:

from datetime import datetime, timezone

import time_machine

from checkout.clock import SystemClock
from checkout.pricing import PROMOS, promo_applies

LAST_EVENING_UTC = datetime(2026, 12, 31, 23, 30, tzinfo=timezone.utc)  # 00:30 on 1 January in Lagos

@time_machine.travel(LAST_EVENING_UTC, tick=False)
def test_the_real_clock_can_be_held_still():
    now = SystemClock().now()
    assert now == LAST_EVENING_UTC
    assert not promo_applies(PROMOS["HARMATTAN"], now)

def test_travel_ends_when_the_block_ends():
    with time_machine.travel(LAST_EVENING_UTC, tick=False):
        assert SystemClock().now() == LAST_EVENING_UTC
    assert SystemClock().now() != LAST_EVENING_UTC  # outside the block the real clock is back
.venv/bin/pytest tests/unit/test_system_clock.py -q -p no:randomly
2 passed. SystemClock reads the real clock, and inside the decorator or the with block it returns the instant you chose. Compare steps 2 and 4: the first changes what you hand to the code, the second changes what the code reads.

5. Replay a random failure from its seed. Create tests/unit/test_promo_random.py. The oracle is wrong on purpose: it takes the day from the UTC instant.

import os
import random
from datetime import date, datetime, timedelta, timezone

import pytest

from checkout.pricing import PROMOS, promo_applies

HARMATTAN = PROMOS["HARMATTAN"]

@pytest.fixture
def rng(request):
    """A random generator whose seed is always on the failure report. TEST_SEED=n replays a run."""
    seed = int(os.environ.get("TEST_SEED", random.SystemRandom().randrange(2**32)))
    request.node.add_report_section("call", "seed", "TEST_SEED=%d" % seed)
    return random.Random(seed)

def test_random_instants_agree_with_the_lagos_calendar(rng):
    start = datetime(2026, 12, 30, 12, 0, tzinfo=timezone.utc)
    for _ in range(20):
        instant = start + timedelta(minutes=rng.randrange(48 * 60))  # 30 Dec 12:00 to 1 Jan 12:00
        lagos_day = instant.date()  # the day, read in UTC
        expected = date(2026, 12, 1) <= lagos_day <= date(2026, 12, 31)
        assert promo_applies(HARMATTAN, instant) is expected, instant.isoformat()

Run it twenty times and count the outcomes:

for i in $(seq 1 20); do .venv/bin/pytest tests/unit/test_promo_random.py -q -p no:randomly 2>&1 | tail -1; done | sed 's/ in .*//' | sort | uniq -c

A split such as 13 1 passed and 7 1 failed. Over 100 runs here, 34 failed, about the one in three the arithmetic predicts. Nothing in the code changed between runs: only the dice did.

Keep running until one fails and read the report:

.venv/bin/pytest tests/unit/test_promo_random.py -q -p no:randomly

A failing run ends like this (your seed and minute will differ):

E           AssertionError: 2026-12-31T23:27:00+00:00
E           assert False is True
------------------------------ Captured seed call ------------------------------
TEST_SEED=2282213469

The failing instant is always between 23:00 and 23:59 UTC on 31 December. There, the UTC date is still 31 December, so the test expects the promo to be live, and in Lagos it is already 1 January and the code says it is over.

Replay it three times with the seed from your own report:

for i in 1 2 3; do TEST_SEED=2282213469 .venv/bin/pytest tests/unit/test_promo_random.py -q -p no:randomly 2>&1 | tail -1; done
1 failed in ... three times, with the same instant each time. A failure that follows the seed is yours to debug. Now correct the oracle. In the test, replace the lagos_day line with lagos_day = (instant + timedelta(hours=1)).date() # Lagos is UTC+1, with no daylight saving. Run the 100-run loop again (seq 1 100 in the same command) and every run passes, including the old seed: TEST_SEED=2282213469 .venv/bin/pytest tests/unit/test_promo_random.py -q -p no:randomly gives 1 passed. The bug was in the test, which is how most “random” failures turn out. The seed is what let you tell.

6. Build the race harness and test two buyers for the last unit. Create tests/integration/race_helpers.py. It holds the race function, a fake provider that charges once per key and takes delay_s to answer, and a helper that counts keys with more than one order:

"""Helpers for tests that need two things to happen at the same moment."""

import sqlite3
import threading
import time

from checkout.payments_client import ChargeResult

def race(n, fn):
    """Call fn(i) in n threads released together by a Barrier. Returns each result or exception."""
    barrier = threading.Barrier(n)
    results = [None] * n

    def run(i):
        try:
            barrier.wait(timeout=5)  # nobody starts until everybody is here; never wait forever
            results[i] = fn(i)
        except Exception as exc:  # keep the failure; an exception inside a thread is otherwise lost
            results[i] = exc

    threads = [threading.Thread(target=run, args=(i,)) for i in range(n)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return results

class SlowDedupingPayments:
    """Like the provider: one charge per Idempotency-Key, and it takes delay_s to answer."""

    def __init__(self, delay_s=0.0):
        self.delay_s = delay_s
        self.charges = {}
        self._lock = threading.Lock()

    def charge(self, reference, amount_kobo, idempotency_key):
        time.sleep(self.delay_s)
        with self._lock:
            charge_id = self.charges.setdefault(idempotency_key, "ch_%d" % (len(self.charges) + 1))
        return ChargeResult(charge_id, "succeeded")

def keys_with_two_orders(db):
    """How many idempotency keys have more than one order row?"""
    conn = sqlite3.connect(db.path)
    try:
        return conn.execute(
            "SELECT COUNT(*) FROM (SELECT 1 FROM orders GROUP BY idempotency_key HAVING COUNT(*) > 1)"
        ).fetchone()[0]
    finally:
        conn.close()

Create tests/integration/test_concurrency.py with the first test. Every round uses a new key per buyer and resets the stock of product 3 (the Aso-oke cap) to one:

from checkout.inventory import OutOfStock
from checkout.orders import place_order
from tests.integration.race_helpers import SlowDedupingPayments, race

ROUNDS = 300

def test_two_buyers_for_the_last_unit_one_wins(db, clock):
    payments = SlowDedupingPayments()
    for n in range(ROUNDS):
        db.set_stock(3, 1)  # one Aso-oke cap left

        def buy(i):
            key = "round-%d-buyer-%d" % (n, i)  # a new key every round, or round 2 is a replay
            return place_order(db, payments, clock, [{"product_id": 3, "qty": 1}], key)

        results = race(2, buy)
        won = [r for r in results if isinstance(r, tuple)]
        lost = [r for r in results if isinstance(r, OutOfStock)]
        assert len(won) == 1 and len(lost) == 1, "round %d: %r" % (n, results)
        assert db.stock_of(3) == 0, "round %d: stock is %d" % (n, db.stock_of(3))
.venv/bin/pytest tests/integration/test_concurrency.py -v -p no:randomly
1 passed in about 1.2 s. Three hundred rounds, each with two threads released together, and in every one exactly one buyer got the cap and the other got OutOfStock. Read the source of Database.take_stock to see why: the check and the write are one UPDATE. You have not seen this test fail, so you do not yet know the harness can catch anything. The next step tells you.

7. Make the same-key race fail. Change the import line to from tests.integration.race_helpers import SlowDedupingPayments, keys_with_two_orders, race and append two tests. The first is the realistic retry, with a provider that takes 50 ms. The second uses no delay at all, so the barrier is the only thing lining the threads up:


def test_a_retry_with_the_same_key_makes_one_order(db, clock):
    payments = SlowDedupingPayments(delay_s=0.05)  # the provider takes 50 ms to answer
    results = race(2, lambda i: place_order(db, payments, clock, [{"product_id": 2, "qty": 1}], "same-key"))
    assert sorted(created for _order, created in results) == [False, True]  # one new order, one replay
    assert db.count_orders() == 1
    assert db.stock_of(2) == 99

def test_the_same_race_with_no_delay_at_all(db, clock):
    payments = SlowDedupingPayments(delay_s=0.0)
    for n in range(ROUNDS):
        key = "retry-%d" % n
        db.set_stock(1, 50)  # so a run of doubled orders cannot empty the shelf
        race(2, lambda i: place_order(db, payments, clock, [{"product_id": 1, "qty": 1}], key))
    doubled = keys_with_two_orders(db)
    assert doubled == 0, "%d of %d keys got two orders" % (doubled, ROUNDS)
.venv/bin/pytest tests/integration/test_concurrency.py -p no:randomly 2>&1 | grep -E "^E  +(assert|Assertion)|^FAILED|passed|failed"
E       assert [True, True] == [False, True]
E       AssertionError: 300 of 300 keys got two orders
E       assert 300 == 0
FAILED tests/integration/test_concurrency.py::test_a_retry_with_the_same_key_makes_one_order
FAILED tests/integration/test_concurrency.py::test_the_same_race_with_no_delay_at_all
2 failed, 1 passed in 3.3s

Both requests report created = True: each believed it placed the first order. Across 300 rounds, every key got two orders, with no sleep and no delay. The race window in place_order is milliseconds wide, because two SQLite commits sit between the lookup and the save, so the barrier is enough. The harness can see overlaps, and the green test in step 6 now means something.

8. Fix it: a unique index, and handle the loser. Edit checkout/db.py and change CREATE INDEX IF NOT EXISTS orders_key to CREATE UNIQUE INDEX IF NOT EXISTS orders_key in the SCHEMA string. Edit checkout/orders.py: add import sqlite3 as the first import line, and replace the last two lines of place_order (order = db.save_order(...) and return order, True) with:

    try:
        order = db.save_order(idempotency_key, quote.total, charge.id, clock.now(), lines)
    except sqlite3.IntegrityError:
        # A request with this key saved first. Put our stock back and return its order.
        release_all(db, lines)
        return db.find_order_by_key(idempotency_key), False
    return order, True
for i in 1 2 3; do .venv/bin/pytest tests/integration/test_concurrency.py -q 2>&1 | tail -1; done
.venv/bin/pytest -q
3 passed each time, in about 3 to 7 s, with the shuffle on. Then the full suite: 37 passed, 1 skipped, 1 deselected (the starter 23, plus 7 window tests, 1 zone test, 2 time-machine tests, 1 random test and 3 concurrency tests). The check-then-act race is now closed by the database, and the loser’s stock goes back. Note that data/checkout.sqlite, if you already ran the app, keeps its old non-unique index: IF NOT EXISTS skips an index of that name. The tests use fresh files, so they see the new one.

9. Put the lab back. Later chapters count tests from the clean state.

cp scratch/db.py checkout/db.py
cp scratch/orders.py checkout/orders.py
rm -rf scratch tests/unit/test_promo_window.py tests/unit/test_naive_clock.py tests/unit/test_system_clock.py tests/unit/test_promo_random.py tests/integration/race_helpers.py tests/integration/test_concurrency.py
.venv/bin/pytest -q
23 passed, 1 skipped, 1 deselected, the starter state.

Break it further. Bring the concurrency files back for ten minutes. In race_helpers.py, replace the barrier.wait(...) line with time.sleep(0.2 * i), so the second thread starts 200 ms after the first, and run -k "same_key". It passes, because the first request finishes long before the second looks. That is the test most teams already have: two calls a moment apart, a green result and a double order in production. Then restore the barrier and run the fixed code with ROUNDS = 1000. How long does it take, and what does that cost you in a suite that must run in under two minutes? Last, write down which of the three conditions (the clock, the dice, the scheduler) each of your tests holds still and which it leaves to chance. Restore everything before you move on.

DECIDE

Khanyi's team has a barrier test for the last unit of a flash-sale item. It has passed for months. One night in CI it fails once, with two buyers both told they got the last unit, and the next 40 runs pass. The release is tomorrow. A colleague proposes adding a retry plugin to the job so one red run is ignored; another says the test must be wrong because it has passed for months. Khanyi has the build log, the commit hash and the seed of the shuffle, and a release tomorrow.

READING
  1. DOC
    zoneinfo: IANA time zone support

    The standard-library source for ZoneInfo, aware against naive datetimes, and the fold attribute. Gaps and the rules for them are in PEP 495, cited in the text. Read the first page; the rest is reference. Read: The introduction and the section on `fold`..

  2. CODE
    time-machine: Travel through time in your tests Adam Johnson

    The tool the lab pins (2.19.0). The README and the linked usage page show travel as a decorator and a context manager, and the tick option. Read it to see what it patches before you reach for it over a clock you pass in.

  3. POST
    Eradicating Non-Determinism in Tests Martin Fowler, 2011

    A short list of where flaky tests come from (lack of isolation, asynchrony, remote services, time, resource leaks) and what to do about each. Read the sections on time and on asynchrony after the lab and compare them with your own harness.

  4. DOC
    threading: Barrier objects

    The exact behaviour of Barrier.wait, its timeout argument and what BrokenBarrierError means, which the race helper depends on. A page of reference; read only the Barrier section.

  5. PAPER
    Finding and Reproducing Heisenbugs in Concurrent Programs Musuvathi, Qadeer, Nainar and others, 2008

    The CHESS paper (OSDI 2008): a tool that takes control of thread scheduling and explores interleavings systematically, and reproduces the failing one every time. It shows what the barrier-and-loop method in this chapter approximates by chance. Read: The abstract, the introduction and the section on the design of the scheduler. Skip the implementation details unless you want to build such a tool..

  6. CODE
    pytest-randomly

    What the plugin shuffles, how it reseeds the random module before each test, and the options (--randomly-seed, -p no:randomly) the lab uses. Short; read the README top to bottom.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Testing across services: fault injection and deterministic simulation →