Topics
Recent articles

Product Engineering

How to Tell a Flaky Test From a Regression Before Rerunning CI

Preserve the first CI failure, compare candidate and baseline under matching conditions, and distinguish intermittent tests, regressions, and runner failures.

Table of Contents9 sections
Pixel art compares a passing baseline with a candidate that fails, passes, and fails again.
A passing rerun does not erase the first failure. Compare the candidate and baseline.

A CI test fails, you rerun the job, and it passes. Did you confirm that the pull request is safe? No. You learned that the failure did not occur on the second attempt. The next step is to find out whether the code change, the test, or the runner accounts for the difference.

Quick solution:

Keep the first failure. Repeat the same test with the same candidate commit and comparable inputs, then run the same check on the baseline. Classify the result from both sets of attempts rather than from the last green or red badge.

Before rerun: save test ID, first failure, checkout and runner
Then compare: candidate vs. baseline under matching conditions
Report: regression, intermittent failure, infrastructure, or unresolved

The counts below are fictional examples for a small, time-boxed diagnosis, not statistical thresholds or prescriptions for branch protection.

Keep the first failure before you touch the rerun button

Save the exact suite, test case, expected and actual values, and first relevant stack trace. Keep the original report or artifact, not a screenshot of the badge. It matters whether the app returned the wrong value, a fixture never started, or the job stopped before the test executable ran. A later attempt may overwrite a local report or leave the first result hard to find. Include the first attempt in the pull request or incident notes with a direct link.

Capture the source checkout and build configuration with the report. Record the actual commit under test, the run and attempt identifiers, the test task or command, and the variant. For failures on an Android emulator, capture the API level and device image if relevant. If the test used an artifact from an earlier job, record which artifact and digest it consumed. For a mobile test failure starting with an unknown binary, trace the Android QA APK back to its Git commit before making a comparison.

This information is usually cheaper to collect during the first red run than to reconstruct after it. Avoid logging environment variables wholesale. A dependency version or runner image can be shared with someone debugging the test; credentials and captured user data cannot be treated as ordinary failure evidence.

Separate a failing test from a failed job

There are several kinds of red. An assertion failure on a stable input can indicate a behavior change worth blocking. A test that alternates between pass and fail under comparable conditions is intermittent, but the reason can still be a product race rather than a bad test. A runner or dependency service can also fail before there is any test result. Assign each failure an owner based on what the evidence shows, not on the job’s name.

Look for the earliest event that explains the later errors. Twenty tests timing out while waiting for an emulator may have one startup failure rather than twenty broken behaviors. By contrast, a suite that starts normally and produces the same incorrect value in one case gives you a specific behavior to reproduce. Compare the first relevant assertion message, not just the final exit code. Collect failure signatures with enough detail to distinguish related incidents without storing full sensitive logs in a ticket.

Keep an unresolved category. A timeout after test startup could come from a fixture, a system under load, or an app operation that never completes. Keep investigating if the consequence is high, but give the result a name that doesn’t overstate it. “One timeout, not reproduced on known inputs” helps the next person more than “flaky, rerun fixed.”

Use one comparable rerun, not a new experiment by accident

Rerun a targeted job or test first if that can answer the question without rebuilding everything. In GitHub Actions, the workflow rerun documentation describes reusing the event’s SHA and ref. Still record what was actually checked out: a workflow might explicitly retrieve other sources or fetch inputs at runtime. The contexts reference distinguishes the run ID from the run attempt, which makes it possible to cite both attempts accurately.

Keep the test task, variant, seed if known, and important configuration constant for the first comparison. A new runner can still have a changed image or a transient service can recover. Compare resolved dependencies and the device environment rather than assuming the same source ref guarantees the same execution. Don’t introduce a new cache setting, increase a timeout, and patch the candidate at the same time. Those changes can be useful probes later, but they turn the first comparison into a different experiment.

The following example targets a local JVM test in a hypothetical Android app that has a testDebugUnitTest task. The command is not for an emulator or instrumented test. Replace the module, variant task, and class or method with the exact ones from your report. Gradle’s testing documentation describes the test filter and rerunning via the task execution options.

./gradlew :app:testDebugUnitTest \
  --tests 'com.example.inventory.StockCountTest.savesLatestCount' \
  --rerun-tasks

Check the report to confirm that the named test actually ran. A task that restored a result from cache or filtered out the relevant case isn’t a confirming pass. A test that passes alone can still fail in its suite because of ordering, shared fixture state, or parallel execution. After the isolated check, run it again with the original grouping if interaction is a plausible cause.

Compare the baseline against the actual candidate

Define candidate and baseline before comparing them. The candidate may be the tested merge checkout rather than the top commit of a branch. A sensible baseline is the base revision before the change, tested with the same checks and a comparable environment. A successful nightly run on a newer commit and a different runner is useful history, but it isn’t a controlled baseline. Note the dates if anything external may have changed since the original failure.

If the test did not exist on the baseline, don’t count its absence as a pass. When feasible, run the same independent diagnostic or compatible fixture against both builds. If a change intentionally alters behavior, make sure both are evaluated against an appropriate contract: a new assertion may correctly fail on the baseline because it tests a new feature. State that limitation and use a targeted reproduction rather than inventing symmetry.

Here is a practical way to write down the comparison. The sequences represent observed results, not enough runs to estimate a failure rate precisely. A repeated assertion means the same relevant failure signature, not merely a failed job badge.

What you observe Reasonable next call
Baseline passes repeatedly; candidate repeats the same assertion failure Strong regression signal. Review the change and the expected behavior.
Same candidate fails and passes with comparable inputs Intermittent under the observed conditions. Cause and ownership are still open.
Baseline is stable but candidate alternates Possible regression that introduced a race. Don’t dismiss it as pre-existing flake.
Baseline and candidate fail with the same signature Existing failure or shared dependency issue is plausible. Check recent history and environment.
Neither attempt reaches the test runner No test verdict. Restore the environment and rerun the intended test.
Only one failure is observed and context isn’t comparable Unresolved. Preserve both results and decide whether to gather more evidence.

Use a small budget for routine triage rather than attempting to prove a rare failure cannot recur. Three passes do not prove stability. If a known race occurs rarely, a short run has little chance of reproducing it on demand. Decide how much evidence you need from what could ship broken, not from how fast you want the build to turn green.

Change one likely cause at a time

Once you have a repeatable symptom or useful contrast, test the best hypothesis. For a timeout around a fixed sleep, capture which signal was actually awaited and vary system load or scheduling separately from the code. For a fixture that occasionally reuses a record, run the test with isolated data and then with the original suite order. For a test that fails only against a live service, compare a known local fixture with the integration result rather than attributing the failure to the service by default.

Remove clocks and randomness from unit tests where the behavior doesn’t require real time or true randomness. Inject a controllable clock or a recorded seed, then wait for a meaningful event rather than masking scheduling variability by adding more sleeps. In Android tests, account for animation, process startup, and readiness signals separately. For distributed integration tests, make the external inputs and timeout boundaries observable; they may be difficult to reproduce exactly even with unchanged source.

A product race can look indistinguishable from a flaky fixture until you inspect the actual output. If two app operations write in the wrong order intermittently, the test may be doing its job. A useful fix addresses the ordering or contract and adds a deterministic test for it. Making the assertion more permissive solves the wrong problem if either value cannot safely occur in the real product.

Work through an Android checkout failure

Imagine a fictional inventory app. On the first run, a test opens a screen, saves 12 units, and reads back the earlier value of 9. The rerun passes. That is initially an intermittent symptom, not evidence that the old value is harmless. Save the original test report, the checkout, the variant, and the last few ordered events with their run identifiers.

Now run the same scenario on the baseline and candidate using the same test data. Suppose the baseline checks return 12 on all observed attempts, and the candidate returns 9 whenever a controlled fake repository holds the save acknowledgment until after navigation. With that timing controlled, you can reproduce the same wrong value and show that the candidate changed the sequence. The original passing rerun was merely a schedule in which the writer won.

A different outcome calls for a different fix. Suppose both revisions fail when a test fixture ID is reused and both pass when each test gets a fresh row. The evidence points toward fixture contamination rather than the candidate’s feature logic. It still needs an owner and a follow-up; the original failure should remain visible. Report the narrower fact that was demonstrated, not a blanket guarantee that no regression exists anywhere in the pull request.

Set a rerun policy that keeps failures visible

A retry can be useful for collecting evidence or getting work moving after a known infrastructure problem. It should not silently replace the first outcome. If your build retries tests automatically, retain attempts and report which cases needed a retry. The Gradle Test Retry plugin exposes a setting to fail when a test passes only after a retry. Whether to enable that in a particular suite is a team policy decision, but the underlying distinction is worth preserving either way.

For a known, isolated flaky test, give it an owner, a failure signature, a tracking issue, and a deadline to fix or revisit it. If the team explicitly chooses quarantine, keep a separate run or other visible signal and protect the capability with appropriate coverage. Removing a critical test from the gate without a replacement is a release-risk decision, not ordinary cleanup. A known non-critical fixture problem does not automatically establish that future failures of the same test are the same issue.

Measure first-attempt failures and retries that later pass separately. A dashboard that only counts the final verdict can make a flaky suite look healthier as engineers spend more time babysitting it. Record how often people abandon a test or wait for reruns. Those details help decide whether the biggest value is fixing the product race, the fixture, or the build environment.

Leave a short, reproducible triage record

Write a handoff that tells another engineer exactly what ran, what changed, and what decision was made. Include a failure label and an owner rather than just linking to a green job. If a critical failure remains unresolved, say what evidence would make it safe to proceed, and leave release authority with the person or policy responsible for the risk.

The useful output of a rerun isn’t a different color. It’s a better explanation of the first failure and a clear decision about what the team should fix or ship.

You Might Also Like

View all articles
Fix Firebase Variant CI Configuration
3 min read

Fix Firebase Variant CI Configuration

Learn how the Google Services Gradle plugin matches build variants to configuration files, where variant-specific JSON files live, and how to verify that your CI pipeline exercises the intended Firebase project.