Skip to navigation

Claude Code Flaky Tests: Triage Before You Rerun

In short: Capture failure signatures, isolate order and state leaks, then quarantine only with an owner and an expiry date.

Published 21 min read
On this page

Direct answer

Treat an intermittent failure as evidence about state, ordering, timing, or the assertion itself, and investigate before rerunning. Pytest defines a flaky test as one that fails intermittently or sporadically and behaves non-deterministically. The definition describes the symptom, not the cause, so the first task is to capture the failure signature: which test, which input, which order, which environment, and what the assertion actually compared.

The sequence that works is reproduce, vary one variable at a time, form a falsifiable hypothesis, then decide. Reruns belong inside that sequence as a diagnostic signal. A passing rerun is not a fixed test, and a retry configuration is not a response to flakiness. It hides the condition and leaves the intermittent failure in the critical path.

Quarantine is the right tool when the investigation needs more time than the change can wait. A quarantine without an owner, a reason, and an expiry date is a deletion that has not been admitted yet. The record should also state how the test gets restored, so the exception has an end.

Why an intermittent failure is expensive

A flaky test costs more than the seconds it takes to rerun. The first cost is trust. Once a test is known to fail randomly, engineers stop reading its failures, and a real regression in that test arrives wearing the same costume as noise. The second cost is the retry loop itself: a run that passes on the second attempt still consumed the first attempt, the person watching it, and often a pipeline slot. The third cost is the decision it forces under pressure, which is usually to disable the test and move on.

That last decision is where a small reliability problem becomes a permanent coverage gap. A test removed during an incident is rarely restored with the same urgency. Recording the removal as a quarantine with an owner and a date converts an untracked loss into a tracked exception with a named person responsible for ending it.

A change in flight pays a cost too. A flaky test inside the selected set for a pull request competes with the real signal, and reviewers waste attention separating a genuine break from the known flake. The test selection guide argues for recording skipped scope, and a quarantined test belongs in that record explicitly rather than in someone’s memory.

Evidence map from a failure signature to shared state, a rerun signal, and a tracked quarantine record.
Editorial evidence map based on F004, F005, and F006. A rerun can reveal instability; it cannot explain the instability, and the quarantine record is an operational recommendation rather than a tool requirement.

Evidence and its limits

Official, F004: The Pytest flaky tests page defines a flaky test as one with intermittent or sporadic failure and non-deterministic behavior. This gives the term a shared meaning. It does not identify the cause in any specific test, and it does not say how often a test must fail to count.

Official, F005: The same Pytest page lists possible causes, including uncontrolled system state, overly strict assertions, and thread-safety issues. These are candidate hypotheses to test against a specific failure. Reading the list is not a diagnosis, and a test can be flaky for a reason the list does not mention.

Derived, F006: A quarantine record should carry an owner, a reason, an expiry, and a plan to restore the test. This is an operational recommendation for keeping an exception visible. It is not a Claude Code requirement and not a feature of any test runner.

Official: Pytest logging documents capturing log output during a test run, which is how a failure signature acquires context beyond the assertion message. The specific configuration belongs to the repository.

No measured flake rate, retry threshold, or defect-detection improvement is claimed. The fact pack contains no benchmark for triage method and no reproducible community run.

Define the flaky failure signature

A failure signature is the minimum description that lets someone else reproduce the same failure without asking questions. Vague signatures produce reruns. Specific signatures produce hypotheses.

Capture these fields the first time the failure appears:

Field What to record Why it matters
Test identity File, test name, and the case or seed Names the exact unit that failed
Assertion What was compared, expected versus actual Separates a wrong value from a wrong type of value
Frequency Fails one in ten, one in two, or once a week Sets the cost of investigation
Order Ran alone, in a file, or in a randomized suite Points at ordering and leakage
Environment Local, container, CI runner, operating system Separates machine state from code
Timing Fails on first run of the day, after a long run, under load Points at time and resource assumptions

The frequency field deserves special care. A test that fails one run in a hundred is a different problem from one that fails one in three, and the second is usually cheaper to diagnose because the signal is dense enough to iterate against. When a failure is genuinely rare, the first move is often to record it and add observability rather than to start changing code.

The debug log guide covers the companion discipline: write the observation before forming the explanation. A signature recorded after the first hypothesis is already filtered by that hypothesis.

Reproduce the same test repeatedly

The cheapest reproduction is a loop around the single failing test. Running the one test many times, rather than the whole suite, removes most of the variables at once. If the test fails in isolation, ordering and cross-test state are probably not involved. If it never fails in isolation, the next step is the suite.

A representative loop shape, adapted to the repository’s runner:

for i in 1 2 3 4 5 6 7 8 9 10; do
  <run one named test> || echo "FAILED on attempt $i"
done

Record the result of each attempt rather than summarizing. A run that failed twice in ten attempts has a frequency you can compare after the next change. A run described as “sometimes fails” cannot be compared with anything.

Reproduction also has a failure mode worth naming: the reproduction can be too stable. A test that leaks state from a specific earlier test will pass reliably when run alone. Isolated reproduction then produces a false clear, and the conclusion “cannot reproduce” is wrong in a specific way. That is why the next step varies order rather than only repeating the test.

When a single test cannot be made to fail, the minimal repro guide covers shrinking the surrounding case while keeping the failure signal intact. The same reduction discipline applies to flakiness: remove one variable at a time and confirm the failure still appears.

Vary order, time, and shared state

Ordering is the first variable to vary because it is cheap and it implicates a specific class of defect. If the suite randomizes order, run the failing test before and after its neighbors. If it does not, reverse a small group of tests around the failure and see whether the failure follows the group or the individual test. A failure that moves with position is a leakage symptom.

Pytest’s guidance behind F005 lists uncontrolled system state as a candidate cause, and that is what order variation tests. A test that writes a file, mutates a module-level variable, leaves a database row, or changes an environment variable can hand the next test a precondition the next test never declared. The failure then appears in the wrong test, which is what makes flakiness hard to reason about from the assertion alone.

Time is the second variable. A test that depends on the current clock, on a timeout, on a delay, or on two events arriving in a particular order can fail when the machine is slower or faster than usual. Controlled time is covered separately in the deterministic tests guide, which explains how to freeze the clock and advance timers deliberately. For triage, the immediate question is whether the failure correlates with elapsed time or with a timestamp boundary such as a date rollover.

Shared state is the third variable, and it overlaps with ordering. Fixtures that promise a fresh boundary but reuse a connection, a cache, or a seeded table can produce failures that look like ordering problems. The fixtures isolation guide covers making setup explicit and naming cleanup ownership. During triage, the practical test is to give the suspect test a fully fresh boundary and see whether the failure survives.

Variable Controlled change Observation that implicates it
Order Run the test alone, then within a group Fails only in the group
Time Freeze or advance the clock deliberately Fails near a timeout or date boundary
Shared state Give the test a fresh fixture boundary Failure disappears with isolation
Concurrency Run the test serially, then in parallel Fails only under parallelism
Load Add or remove competing work Fails under resource pressure
Workflow from a recorded failure signature through reproduction, one-variable variation, hypothesis, and quarantine decision.
Editorial workflow based on F004, F005, and F006. Each step narrows a hypothesis; none of the steps turn a passing rerun into a repair.

Inspect assertions and test boundaries

Not every intermittent failure is a broken test. Some are correct tests failing because production code has a race or an unhandled boundary. The distinction matters because the responses are opposite: one needs a fix in the test, the other needs a fix in the product.

Pytest lists overly strict assertions as a candidate cause behind F005. An assertion can be stricter than the contract it is meant to check. Comparing a rendered timestamp exactly, comparing floating-point output without a tolerance, or asserting on the order of items that have no defined order all produce intermittent failures that say nothing about correctness. The fix is to assert on what the contract actually promises.

An assertion can also be too loose in a way that only shows up intermittently. A check that verifies a value exists but not what it is will pass most of the time and conceal a race. The mutation testing guide covers this from the assertion-quality direction: a surviving mutant shows which checks could not fail even when they ran.

Boundaries deserve the same reading. A test that crosses a real network, a real clock, a real filesystem, or another process depends on conditions outside the test’s control. The fix is usually to move the dependency behind a boundary the test owns, which is the determinism problem described in the async races guide. That guide treats scheduling as the thing to make explicit rather than a source of sleeps.

Failure signature Candidate cause Response
Timestamp or ID mismatch Uncontrolled clock Freeze time at the test boundary
Order-dependent list comparison Missing sort or unspecified order Assert on the contract, not incidental order
Floating-point mismatch Representation, not logic Compare with a tolerance
Fails only in parallel Shared mutable state Isolate fixtures and boundaries
Fails after a specific delay Timeout too tight for slow machines Control the timer explicitly

Use reruns as diagnostic signals

Reruns have a legitimate use in triage, and it is narrower than the way they are usually deployed. A rerun tells you whether a failure is reproducible. A sequence of reruns under controlled conditions tells you a frequency. Neither tells you the cause.

The distinction matters when a runner offers automatic retries. A retry configuration converts a reproducible failure signal into a probability, which is useful for keeping a pipeline moving and useless for understanding the defect. A retry also changes the record: a run that passed after three attempts is recorded as green, and the two failures disappear from the history that would have justified an investigation.

Use reruns deliberately during triage:

  1. Establish that the failure reproduces at all, with a loop around the single test.
  2. Measure a rough frequency so a later change can be compared fairly.
  3. After one controlled change, rerun the same loop and compare the frequency.
  4. Stop rerunning when the frequency is stable and the hypothesis is formed.

If the failure does not reproduce after a reasonable loop, record that result honestly rather than closing the investigation. A rare failure with no reproduction is still a real observation, and it belongs in the quarantine record with the conditions that were tried. The snapshot review guide covers a related honesty point in a different context: an update command records a decision, and it does not make the decision correct.

The flaky definition behind F004 is also a reminder that intermittency is the defining property. A test that fails every time under one configuration is a broken test with a configuration problem, not a flaky one, and the response is a fix rather than a quarantine.

Tradeoff between retrying a flaky test to keep moving and losing the failure signal needed to diagnose it.
Editorial tradeoff diagram based on F004 through F006. Retries preserve throughput and destroy the signal that triage depends on, which is the cost this post asks readers to weigh.

Ask Claude Code for a falsifiable hypothesis

Once the signature is recorded and one variable has been varied, the agent has enough to work with. The official guidance behind the best practices page supports giving the agent a pass-or-fail check and naming files and symptoms. A flaky test is a good fit for that shape, provided the ask is specific.

Ask for a falsifiable hypothesis rather than a fix. A useful prompt names the test, gives the recorded signature, states what has already been varied, and asks for the single most likely cause plus the experiment that would confirm or refute it. The resulting request produces something a reviewer can check. A request for “fix the flaky test” produces a diff that may pass by coincidence.

Two boundaries keep the agent useful here. First, a hypothesis is a prediction, and it must be tested before it becomes a fix. The debug log guide covers recording the prediction before the observation so the record cannot be rewritten after the fact. Second, a fix that removes the failing assertion is not a fix. If the proposed change weakens the check, that is a decision for the test’s owner, not an implementation detail.

When the hypothesis points at state leakage rather than timing, the fixtures isolation guide covers the isolation work. A hypothesis pointing at uncontrolled time calls for the deterministic tests guide, which covers freezing the clock and advancing timers explicitly. A concurrency assumption calls for the async races guide, which covers making the ordering deterministic before trusting a passing run.

Quarantine with ownership and expiry

Quarantine is a tracked exception. The test keeps existing, the suite reports it separately, and a named person is responsible for ending the exception. This is the derived recommendation behind F006, and the reason for it is straightforward: an untracked quarantine is a permanent coverage loss that nobody agreed to.

A quarantine record needs five fields:

Field Content Failure mode if missing
Test File, test name, and the affected case Nobody can find what was disabled
Owner One team or person responsible for the decision The exception outlives everyone who understood it
Reason The recorded signature and current hypothesis The next reader cannot judge severity
Expiry A date when the quarantine is reviewed or removed Silence becomes permanent
Restore plan What has to be true for the test to return Removal looks like progress
Quarantined test Owner Reason Expiry Tracking reference
orders_export scheduled-job case Orders team Fails without job fixture, no repro in isolation 30 days TICKET-2187
search_ranking ordering comparison Search team Overly strict order assertion 14 days TICKET-2203
invoice_total currency case Billing team Fails near month boundary under real clock 21 days TICKET-2211

The expiry deserves emphasis because it is the field most often left out. A quarantine without a date is a decision deferred forever, and the coverage gap it creates is invisible in every report that counts passing tests. Review the quarantine list on a schedule, and treat an expired quarantine as either a restored test or a deliberate deletion with a recorded reason.

Quarantine is also not the only response to a failing test in a selected run. The test selection guide covers recording skipped scope, and a quarantine is one specific kind of skip: one with a name, a cost, and an end date.

Control checklist covering a recorded signature, varied variables, a falsifiable hypothesis, and an owned quarantine with expiry.
Editorial control checklist derived from F004 through F006. Completing the checklist shows the exception was recorded honestly; it does not prove the flake is understood.

Close the flake with a regression case

A flake is closed when the underlying condition is either fixed or made deterministic, and when something would notice if it came back. The last part is the regression case, and it is the step most often skipped.

A state leak needs a regression case made of the two tests in the order that reproduced the failure. Keep that ordering deliberately, so a future leak in the same direction fails instead of hiding. A timing dependency needs a test with a controlled clock advanced past the boundary that used to fail. An over-strict assertion needs the assertion rewritten against the contract plus a test for the boundary that was being compared accidentally.

The regression case should be concrete rather than generalized. A comment saying “this used to be flaky” is weaker than a test that names the order, the boundary, or the input that exposed the condition. Concrete regressions also survive refactoring better, because a reader can tell whether the condition still exists. The property tests guide covers a complementary technique when the condition is a class of inputs rather than a single case.

After the fix, remove the quarantine entry and record the restoration. A closed flake that still appears in the quarantine list is a contradiction that erodes trust in the list itself.

Worked example: an export test that fails only in the suite

Suppose an export test fails roughly one run in four in CI and never locally. The recorded signature shows the failure is an assertion on row count: expected 12, got 11. The test runs last in its file. Running it alone ten times produces ten passes.

Varying order reproduces it: moving the test before a seeding test produces eleven rows reliably. The hypothesis is that the seeding test inserts a row asynchronously and the export reads before the write completes. The falsifiable form is “if the export waits for the seed write to complete, the count is 12 in every run”.

Executed step Observation Conclusion
Ten isolated runs Ten passes Not a defect in the test’s own logic
Test moved before the seeding test Fails reliably with 11 rows Ordering and shared state implicated
Export awaits seed completion Twelve rows in every run Timing of the write is the condition

The response is to make the write-to-read dependency explicit, then keep the reproducing order as the regression case. If the team cannot make that change inside the current pull request, the test is quarantined with an owner, the recorded order, and a thirty-day expiry, and the skip appears in the change record. The concrete win is a named condition instead of a coin flip. The concrete loss is that the quarantined case is not verifying anything until the fix lands.

Verdict that triage with recorded signatures and owned quarantine produces diagnosable flakes while reruns alone preserve the failure.
Editorial verdict based on F004 through F006. Triage produces a diagnosable condition and a bounded exception; retries alone preserve the flake and remove the evidence.

Stop conditions and follow-up

Stop the investigation and quarantine when the next experiment would take longer than the change can wait and the failure is understood well enough to describe. Stop and fix immediately when the failure indicates a product race rather than a test problem, because that class of defect does not belong behind a quarantine. Stop and escalate when the failure appears in several unrelated tests, which points at shared infrastructure rather than one test.

Follow-up takes three forms. A new flake in a previously stable area is a change to investigate, and Git history from git log shows when the area last changed. A flake that survives a fix belongs in the selected set again, with the reproducing order kept as a regression case. A quarantine approaching expiry is a scheduled decision, and the review should either restore the test or record a deliberate deletion.

Failures that only appear under concurrency are covered by the async races guide, which treats scheduling as something to control rather than something to sleep through. Uncontrolled time is the subject of the deterministic tests guide. Leaked fixtures are the subject of the fixtures isolation guide. A suspected slow leak rather than a test-order leak belongs with the memory leaks guide and its comparison of retained evidence across a fixed workload.

Triaging a flake sits inside a wider verification practice. Select checks for changed code decides which tests run at all, and snapshot diff review keeps a stored expectation from hiding the same condition. Contract tests for API expectations protect a boundary the flake was crossing.

Evidence discipline is covered by a debug log of facts and hypotheses, and a failure that needs a shrunken case belongs with minimal repro discipline. Deterministic time and randomness, isolated fixture state, and deterministic async scheduling cover the three causes this post treats as hypotheses. Assertion quality is covered by mutation testing, and a condition spanning a class of inputs is a fit for property tests.

Infrastructure symptoms are investigated differently. A suspected slow leak belongs with memory allocation snapshots. Git bisect locates the change that introduced a flake. Enforced checks are covered by choosing a branch policy, defining merge checks, and recovering a failed merge group. Quality work that keeps the selected set meaningful is covered by complexity-driven refactoring, choosing reuse or independence, and baselining static-analysis noise. Release verification questions are covered by deciding a version increment and the release checklist.

Data gap and future update

No measured flake rate, retry threshold, quarantine duration, or defect-detection improvement appears in the source set. The causes behind F005 are the Pytest page’s list of candidates, and no specific test in this post was diagnosed from them. The quarantine fields are a derived operational recommendation rather than a tool feature.

The framework pages in the source list were checked for reachability, and the retry and randomization configuration details belong to each repository’s version. A future update should add three things. A measured comparison of triage against retry-only handling on a real suite. A documented pattern for tracking quarantine entries over time. Fresh content review of retry and randomization flags before quoting specific framework behavior.

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 offers https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. That is a different client and request format, not a workaround for Claude Code authentication. See the free model list and eligibility notes before choosing a route.

FAQ

Does a passing rerun mean the flaky test is fixed?

No. F004 defines flakiness as intermittent, non-deterministic failure. A single pass is consistent with that definition and proves nothing about the condition. Compare a measured frequency before and after a change rather than reading one green run.

Should I enable automatic retries for flaky tests?

Retries keep a pipeline moving and destroy the signal triage needs. Treat a retry as a temporary measure with an owner and an end date, alongside a quarantine record, rather than as the response to flakiness. A retry that runs indefinitely is a permanent blind spot.

How long can a test stay quarantined?

Long enough to fix the underlying condition and no longer. F006 recommends an owner, a reason, an expiry, and a restore plan. An expiry without a review habit becomes a permanent exception, so the list needs a scheduled review as well as dates.

Can Claude Code diagnose the cause of a specific flake?

It can propose a falsifiable hypothesis when given the recorded signature, what has been varied, and a pass-or-fail check to test against. The hypothesis still needs a controlled experiment, and a proposed fix that weakens the assertion is a decision for the test’s owner rather than an implementation detail.

When is a flaky test actually a product bug?

When the intermittent failure reflects a real race, a missing boundary, or an unhandled state in production code. Overly strict assertions are the opposite case, where the test is wrong and the code is fine. F005 lists both classes as candidates, which is why the assertion and the boundary both need reading before choosing a response.

More Claude Code troubleshooting

Sources

  • Official: Pytest flaky tests, supporting the flaky-test definition (F004) and the list of candidate causes (F005).
  • Official: Pytest logging, reference for capturing log context during a run.
  • Official: Claude Code best practices, supporting pass-or-fail checks and named files and symptoms, and the derived quarantine record fields (F006).
  • Official: Jest configuration, reference for runner configuration including retry and randomization settings.
  • Official: Vitest configuration, reference for runner configuration.
  • Official: Git log, reference for history around a previously stable area.
More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
  • 100requests
    per day
  • 3Mtokens
    per day
  • 47free
    models
  • $0per
    token
  • No card
  • No end date
Claim $10 credit →