Repository navigation
Description
Background
First off, flaky tests (a test that usually passes but sometimes fails) are the worst and you should not write them and fix them immediately.
That said, the larger teams & projects & tests get, the more likely they get introduced. And sometimes it's technically and/or politically hard to get them fixed. (e.g. the person who wrote it originally left the company or works on a new team) You're then left deciding whether to skip/delete the entire test (which might be otherwise super useful), or teach your team to become immune to and start ignoring test failures, which is the worst, when teams start submitting when CI's red, becoming blind to real test failures.
Google doesn't have this problem internally because Google's build system supports detecting & annotating flaky tests: https://bazel.build/reference/be/common-definitions
Tailscale has its own test wrapper that retries tests annotated with flakytest.Mark as flaky. We can't use go test -exec=... unfortunately, as that prevents caching (#27207). So instead we need a separate tool wraps cmd/go (kinda awkwardly, as it turns out).
Go internally also uses these flaky test markers 79 times:
So, clearly flaky tests are a problem. And cmd/go isn't helping.
Proposal
I propose that Go:
- let users annotate known flaky tests (ala
tb.MarkFlaky(urlOrMessage string)) - let
cmd/gosupport re-running marked flaky tests up to N times (default 3 like Bazel?). Maybe add-retrycountor-maxcountaside the existing-countflag? - output machine readable output from
cmd/go(thattest2jsonrecognizes) to say that a test was flaky and failed but eventually passed, that users can plug into their dashboards/analytics, to find tests that are no longer flaky - optional: support re-running even tests not annotated as flaky after they fail, to discover that they're flaky. (perhaps it can still fail the test if not annotated, but it can fail with a different failure type, so the users learn it's flaky and can go fix or annotate)
FAQ
Won't this encourage writing flaky tests? No. Everybody hates flaky tests.
Won't this discourage fixing flaky tests? No. We're already retrying flaking tests. We're just fighting cmd/go to do so.
Why do you have flaky tests? Unit tests for pure functions aren't flaking. The tests usually flaking are big and involve timeouts and the network and subprocesses, even hitting localhost servers started by the tests. Many CI systems are super slow & oversubscribed. Even super generous network timeouts can fail.
Wasn't there already a proposal about this? Yes, in 2018: #27181. The summary was to not write flaky tests. I'm trying again.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsIn Progress
- StatusShow more project fieldsAccepted
Activity
bcmills commentedon Aug 23, 2023
I've investigated an awful lot of test flakes in the Go project over the past few years. Some observations:
Many test flakes are due to hard-coded timeouts (in the test or in the code under test).
Many test flakes manifest as deadlocks or hangs.
Test flakes that are not in one of the above categories generally have a systematic (but undiagnosed) failure mode.
watchflakesto classify errors.The common elements of these points are that flaky tests often need to be retried at a fine granularity and with a progressively increasing timeout, rather than retried a fixed number of times in the same configuration.
To me, that suggests an API addition to the
testingpackage rather than a solution incmd/go.bitfield commentedon Aug 24, 2023
I'm sure we all agree on that, Brad, but it doesn't follow that we should add special functionality to Go to make it easier for developers to live with flaky tests.
I'm not sure why you expect a different answer this time. Frankly, if having flaky tests annoys you, or is inconvenient, I'd say that's a good thing.
Agreed. The solution is to delete them instead, not to mask the flakiness with automatic retries.
painhardcore commentedon Aug 29, 2023
I wholeheartedly support this proposal. Addressing flaky tests is a real-world necessity and providing a structured way to manage them in the standard library is a step in the right direction.
This not only facilitates better tracking and management of these tests but also synergizes well with other tools like linters, by enforcing the addition of comments with Issue numbers or JIRA tickets, thus ensuring that the issues are properly documented and tracked.
Moreover, this proposal strikes a good balance by acknowledging the existence of flaky tests without encouraging their creation or ignoring their need for eventual resolution. It's a pragmatic approach to a problem that, despite our best efforts, persists in many large-scale projects.
vearutop commentedon Aug 29, 2023
I agree, I'd rather have a conservative opt-in way to retry test failures, so that flakyness "policy" is defined per test and is in full control of a developer.
rsc commentedon Sep 7, 2023
This proposal has been added to the active column of the proposals project
and will now be reviewed at the weekly proposal review meetings.
— rsc for the proposal review group
dnephin commentedon Sep 10, 2023
This is a really important point that I think is worth elaborating. The impact of flaky tests on the contributors to a software project is often directly correlated to the constraints imposed by the organization responsible for the project.
Many software projects won't suffer from flaky tests. Maybe because the code has minimal concurrency, the scope of the problem is small, or because the code isn't critical enough to require comprehensive end-to-end testing of all the components. Other projects with significant concurrency, large scope, and large end-to-end tests may encounter the occasional flaky test, but also don't suffer from flaky tests because the team has sufficient time and resources to deal with them. The Go project has some flaky tests, but appears to have significant infrastructure in place to identify, and triage the flaky tests, and also to mitigate the impact of those flakes on other contributors. Not every project is so fortunate. If your experience is working only on projects that are in these two categories it can be easy to dismiss the problem of flaky tests as not significant. Maybe the problem of flaky tests is not significant to the majority of projects, but it can be very real for some.
A few years ago I joined a team that was working on a well known open source project. The project has thousands of tests, many of them could flake. The team had attempted to deal with the flaky tests for years, but could never get them into a reasonable state. The project had been around for 6 years already, had hundreds of contributors who no longer worked on it (many from the open source community), and most of the flaky tests were written by someone who was no longer involved with the project. The cost of fixing a flaky test was high enough that by the time one or two were fixed new ones had appeared. Contributors were forced to either click "rerun job" in CI multiple times (and wait hours to get a green run), or assume the test was flaky and merge with a failing CI check.
Multiple attempts were made to manually identify flaky tests by creating github issues to track them. This helped a bit, but by itself didn't really address the problem. Creating github issues for every CI run was still taking time from every contributor, and it was often easier to click re-run and not create a github issue. Github issues on their own did not help prioritize the most flaky of tests. This manual approach was not enough.
This experience is what motivated me to write the
--rerun-failsfeature ingotestsum. It doesn't use test markers, but otherwise seems to implement the proposal described in the original post. Roughly:--rerun-fails-report=filenamewill output the list of tests that were re-run. This can get posted to the Github PR as a comment, so that the author of the PR is still aware of any potentially new flaky tests in their CI run.This feature allowed the team to make real progress against fixing flaky tests. Instead of manually ticketing and re-running failures we could use the
test2jsonoutput to find the most common flakes, and focus our efforts on those tests.I've seen some interest in this feature from the community. This sourcegraph search shows at least a few recognizable projects using it. I imagine there are others that are not indexed by source graph, not open source, or are using the flag in a script that doesn't match the search query.
dnephin commentedon Sep 10, 2023
Given my experience with flaky tests above, I have a few questions about the proposal.
Why only re-run marked tests? My rational for re-running flaky tests has generally been that an existing flaky test should not introduce friction for other contributors. If a contributor has to create a github issue and edit a test they are not familiar with, that is non-zero friction and they may be tempted to just re-run the CI job instead. I would generally prefer to have an automated system notice the flakes by reading the
test2jsonoutput and seeing that a test both failed and passed in the same run. That same system should be able to sort the flakes to find the most common ones.Some indication of re-run tests is important, but given the nature of a flaky test, it seems unlikely that the person adding the mark is going to be the same person that introduce the flake.
Is the marking of a test more for the developer reading the test code, so that they understand it's a flaky test?
Do we need new output to show "that a test was flaky and failed but eventually passed" ? If a test appears multiple times in the
test2jsonwith both fail and pass doesn't that indicate a flake?bcmills commentedon Sep 11, 2023
I think @vearutop is on the right track with
RunRetry, but I think it's also important to be able to distinguish an outrightFail(meaning “this test had an unexpected failure mode”) from a “flake” (meaning “this test failed to produce a useful signal”).I suggest the following additions to
testing.T. TheRetrymethod is analogous toFail, and theRestartmethods are analogous to theSkipmethods.The same methods could also be added to
testing.Bandtesting.Fif desired, but note that this would not allow for flakyExamplefunctions.The idea is that when a test flakes, it calls
RestartorRestartfwith a suitable message; the re-run can then use theRetriesmethod to compute whatever new timeouts it needs. If for some reason a test wants to limit the number of retries it attempts, it could also use theRetriescounter to trigger a call toFatalfor similar.bcmills commentedon Sep 11, 2023
@dnephin
The marking of a test is so that the flake-retry mechanism doesn't mask actual regressions — such as data races or logical races — that may manifest as low-but-nonzero-probability failures in tests that were previously not flaky at all.
willfaught commentedon Sep 11, 2023
Why return int64 instead of int?
29 remaining items
bcmills commentedon Nov 10, 2023
Hmm. I don't think
Retryshould abort the test like howFailNowdoes — that makes it unsafe to use in a child goroutine (at least in most cases). It should instead work likeFail(just mark the test), and if a test helper wants to skip the rest of the test they can pair it with aSkipNow.(An exception for “already cleaning up and exiting” seems too fragile and too ambiguous to me — what would that mean if
Retrywas called from adeferin an ordinary test function, and would that be different from being called in at.Cleanupcallback?)I think that would be something like:
bcmills commentedon Nov 10, 2023
We should also specify the behavior for subtests. Probably we retry the individual subtest function, rather than retrying the entire chain of parents.
But then what happens if a subtest fails and its parent test calls
Retryafterward? If we're running in-jsonmode and streaming output, we may have already written theFAILstatus for the subtest at that point. 🤔rsc commentedon Dec 5, 2023
I think both @bcmills's comments are correct and should be reflected in the final implementation, whenever that happens. In particular if someone is foolish enough to call t.Retry in a parent after a subtest has failed, seeing an overall PASS seems OK.
testing: add T.Retry and T.Retries for flaky test retries
gopherbot commentedon Jul 5, 2026
Change https://go.dev/cl/797000 mentions this issue:
testing: add T.Retry and T.Retries for flaky test handlingtesting: add T.Retry and T.Retries for flaky test handling
neild commentedon Jul 7, 2026
This is an accepted proposal, but I don't think this is the right API and I'd really rather we not implement it.
To recapitulate @rsc's comment (#62244 (comment)):
The main argument in favor of retry, as I follow it, is that it lets the test author be precise about what flakes should be retried. If a test is flaky, the test author can insert a
t.Retryat the point the flaky failure occurs. If the test fails for some other reason, that unexpected failure won't be retried.I am not convinced by this argument. If a test is flaky, and the owner of the test wants to work around the flakiness by running the test multiple times, then I think the owner is vanishingly unlikely to find the exact location the flaky failure occurs and put in a
t.Retry. They're just going to mark the whole test flaky. You can use a retry to do that (#62244 (comment)), but it's clunky:I am also not convinced that there's any value in distinguishing "expected flaky failure" from "unexpected flaky failure". If a marked-flaky test encounters an new failure mode, then either that mode is a new flake (in which case the best we can expect is that the test owner will mark this new mode as an expected failure) or it's a non-flaky real failure (in which case the test will fail when we retry it).
If retrying flaky tests is reasonable (which I think it is), then I think we should have a simple, focused API which does exactly that. As it stands, this proposal is more of a building block which can be used to build a retry-my-flaky-test API.
I'd prefer something simple and to the point, along the lines of:
This does leave the question of how many times we should rerun a flaky test. I can think of a few possibilities:
-retrycount=N. Downside is that this is a global policy, not a per-test one.t.SetRetries(5). More API surface, but simple.A global -retrycount=N with a per-test override of
t.SetRetries(maxTestRuns)would be fairly simple and configurable.t.Flakywould not aid in the use case described in #62244 (comment), such as a test which runs many times with ever-increasing timeouts so as to pass quickly on fast developer machines and reliably on slow CI ones. I think that's fine: A retry loop can be written directly in the test in a straightforward fashion. It doesn't need support from the testing package. (And it is usually best written without any retry loop using a synthetic clock, such as the one provided bytesting/synctest.)