Turn a Suspected Race Condition Into a Deterministic Reproduction and a Regression Test

You are helping me turn a suspected race condition into a reproduction that fails every time, and then into a regression test. Intermittent failures are hard to fix because nobody can confirm a fix worked. Your goal is to remove the luck.

I will provide: the code paths involved, the symptom (wrong value, duplicate record, deadlock, crash), how often it happens, the concurrency model (threads, async tasks, multiple processes, multiple servers), and any logs from a failing occurrence.

Follow this process and label each part of your answer:

1. State the hypothesis precisely as an interleaving: "Operation A reads X, operation B writes X, then A writes based on the stale read." Draw the timeline as a table with one column per actor and one row per step. If more than one interleaving could explain the symptom, list each and say which evidence would distinguish them.
2. Identify the shared state and the unprotected window: what is read, what is written, and what assumption (atomicity, ordering, uniqueness) the code relies on that is not enforced.
3. Propose a way to force the bad interleaving without changing production logic: an injected pause or barrier at the exact point between the read and the write, a controllable scheduler or fake clock, a latch that holds one actor until the other has finished, or a hook that is a no-op in production. Provide the code for this in my language.
4. Write the test: it must fail on the current code and show the specific wrong outcome. Include what it asserts and why that assertion captures the bug and not a side effect.
5. Propose the fix options (a lock, a transaction with the right isolation level, an atomic compare-and-set, a unique constraint, an idempotency key), compare their trade-offs, and say which one removes the window versus merely narrowing it.
6. Describe how to confirm the test passes after the fix and still fails if the fix is reverted. Add a stress variant (many iterations, many actors) as a secondary check, and say plainly that a stress run passing is not proof.

If the information I gave is not enough to name an interleaving, do not invent one. Tell me what to log or trace to capture it.

When to use it: any bug described as "happens sometimes", "only under load", or "cannot reproduce locally".

How to adapt it: specify the language and test framework so the barrier code is idiomatic, and say whether tests may touch a real database.

Example input: two requests both read an inventory count of 1 and both decrement it, selling the item twice, with the handler code and a log excerpt.

Good output: a two-column timeline of the double read, a test using a barrier that holds both requests after the read, a failing assertion that the count is -1 or two orders exist, and a comparison between a conditional update (decrement only where count > 0) and a row lock.

Sign in to upvote this prompt.