Direct answer
Reproduce an asynchronous race by controlling the schedule instead of adding sleeps. Vitest documents explicit fake-timer advancement for controlling timeout and interval behavior (F031), and Pytest lists thread-safety issues as a possible source of non-deterministic behavior (F032). The method here is to describe the competing operations, control the event-loop boundary, serialize the suspect path once, then vary one concurrency dimension at a time until the failing interleaving appears. A passing serial run does not explain a concurrent failure, and an arbitrary sleep is not proof that a race is fixed.
Ask Claude Code to name the ordering assumption in the suspect path. The assumption, not the symptom, is what the regression test has to encode.
Why a race that is hard to reproduce gets shipped
A race condition fails only under a specific interleaving of asynchronous operations. In ordinary runs the scheduler happens to produce a safe order, so the test passes and the defect stays invisible. The failure appears in production under load, on a slow network, or on a machine with different timing, where the unsafe interleaving becomes common enough to surface.
Three costs follow. The bug is reported as intermittent and gets deprioritized because nobody can reproduce it on demand. Fixes are validated with sleeps, which make the test pass by waiting longer rather than by removing the race. The team loses confidence in the affected area, because nobody can say whether the fix covers the schedules that actually occur.
| Signal in the report | Likely underlying issue | First control to add |
|---|---|---|
| Fails under load only | Unsafe interleaving becomes likely | Serialize the suspect path |
| Fails on slow networks | Timeout outraces the response | Fake timers with explicit advancement |
| Passes alone, fails in suite | Shared resource raced across tests | Unique resource per test |
| Intermittent assertion on a count | Two writers race for one counter | Capture the interleaving that fails |
None of these are rare. They are the ordinary consequences of code that assumes an order the scheduler does not guarantee.
Naming the operations also bounds the investigation. A race report that says “sometimes the save is lost” could involve the debounce timer, the navigation handler, the optimistic update, and the server acknowledgment. Writing down which two of those can overlap and which shared record they both write is what turns an open-ended search into a bounded one.
Describe the competing operations
Start by naming the operations that can overlap and the shared resource they touch. A race needs at least two operations and one shared resource; naming all three makes the rest of the investigation concrete.
| Operation | Trigger | Expected order | Observed order | Shared resource |
|---|---|---|---|---|
| Save draft | Debounced input | Save completes before navigate | Navigate cancels the save | Draft record |
| Refresh token | Expiring session | Refresh before retry | Two requests refresh at once | Token store |
| Increment counter | Concurrent requests | Read then write atomically | Read, read, write, write | Counter row |
| Apply discount | Two tab events | First event wins | Both apply | Cart total |
Record the expected order as a statement about observable state, not about implementation. “The second request reuses the token the first request obtained” is checkable. “The requests are synchronized” is not.
Claude Code best practices recommends precise investigation prompts that name files and symptoms. Applied here, the prompt asks which operations in a named file can overlap and which shared state they touch, and it returns a map you can review before running anything.
Control the event-loop boundary
Asynchronous behavior is ordered by the scheduler, not by the order the code appears in. Timers, promises, and I/O completions are queued, and the queue order determines which operation observes which state. Controlling that queue is what makes a race reproducible.
Vitest provides fake timers that replace the real clock and advance explicitly (F031). With fake timers, a test can advance time past a debounce window, past a timeout, or past an interval tick on demand, and the callbacks fire in a deterministic order rather than whenever the real clock allows. Jest provides the same capability for timer mocks.
| Scheduling control | What it makes deterministic | What it does not cover |
|---|---|---|
| Fake timers with explicit advance | Timer and interval ordering | Promise resolution order from I/O |
| Awaited promises in a fixed sequence | Promise chain order | Callbacks registered after the await |
| Queued microtask flush | Microtask before macrotask | Thread-level interleaving |
| Injected scheduler | Any order the test chooses | Schedules the real runtime uses |
Timer control does not by itself model every promise or thread interleaving. A test that advances fake timers proves something about timer ordering and nothing about the interleaving of two network responses arriving in a different order than they were sent. That limitation is worth stating in the test rather than leaving for the next reader to discover, because a fake-timer test that passes can be mistaken for proof that no race exists.
Make promise order explicit
Promise chains hide their order in the shape of the code. Two awaits written sequentially execute in order; two promises created before either is awaited may already be in flight. Making the order explicit is what turns an implicit assumption into something a test can check.
Record which operations are created before they are awaited, which are awaited in sequence, and which run concurrently by design. The race is usually at a boundary where one of those categories was assumed to be another.
| Code shape | Actual order | Common wrong assumption |
|---|---|---|
| Two promises created, awaited later | Both in flight immediately | They run one at a time |
| Sequential awaits | Strictly ordered | They might overlap |
Promise.all over two calls |
Concurrent | The second finishes first is impossible |
| Fire-and-forget without await | Unordered relative to the caller | It completes before the next line |
Ask Claude Code to mark each await in the suspect path as sequential, concurrent, or fire-and-forget, and to state what shared state each one touches. That map is the input to serialization.
Serialize the suspect path once
Before varying anything, run the suspect path with the concurrency removed. Force the operations into the order you believe is safe and confirm the test passes. This is a control run, and its purpose is to show that the logic is correct when the ordering is guaranteed.
A passing serial run establishes that the failure is about ordering rather than about the logic itself. It does not explain the concurrent failure, and it must not be presented as the fix. Removing concurrency changes the system; a serial pass only proves the system is correct under one specific schedule.
| Run | Ordering | Result | Interpretation |
|---|---|---|---|
| Serial, forced safe order | Fully controlled | Passes | Logic is correct under this schedule |
| Concurrent, uncontrolled | Real scheduler | Fails intermittently | An unsafe interleaving exists |
| Concurrent, fake timers | Controlled clock | Fails deterministically | The interleaving is captured |
The third run is the target. It reproduces the race on demand, which is the precondition for a regression test that actually guards it.
Vary one concurrency knob at a time
Once the schedule is controllable, vary one dimension at a time. Delay one operation relative to the other. Reverse the arrival order of two responses. Advance the fake clock by different amounts. Each variation tests one ordering assumption.
| Scheduling control | Serialized result | Concurrent result | Diagnosis |
|---|---|---|---|
| Response A delayed | Passes | Fails | Code assumes A arrives first |
| Response B delayed | Passes | Passes | B’s timing is not load-bearing |
| Timer advanced past timeout | Passes | Fails | Timeout outruns the handler |
| Two concurrent writes | Passes | Fails | Last write wins without a guard |
Changing one dimension at a time is what identifies which assumption breaks. Changing several at once can produce a failure that points at the wrong operation, and the fix then addresses an assumption the system does not actually make.
Property-based testing automates a related search over inputs. Hypothesis documentation describes generating inputs and shrinking failures, which is the input-space analog of varying a schedule (F033). The property tests guide covers that approach.
Capture the interleaving that fails
When a variation fails, record the exact interleaving: which operation ran, in what order, and what shared state each one observed. That record is the failing schedule, and it is what the regression test has to reproduce.
| Interleaving | Assertion that fails | Fix candidate | Residual risk |
|---|---|---|---|
| Read, read, write, write | Counter is one increment short | Atomic read-modify-write | Other writers outside this path |
| Two refreshes in flight | Second refresh invalidates the first | Single-flight refresh | Token revocation timing |
| Navigate before save resolves | Draft write cancelled | Await save before navigate | User navigates away anyway |
| Timeout before handler | Stale value rendered | Cancel the stale result | Very slow handlers |
Capture the interleaving before writing the fix. A fix written from the symptom rather than from the recorded schedule often closes the specific interleaving that was observed and leaves the adjacent ones open.
Ask Claude Code to name the ordering assumption
Give Claude Code the failing interleaving and ask it to state the ordering assumption the code makes. The assumption is a sentence such as “the code assumes the first response has been applied before the second is processed.” That sentence is what the fix addresses and what the regression test encodes.
Official Claude Code best practices recommends precise prompts naming files and symptoms. The useful prompt here names the file, the failing interleaving, and the shared state, and asks for the assumption rather than for a fix. A fix proposed before the assumption is named frequently addresses the symptom and leaves the class of race open.
| Failing interleaving | Assumption the code makes | Regression test encodes |
|---|---|---|
| Two responses reversed | First-sent arrives first | Reverse the arrival order |
| Timeout outraces handler | Handler completes within the timeout | Advance the clock past the timeout |
| Concurrent writes | Reads and writes are atomic | Interleave two writers |
The minimal repro method applies to the captured interleaving: reduce it to the smallest schedule that still fails before writing the fix.
Add a deterministic regression test
The regression test reproduces the recorded interleaving on demand and asserts the observable result that was wrong. It should fail against the unfixed code and pass against the fixed code, deterministically, without sleeps.
| Test ingredient | Purpose | Anti-pattern to avoid |
|---|---|---|
| Fake timers with explicit advance | Deterministic clock | Real timeouts that vary by machine |
| Fixed promise resolution order | Deterministic interleaving | Sleeping and hoping |
| Assertion on observable state | Checks the result | Asserting on internal scheduling |
| No arbitrary delays | Runs fast and reliably | A sleep that masks the race |
An arbitrary sleep is the specific anti-pattern this section exists to prevent. A test that passes because it waited longer has not fixed the race; it has moved the failure to a slower machine or a busier day. Vitest’s explicit timer advancement exists precisely so the clock is controlled rather than approximated (F031).
One deterministic interleaving does not cover all schedules. Record which interleaving the test guards and which adjacent interleavings remain untested. A test that claims to cover “the race” when it covers one schedule creates false confidence, and the false confidence is more expensive than the missing test because it ends the investigation early.
Review the new test against the same standard as any other regression test. Mutation testing for weak assertions checks whether it would fail against a mutant that removes the fix.
Treat the suspect path as a bounded surface, and where the same ordering assumption appears in several places, duplication and reuse independence addresses the copies that a fix in one place will miss.
Worked example: two concurrent refreshes
Suppose an API client refreshes an expired token before retrying a request. Two requests fire while the token is expired. Both see the expired token, both start a refresh, and the second refresh invalidates the token the first obtained. The retry then fails with an authorization error intermittently.
Describe the competing operations: two refresh calls, triggered by two concurrent requests, sharing the token store. The expected order is that the second request reuses the token the first obtained.
Control the schedule with fake timers and an injected token fetch. Serialize the path by making the second request await the first refresh. The test passes, which establishes the logic is correct under a guaranteed order.
Vary one dimension. Allow both refreshes to start before either resolves. The test fails deterministically with the authorization error, and the failing interleaving is recorded: refresh A starts, refresh B starts, refresh A resolves and stores a token, refresh B resolves and overwrites it with a different token.
Ask Claude Code to name the assumption. The code assumes a refresh started after another has begun will not complete before the first stores its result. The regression test encodes the reverse: it starts both refreshes, resolves them in a fixed order, and asserts the token store holds one consistent token.
The fix is a single-flight refresh: concurrent callers share one in-flight promise. The test fails against the unfixed client and passes against the fixed one, deterministically, with no sleeps.
The concrete win is a race that reproduces on demand and a regression test that fails if the single-flight guard is removed. The concrete loss is that the test covers one interleaving, and adjacent schedules involving token revocation remain untested. The practical implication is to capture the failing interleaving before writing the fix, and to treat the deterministic test as covering a recorded schedule rather than the whole space of schedules.
Connect the method to the rest of the batch
Concurrency failures are one branch of debugging in this batch. A captured interleaving should be recorded with the debug log that separates facts from hypotheses, and reduced with the minimal repro method before the fix is written. A trigger that only appears at a boundary value is a case for property tests for edge cases, which generate candidate inputs automatically.
Shared state across tests rather than within one operation is a fixture problem, addressed by test fixtures that isolate shared state, and the flaky test triage guide covers classifying the failure before investigating it. A shared resource that is memory or an allocation calls for comparing allocation snapshots as the measurement method.
The regression test the method produces is only as good as its assertions. Mutation testing for weak assertions checks that the new test would fail against a mutant that reintroduces the race, and snapshot review prevents the recorded schedule from being approved without inspection.
Related controls include deterministic handling of time and randomness for the broader class of non-determinism, and property tests for edge cases for the input-space search that complements schedule variation. Where the race crosses a service boundary, contract tests for API expectations pins the promise the client relies on. When the failure only appears at scale, selecting tests for changed code keeps the schedule variations fast enough to run on every change.
Investigation hygiene applies here too. Selecting tests for changed code keeps each schedule variation fast, and static analysis baseline can name the unsynchronized access a review would miss. Where the concurrency spans many files, refactoring complexity hotspots addresses the structure that makes ordering hard to see, and dead code removal removes operations that never run but still suggest an ordering the reader has to reason about. For an investigation that touches many files at once, auditing the context already loaded keeps the suspect path small enough to reason about.
Fixes land reviewably with atomic commits and commit messages that record change intent. Where a race blocks merges intermittently, the merge queue guide explains why retries can mask it. When a race has already reached production, git bisect for regression hunts finds the change that introduced the ordering assumption.
Data gap and future update
The fact pack contains no measured detection rate for schedule variation, no benchmark comparing fake-timer tests with sleep-based tests, and no evidence that Claude Code consistently identifies ordering assumptions correctly. No such number is claimed here.
Vitest documentation describes explicit fake-timer advancement (F031) and does not claim coverage of every interleaving. Pytest documentation lists thread-safety as a possible cause of non-deterministic behavior (F032) without diagnosing a specific race. The serialize-then-vary method is a derived debugging strategy (F033), not a guarantee of complete race detection.
A future update should add a reproducible case study with the number of interleavings tested, the one that failed, and the regression test that encodes it. Framework timer APIs change; recheck the cited pages before publishing and preserve the caveat that timer control does not model every interleaving.
One AI API Key option for OpenAI-format agents
Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.
For a separate OpenAI-format agent, One AI API Key provides https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. That option concerns a different client and request format, not a workaround for Claude Code authentication or quota. Review the free model list and eligibility details before choosing an agent route.
FAQ
Does a passing serial run prove the race is fixed?
No. A serial run proves the logic is correct under one guaranteed order. It does not explain the concurrent failure, and removing concurrency changes the system. The concurrent case still needs a deterministic test.
Are sleeps acceptable in a race test?
No. A sleep makes a test pass by waiting longer, which hides the race on fast machines and surfaces it on slow ones. Vitest’s explicit fake-timer advancement (F031) exists so the clock is controlled rather than approximated.
Does one deterministic test cover all schedules?
No. A test covers the interleaving it encodes. Record which schedule the test guards and which adjacent interleavings remain untested, because claiming full coverage creates false confidence.
Can Claude Code find the race automatically?
It can name the ordering assumption from the failing interleaving, which is a useful step. The evidence pack contains no measurement that it detects races reliably on its own, so no detection claim is made.
What if the race involves real threads?
Timer control does not model thread interleaving (F031). Pytest lists thread-safety issues as a source of non-deterministic behavior (F032). Thread-level races need synchronization at the shared resource, and the test strategy is to serialize access and verify the guard rather than to schedule the threads.
More Claude Code troubleshooting
- Claude Code Git Stash: Recover Work Without Dropping It
- Claude Code Git Rebase: Choose a Branch Policy
- Claude Code Merge Conflicts: Resolve Behavior, Not Lines
- Claude Code Branch Protection: Define Merge Checks
- Claude Code SemVer: Decide Major, Minor, or Patch
- Claude Code Release Tags: Use Annotated Markers
- Claude Code Hotfix Backports: Cherry-Pick Carefully
- Claude Code Rollback: Plan a Revert Before Release
- Claude Code Changelog: Write Consumer-Facing Changes
- Claude Code Release Checklist: Verify the Candidate
Sources
- Official: Vitest timers, supporting explicit fake-timer advancement (F031).
- Official: Vitest timer API, supporting the specific timer control surface.
- Official: Jest timer mocks, supporting the equivalent control in Jest.
- Official: Pytest flaky tests, listing thread-safety as a non-determinism cause (F032).
- Independent: Hypothesis documentation, supporting generated inputs and shrinking as the input-space analog (F033 context).
- Official: Claude Code best practices, supporting precise investigation prompts with named files.