Blog
fix flaky testsflaky testsflaky test detection

How to Fix Flaky Tests with AI: Find, Reproduce, Repair

A step-by-step guide to fix flaky tests: measure flake rate, reproduce failures, use AI prompts to find the cause, and verify the fix actually holds.

Portrait of Luis Chavez-Mattos
Edited by Luis Chavez-Mattos, Director, Product··RSS

For Engineering and Managers

Three comic panels: a man squints, then compares two blank log printouts under a magnifying glass beside a colleague, and a close-up of the lens reveals one small bright mark.

How do you fix flaky tests?

You fix flaky tests by measuring which ones fail intermittently, reproducing the failure on demand, identifying the cause (usually timing, shared state, test order, time, or an outside service), fixing that cause instead of adding retries, and then running the test many times to prove the fix holds. AI helps most with the middle steps: comparing passing and failing logs, sorting failures into cause categories, and proposing hypotheses you then confirm by reproducing the failure.

A flaky test is one that passes and fails on the same code. It erodes trust in the whole suite, because people stop believing red builds. This guide gives you a process you can run this week, with prompts to paste.

TL;DR

  • Measure before you fix. Record pass and fail per test per run so you can rank tests by flake rate and by how many builds they block.
  • Reproduce first, theorize second. A fix you cannot verify against a reproduction is a guess, and AI guesses fluently.
  • Most flakes fall into a few causes: timing and async waits, shared state, test order, time and randomness, and external dependencies.
  • Use AI as an analyst, not a judge. It is good at reading logs and spotting patterns, and it is unreliable about what actually happened on your CI machine.
  • Do not accept retries, longer sleeps, or loosened assertions as fixes. Retries are a diagnostic tool and a short-term bandage.
  • Prove the fix statistically. If a test fails 1 run in 20, one green run means nothing. Run it at least 60 times, and several hundred for rarer flakes.
  • Quarantine with an owner and a deadline so flaky tests stop blocking everyone without disappearing.

What makes a test flaky?

A test is flaky when its result depends on something the test does not control. The code under test has not changed, but something else varied between runs. Almost every flake traces back to one of these:

CauseWhat it looks likeTypical fix
Timing and async waitsFails more on slow CI machines; "element not found" or "expected X, got undefined"; a sleep somewhere nearbyWait for a condition or event, not a fixed time
Shared statePasses alone, fails in the full suite; leftover rows, files, or globalsIsolate and clean up per test; use unique data
Test order dependenceFails only when another test runs first or not at allMake each test set up its own world; shuffle order in CI
Time, dates, randomnessFails near midnight, month end, DST changes, or on certain random valuesInject a fake clock; seed random values
External servicesNetwork timeouts, rate limits, third-party outagesStub or mock at the boundary; keep a few real contract tests separate
Concurrency and race conditionsRare, inconsistent failures with threads, queues, or parallel workersFix the race in the code (it may be a real bug), not the test
Resource limitsFails on CI only; out of memory, port already in use, slow diskUse free ports, bound resources, give tests realistic timeouts
Environment differencesLocale, timezone, OS, or dependency versions differ between laptop and CIPin versions; set locale and timezone explicitly

One point worth stating plainly: a flaky test is sometimes a correct test catching a real, intermittent bug. A race condition in production code will show up as a flaky test first. Do not assume the test is the broken part.

How do you find which tests are flaky?

You need history, not memory. "That test always fails" is how teams remember flakes, and it is usually wrong about which ones cost the most.

Step 1. Collect results per test, per run. Most CI systems can export test results (JUnit XML is a common format). Store, for each run: test name, result, commit, branch, duration, runner, and timestamp. A spreadsheet works to start. A database is better once you have a few weeks of data.

Step 2. Identify flakes with two signals.

  • Same commit, different result. If a test fails and then passes on a rerun of the identical commit, it is flaky by definition.
  • Fails on main. A test that fails on a branch already merged to main, with no related change, is a strong suspect.

Step 3. Rank by cost, not by annoyance. For each flaky test, calculate:

  • Flake rate: failures divided by total runs, on commits where the failure was not a real regression.
  • Blast radius: how many pipelines it blocked or forced to rerun.
  • Time cost: rerun minutes multiplied by the number of reruns.

Fix the top three by blast radius first. A test with a 2% flake rate in a test that runs in every pipeline can hurt more than a 30% flake rate in a rarely run job.

Step 4. Use AI to cluster the failures. Export the failure messages for the last few weeks and have AI group them. Many different test names often share one root cause, such as a shared test database or one slow dependency.

Paste this:

Below are failure messages from our CI for tests that
failed and then passed on rerun of the same commit.
Each line: test name | failure message | runner | date.

Group them by likely root cause. For each group give:
1. A short label for the suspected cause
2. The tests in the group
3. What evidence in the messages supports the grouping
4. What additional information would confirm or reject it

Do not propose fixes yet. If a message is too vague to
classify, put it in an "unclear" group instead of guessing.

[paste data]

The last instruction matters. Without it, AI will assign every row to a category to look complete.

What to check: Pick two or three tests from each group and read their actual logs yourself. If the grouping does not hold up for those, discard it.

How do you reproduce a flaky test?

Reproduction turns a mystery into a normal bug. Try these in order, from cheapest to most involved.

  1. Run the test alone, many times. Most test runners have a repeat option. In Python, the pytest-repeat plugin gives --count=200. In Go, go test -count=200. If it never fails alone, the cause is probably shared state, order, or load.
  2. Run the whole file or suite in a loop. If it fails only with neighbors, it is state or order related.
  3. Shuffle the order and keep the seed. In pytest, pytest-randomly shuffles order and prints a seed; rerun with --randomly-seed=<seed> to replay a failing order. Many other runners have an equivalent.
  4. Match CI conditions. Limit CPU (for example docker run --cpus=1), run tests in parallel the way CI does, and use the same container image. Timing flakes often appear only when the machine is slow.
  5. Turn on race detection where available. Go has -race. Other languages have thread sanitizers or similar tools.
  6. Change the clock. Run the test with the system date set to month end, a leap day, or just after midnight in a different timezone.
  7. Add logging to the failing path. Log timestamps, thread or worker IDs, and key state right before the assertion. Rerun in a loop until it fails, and keep that log.

Once you have one failing run with detailed logs and one passing run with the same logging, you have what AI needs.

How can AI help find the root cause?

AI is useful here because the work is reading two long logs and spotting the difference. It is tedious for people and quick for a model. Give it evidence, not a description.

Paste this:

I have a flaky test. It passes most runs and fails
occasionally on the same code.

Test code:
[paste the test and any fixtures/setup/teardown]

Code under test (relevant parts):
[paste]

Log from a FAILING run:
[paste]

Log from a PASSING run:
[paste]

Environment notes: [CI runner type, parallel workers?,
database shared?, language/framework versions]

Do the following:
1. List the differences between the two logs that could
   matter, in order of relevance.
2. Give up to three hypotheses for why the result varies.
   For each: what it predicts, and one experiment I can
   run to confirm or rule it out.
3. Say which hypothesis you think is most likely and why.
4. List what you cannot tell from the information given.

Do not suggest adding retries or increasing sleep times.
Do not change any assertions.

Notice the structure. It asks for experiments, not just answers, which keeps you in the loop of confirming by reproduction. It also forces the model to state what it cannot know.

What to check in the answer:

  • Does every claim point to a specific line in your logs? Ask for line references if not.
  • Do the hypotheses make different predictions? If all three are vague variants of "timing issue," ask for sharper ones.
  • Run the proposed experiment. A hypothesis is not confirmed until the failure either appears or disappears on command.

Where AI should not be trusted:

  • Stating the cause as fact. A model has not seen your CI machine, your database state, or your network. It sees text you pasted.
  • Reading code it was not given. If the cause lives in a helper or config file you did not paste, it will fill the gap with a plausible story.
  • Sensitive data. Logs can contain tokens, customer data, and internal hostnames. Use only the AI tools your company has approved, and scrub secrets first.

How do you fix each type of flaky test?

Once the cause is confirmed, the fix is usually small. Here are the common patterns.

Timing and async: wait for the condition.

Bad:

click_submit()
time.sleep(2)
assert page.has_text("Saved")

Better:

click_submit()
wait_until(lambda: page.has_text("Saved"), timeout=10)

A fixed sleep is a bet about machine speed. A condition wait passes as soon as it can and tolerates slow runners. Most UI test frameworks have built-in auto-waiting or explicit wait helpers, so use them.

Shared state: give each test its own data.

Use unique identifiers per test (a random suffix on emails and names), create what the test needs in setup, and remove it in teardown. If tests share a database, wrap each in a transaction that rolls back, or use a fresh schema per worker.

Order dependence: make setup explicit.

If test B needs a user that test A creates, B should create its own. Run the suite in random order in CI so new dependencies surface immediately.

Time and randomness: inject them.

Pass a clock into the code, or use your language's time-freezing tool, so tests control "now." Seed random generators and log the seed when a test fails so you can replay it.

External services: stub at the boundary.

Unit and integration tests should not depend on the internet. Replace third-party calls with fakes. Keep a small, separate set of contract tests against the real service, and run those on a schedule rather than on every commit.

Race conditions: fix the code.

If the flake is a real race in production code, the test is doing its job. Fix the locking, ordering, or idempotency problem in the code itself.

Paste this to have AI propose a fix:

Root cause (confirmed by reproduction): [describe it]

Test code:
[paste]

Propose the smallest change that removes this cause.
Rules:
- Do not add retries or fixed sleeps.
- Do not weaken or remove assertions.
- Do not skip or disable the test.
- If the real problem is in the production code, say so
  and show that fix instead.
Explain in two sentences why your change removes the
cause, not just hides it.

What to check: Read the diff for the three classic cheats: a new sleep, a wider tolerance on an assertion, or a try/except that swallows the failure. AI proposes these often because they make red turn green fastest.

How do you know the fix worked?

A test that fails 1 time in 20 will pass 20 times in a row about 36% of the time. So one green run, or even ten, proves almost nothing.

A useful rule of thumb (the "rule of three"): if you observe zero failures in N runs, you can be roughly 95% confident the true failure rate is below 3 divided by N. To be reasonably sure a 1-in-20 flake is gone, run it at least 60 times, and more is better. For a 1-in-100 flake, run several hundred.

Practical steps:

  1. Run the fixed test in a loop under the same conditions that reproduced the failure (limited CPU, parallel workers, shuffled order).
  2. Run it the same number of times on the old code to confirm your loop actually reproduces the failure. If the unfixed version also passes 300 times, your loop is not a valid test.
  3. Merge, then watch the failure data for a couple of weeks. Your Step 1 history will tell you whether the rate dropped to zero.

What should you do with flaky tests you cannot fix yet?

Quarantine them. Do not delete them, and do not leave them blocking merges.

  • Move the test to a separate job that still runs and reports but does not gate the pipeline.
  • Give every quarantined test an owner, a ticket, and a deadline. A quarantine without an owner is a graveyard.
  • Review the list weekly. Set a rule such as: quarantined for more than 30 days means fix it or delete it with a written reason.
  • Treat automatic retries as a diagnostic. Retrying a failed test and recording that it passed on the second try is a good way to detect flakes. Using retries to hide them lets the problem grow quietly.

For managers: track flake rate and rerun time as numbers the team sees. Hours lost to reruns are easy to convert into a cost, which makes it easier to get time on the sprint for this work.

How do you stop new flaky tests from arriving?

  • Run new and changed tests many times in CI before merge (for example 20 to 50 repeats) so obvious flakes never reach main.
  • Shuffle test order on every run and print the seed.
  • Ban fixed sleeps in review, with a lint rule if your tools support it.
  • Block real network calls in unit tests by default.
  • Ask AI to review new tests for flake risk. This works well as a checklist pass:
Review this new test for flakiness risks. Check for:
fixed sleeps, dependence on current time or randomness,
shared or hardcoded data, reliance on test order,
real network calls, and unbounded waits.
List each risk with the line number and a one-line fix.
If you find none, say so instead of inventing issues.

[paste test]

Could you build your own flaky test tracker?

Most teams stall at Step 1 because the data lives in CI logs and nobody owns a place to analyze it. A small internal app fixes that. With Remy, you can describe a flaky test tracker in plain English: a page that receives test results from your pipeline, stores them in a database, ranks tests by flake rate and blocked builds, lets you assign an owner and quarantine status, and sends a weekly summary. Remy builds it as a full-stack app you own, with sign-in for your team. You would still need your CI to send results to the app, so check what export or webhook options yours offers before you start.

Frequently Asked Questions

5 questions

Can AI fix flaky tests automatically?

Not reliably. AI can propose fixes quickly, but it cannot confirm a cause without a reproduction, and it often suggests retries or longer sleeps that hide the problem. Use it to analyze logs and draft changes, then verify with repeated runs.

Is it okay to just retry flaky tests in CI?

Retries are fine as a short-term measure and as a way to detect flakes, as long as you record every retry that rescued a test. They become a problem when they are the only response, because the flake rate keeps climbing while the builds look green.

How many flaky tests is too many?

There is no universal number. The practical test is whether engineers rerun red builds without looking at them. When that habit appears, the suite has lost trust and flaky tests are the top priority, even if the percentage looks small.

Should I delete a flaky test I cannot fix?

Only after you ask what it was protecting. If the behavior still matters, rewrite the test at a lower level (a unit test instead of an end-to-end one often removes the timing and environment issues). If it covers nothing important, delete it and write down why.

Why do tests pass locally but fail in CI?

CI machines are usually slower, run tests in parallel, share resources, and differ in timezone, locale, and dependency versions. Reproduce with limited CPU, the same container image, and the same parallelism as CI, and the failure often appears locally.

How we source, write, and correct our articles. Editorial standards

Related articles

The AI Brief, presented by Remy
The week in AI, and what it means for your work. Every Friday.