Thirty-five pull requests against flaky tests

The most useful thing I did about a flaky test was close the pull request meant to fix it. #169847 changed three lines in one file and reported five hundred runs of the suspect suite with no failures. I wrote in the description that I was closing the pull request and the tracking issue with it, and would reopen if the failure came back. It did not come back.

Between July 2023 and February 2024 I opened thirty-five pull requests in the public elastic/kibana repository against flaky tests. Twenty-four merged. Eleven did not, and nine of those eleven were never meant to. The individual fixes are small, so what I want to describe is the method, which has transferred to every suite I have worked on since.

Some context on the codebase, because the details matter later. Kibana is Elastic's user interface over Elasticsearch. Part of it is a security product where analysts hunt through logs for signs of an attack, and my team owned rule management inside that product. A detection rule is a saved query plus a schedule: Kibana runs it against the customer's security data every few minutes and writes an alert whenever it matches. Elastic's threat research team ships hundreds of rules of its own, versioned and delivered as an integration package that Kibana downloads through a subsystem called Fleet. Those prebuilt rules were what most of my tests exercised.

Two kinds of test were involved. A Cypress test drives a real browser against a running Kibana and clicks through the interface. An integration test under Kibana's Functional Test Runner boots a real Kibana and a real Elasticsearch, then talks to HTTP endpoints with no browser in the loop. Both are slow, and both write to real Elasticsearch indices, which is where almost all of the flakiness came from.

"Flaky" tells you nothing about the cause

Elastic's CI opens an issue automatically whenever a test fails on a main or release branch without an obvious cause, titles it "Failing test: ...", and routes it to the owning team. If you read that issue as "make this test stop failing", you will write a retry, or a wait, or a longer timeout, and the queue will not get shorter.

Elastic also ran a job on Buildkite, the CI service Kibana builds on, called the flaky test suite runner. You point it at one test suite and it runs that suite up to several hundred times in parallel. That turns a guess into a rate. Before touching any test, I ran it.

The first possible outcome is that the test really is flaky, and you now have a reproduction loop instead of a story. The second is more common than I expected, and it is why the runner earns its CI minutes.

On #163241 I ran the suspect integration test three hundred times and all three hundred passed. So I went back to the builds where it had actually failed, and both of them turned out to be backport pull requests against an older release branch. The cause was a race between writing detection rules into Elasticsearch and those rules becoming visible to a search. Elasticsearch is near-real-time. A document you have just indexed is not searchable until the index refreshes, and on a loaded CI machine that gap is wide enough to lose a test in.

I could have added a refresh call to the failing test. Instead I moved the refresh inside the four utility functions that do the writing, installPrebuiltRules, upgradePrebuiltRules, the legacy install helper, and the one that installs the Fleet package, so that no test written afterwards could forget it. The shape of the change, simplified, with es being the Elasticsearch client:

// Before: each test refreshed the indices itself, and some tests forgot.
await installPrebuiltRules(supertest);
await refreshSavedObjectIndices(es);
await expectRulesToBeInstalled();

// After: the helper refreshes before it returns, so no caller can forget.
export async function installPrebuiltRules(supertest: SuperTest, es: Client) {
  const response = await supertest.post(INSTALL_PREBUILT_RULES_URL).send();
  await refreshSavedObjectIndices(es);
  return response;
}

The third outcome is that nothing is wrong at all. #169791 ran five hundred times with no reproduction, and the original failure log showed a socket timeout, which is an infrastructure hiccup rather than a property of the test. The test had been skipped in the meantime, so the whole change was to unskip it. And #169847, the one I opened this post with, went a step further and closed the issue too.

Deciding to change no code is a real outcome, but only if you write down what you measured. Five hundred green runs and a link to the Buildkite build is evidence. "Could not reproduce" is not.

Three of these pull requests have no diff at all

The flaky test suite runner needs a branch to point at, and the practical way to get CI to pick up a branch was to open a pull request. So #161864, #162266 and #163086 have zero-line diffs. They exist so a job had somewhere to run. Others carry a one-line change and a single comment linking a runner build, and one says so in its own body, that it exists to run the flaky test runner and paste the results into the real pull request.

I mention this because the raw count looks bad. Twenty-four merged out of thirty-five reads as churn on a dashboard, when nine of the eleven that did not merge were disposable CI triggers or written records. If your organisation measures engineers by merged pull requests, nobody will use the tooling this way, and this is the way it should be used.

What was actually breaking

When the tests really were flaky, the causes clustered. The list below was close to exhaustive for my area, and I would bet money on at least three of these existing in any mature browser test suite.

The table refreshed under the click. The rules table polls every sixty seconds. A Cypress helper that selects rules one checkbox at a time loses the element when the table re-sorts beneath it, and the click lands on nothing. This was the most common single cause I found, and it is nearly invisible: on #163698 it took roughly four hundred iterations to reproduce one instance. The fix is to disable auto-refresh in the test setup, not to retry the click.

A banner rendered late and shifted the layout. The same selection helper failed for an unrelated reason in a test that signs in without action privileges. A "missing privileges" callout renders a beat after the page, pushes the table down mid-selection, and the checkbox moves out from under the cursor. I added a waitForCallOutToBeShown helper, and gathered the callout element IDs that had been scattered across several files into one module.

Test state leaked between cases. In that same file, the first test signed in as the unprivileged user, and the sign-in for the rest of the suite sat in a before hook rather than beforeEach. Every subsequent test therefore ran as the unprivileged user and died in setup with 401s. One word.

An assertion depended on another team's response shape. #163468 traced a failure to Fleet returning installSource: undefined where the specification said installSource: 'registry'. I deleted the assertion. The reasoning I wrote at the time is the one I still hold: a test should not fail on a field it neither owns nor controls, and retrying around another team's API just hides the same coupling behind a delay.

Cleanup looked finished before it was. Elasticsearch's _delete_by_query does not accept refresh=wait_for, so a between-test cleanup returned while the documents were still searchable, and the next test started against data it thought was gone. Those specific URLs needed ?refresh=true.

When the fixes stopped being per-test

After roughly twenty individual fixes, the pattern was obvious enough that patching one more test felt like losing ground. The work moved to the shared test infrastructure.

#173998 made retryDelay a configurable parameter on Kibana's shared RetryService, so our tests could poll at 200ms instead of the default. It added a retry wrapper that enforces a maximum number of attempts. And it added refreshSavedObjectIndices, one helper that clears the caches and refreshes the indices holding Kibana's own stored documents, replacing a comment about the problem that had been copy-pasted around the codebase. The pull request carries five hundred runs before and five hundred after, on both the stateful and serverless configurations. #174185 followed with retryIfConflict, which retries an Elasticsearch operation that comes back 409 because something else was writing the same document.

The highest-value change in the whole campaign was neither of those. It was #176316, forty-three added lines across seven files, which made the retry helper stop swallowing the error it was retrying. Until then every retried failure produced the same message:

ERROR Reached maximum number of retries for test: 2/2

That is all you got. Whatever the operation had actually returned was caught and counted, then discarded, so every failure in every suite looked identical and told you nothing. After the change the log reads:

ERROR Retrying installPrebuiltRulesPackageByVersion: Error: expected 500 "Internal Server Error", got 200 "OK"
ERROR Reached maximum number of retries for test: 2/2

Months of investigation had been slower than they needed to be because a helper was hiding its own evidence. Go and look at what your own retry and wait utilities do with the error before they try again. Ours discarded it, and the message it printed instead was readable enough that I had spent months not questioning it.

The test that was really a design problem

#164825 was a unit test, not a browser test, and it failed by timeout. It mounted the entire Rule Details page component in order to assert two things, whether a legacy URL redirects correctly and which tabs are visible.

Raising the timeout would have worked, for a while. Instead I pulled useLegacyUrlRedirect and useRuleDetailsTabs out as hooks, extracted the LegacyUrlConflictCallOut component, tested those three directly, and deleted the original test file. The diff is +597 / -600 across nineteen files, so the net line count barely moved, which is about right for a change whose point was that the logic sat in the wrong place.

If the only way to assert something is to mount the whole page, the logic you want to assert is not reachable on its own.

What I would keep

Three habits survived this and I still use them. Run the suite a few hundred times before you form an opinion, and put the run count and the build link in the pull request so the next person does not repeat your work. Fix the helper rather than the test whenever the same failure could plausibly bite a test that has not been written yet. And treat "no change needed" as a deliverable that needs evidence, not as a non-answer.

This work ended in early 2024 and Kibana moves quickly, so the file paths and some of the helpers have probably changed since. The pull requests are all public, so where I have described something you can go and read the diff rather than take my word for it.