Tracing flaky tests back to environment drift

A regression test fails on Tuesday, passes on the rerun, and joins the list of tests the team calls flaky. Where QA servers have stayed up for months, a test on that list can be deterministic. It fails every time on one server and passes every time on another, because the two servers stopped matching and the rerun ran on the other one. Grouping failures by environment before grouping them by commit sorts the list into fixes for the test's author and fixes for whoever maintains the server.

qa01Ten runs at one commit, ten passesqa02Ten runs at one commit, ten failures
A result that follows the stack goes to whoever maintains the environment

Group failures by stack before grouping by commit

In May 2016, Google's testing blog reported a continual rate of about 1.5 percent of all test runs across the company's corpus returning a flaky result, and said that about 84 percent of the transitions it observed from pass to fail involved a flaky test. The post defines a flaky result as a test that shows both a passing and a failing result with the same code. A test on a drifted server meets that definition whenever two runs of one commit land on different stacks, so a flaky list can hold two kinds of failure that need different fixes.

Rerun counts usually tell them apart. When the fault sits in the test code, one commit on one stack gives mixed results. Under drift, a stack gives the same result on every run, and a second stack gives the opposite result on every run. Hold the commit fixed and run the failing test ten times on each QA stack. Ten is our starting count, and you can raise it. A 2014 University of Illinois study of flaky tests, covered in the last section, warns that when a test rarely changes its outcome, rerunning it a few times may miss the flakiness.

Result at one commitReadingGoes to
Some runs pass and some fail, on every stackTest code: a wait, a race or test orderThe test's author
Every run fails on one stack and every run passes on anotherThe stacks differWhoever maintains the environment
Mixed results on one stack and clean results on anotherTest code with a timing fault that one stack exposes, such as a race on a slower or busier serverThe test's author, with both stacks' settings attached
Passes on a rebuilt stack, then fails on the next runState left by the earlier runThe owner of the reset procedure
Fails only around midnight UTCA clock read inside the testThe test's author, with each stack's time zone on record

The Illinois study gives the midnight case as an example of a test that depends on the system time. Drift is the second row, and the rest of this guide covers it. For the fourth row, see Resetting a QA environment between test runs.

Package versions, clock and locale, database settings and dataset

Take a hypothetical company, Hartsell Dispatch, with two QA stacks. qa01 was built in March and has run every regression cycle since. In August the team added qa02 so a second release could test alongside the first. Both followed one runbook. By October the two can differ in four places, and standard commands read three of them back.

# Installed packages and versions, one file per stack
dpkg-query -W | sort > qa01.packages    # Debian and Ubuntu
rpm -qa | sort > qa01.packages          # RHEL family

# With both files on one machine
diff qa01.packages qa02.packages

timedatectl       # clock settings, and whether network time sync is active
localectl status  # the system locale
locale            # locale settings of the current session
-- PostgreSQL, from psql 15 or later: parameters set to values other than the default
\dconfig

-- SQL Server: version, cumulative update and server default collation
SELECT SERVERPROPERTY('ProductVersion'), SERVERPROPERTY('ProductUpdateLevel'), SERVERPROPERTY('Collation');
-- Collation of each database, and the running configuration
SELECT name, collation_name FROM sys.databases;
SELECT name, value_in_use FROM sys.configurations ORDER BY name;

The dpkg-query manual page says the default output of -W gives one line per package with its name and installed version, and the rpm manual page describes -a as a query of all installed packages. Run with no command, timedatectl shows the settings of the system clock, including whether network time synchronization is active, and localectl status shows the system locale. The locale manual page says that with no arguments it prints the current setting for each locale category, based on the environment variables of the session that runs it, so the command block above runs both. According to the psql 15 reference, \dconfig without a pattern lists only parameters set to values other than the default, and the PostgreSQL 14 reference has no such command. On SQL Server, Microsoft's documentation says ProductUpdateLevel reports the cumulative update and Collation returns the server's default collation. Inside each database, collation_name in sys.databases is the default collation, and the value_in_use column of sys.configurations holds the running value of each option.

The fourth place is the dataset, and its check depends on the schema. Count the rows in the tables the suite reads and note the newest migration applied.

Each difference has an ordinary cause. A patch goes onto one server during an incident. Someone raises a timeout on qa01 to get a release through, and the change never reaches qa02. A build definition can fix what a stack starts from while people keep changing the running stack, so two stacks built from one definition can still end up different.

Hartsell adds a pipeline step that saves the output of those commands beside the test report on every run. Each failure then arrives with the state of its stack attached, and two reports can be compared without logging in to either server.

Sort order before and after glibc 2.28

Hartsell's suite has a test that opens the list of open loads and compares it with an expected order recorded on qa01. Two of the load numbers are 1-1 and 11. Hartsell stores the data in PostgreSQL, and the application sorts the list in its query.

The PostgreSQL wiki page on locale data changes says PostgreSQL sorts text with locale data from the system C library. It records that glibc 2.28, released on August 1, 2018, included a major update to that locale data. According to the same page, Debian 10, Ubuntu 18.10 and RHEL 8 use the new data, while Debian 9 and Ubuntu 18.04 and earlier use the old data. The page gives a one line test:

( echo "1-1"; echo "11" ) | LC_COLLATE=en_US.UTF-8 sort

According to the wiki, these two strings sort differently on different locale versions, and other differences may remain when they sort the same. Run the line on both stacks and compare the output.

Suppose Hartsell's runbook names the distribution and leaves the release open. qa01 went onto Ubuntu 18.04 to match an older server a customer still runs, and qa02 went onto a current release. The glibc 2.28 change falls between them, so the test passes on every run on qa01 and fails on every run on qa02. Because the nightly job alternates between the stacks, the report shows a pass one night and a failure the next, and the test gets tagged flaky.

Both servers sort the way their locale data says to. Decide which stack matches production and write that into the runbook as a distribution release and a collation. All of this concerns the libc provider, which the PostgreSQL collation documentation says uses the locales of the system C library. The same page describes an icu provider that uses the external ICU library, and the wiki says table columns using ICU collations are unaffected, so check which provider the database uses first. A query in the next section shows it.

Collation versions and restored copies

PostgreSQL 15 added catalog columns that help here. Its pg_database page lists datlocprovider, which in version 15 holds c for libc and i for ICU, and datcollversion, and neither appears on the version 14 page. According to the current documentation, this version is recorded when the database is created and checked when it is used, to detect changes in the collation definition. It also says the function pg_database_collation_actual_version, which the version 15 function reference lists and the version 14 reference lacks, returns the version the system currently provides, and that when the two differ, objects depending on the collation might need to be rebuilt.

-- PostgreSQL 15 or later: provider, LC_COLLATE, recorded and current collation versions
SELECT datname, datlocprovider, datcollate, datcollversion,
       pg_database_collation_actual_version(oid)
FROM pg_database
WHERE datname = current_database();

We recommend running the query on every QA stack and keeping its output with the package list. The ALTER COLLATION reference says that for libc collations the version is recorded on systems using the GNU C library, FreeBSD and Windows, so on other systems the columns can be empty. It also says that with the GNU C library, the library's version stands in for the collation version, and that distribution maintainers are free to carry newer collation definitions back to older library releases. The wiki goes further and says PostgreSQL has no way to detect an incompatible glibc update. For a libc database, matching versions on two stacks therefore show the same C library version, and the sort test above remains the direct check of the order itself.

A refreshed QA database can carry the problem in with it. The wiki lists restoring a binary backup, such as one from pg_basebackup, onto a system with different locale data among the affected cases. An index built under the old data can then disagree with the order an index scan expects, and the wiki says a query could fail to find data that is actually there, or an update could insert duplicate data that should be disallowed. It lists backups and upgrades through pg_dump as unaffected, because the data moves in a logical form.

After a locale change, the wiki's advice is to reindex every index on text, varchar, char and citext columns before the instance goes back into use. The ALTER DATABASE reference describes REFRESH COLLATION VERSION as updating the database collation version, so we recommend running it after the reindex, once the indexes match the new data.

A build definition under change control

Rebuilding each stack before a regression cycle limits drift to the changes made during that cycle (our recommendation). The definition a stack is built from, whether a configuration management playbook or a base image, should name the distribution release, package versions, database settings, application build and base dataset. When a stack needs a longer timeout or a newer database patch, make the change in the definition through review, and every stack built from it afterward carries the change. A setting changed by hand on one running stack lasts until that stack is rebuilt. Test environment provisioning from approved configurations covers building a stack in layers with a check after each one.

When two releases test in the same week on separate stacks, a difference between the stacks can read as a difference between the releases. Parallel QA environments for two releases in the same week covers running them side by side.

Some environments stay up for months. Those need the commands from the second section run on a schedule, with a person reading the diff (our recommendation). A dry run of the configuration tool is another way to look for drift, with a gap to know about. Ansible's documentation on check mode says modules that support it report the changes they would have made, while modules without support report nothing and do nothing, so a clean dry run can leave a change unreported.

Test code faults a rebuild leaves in place

A clean environment fixes the second row of the table and leaves the first. In the 2014 study, researchers at the University of Illinois analyzed 201 commits that likely fixed flaky tests in 51 open source projects from the Apache Software Foundation. They classified the root cause for 161 of them. In 74, the test made an asynchronous call and did not properly wait for the result, 32 involved concurrency, and 19 depended on the order the tests ran in. The study found that 154 of the 161 had outcomes that did not depend on the platform, which the authors define as the underlying system the test runs on, including the hardware, OS and JVM or JRE. Tests like those 154 stay flaky on a stack built an hour ago. Of the other seven, which did depend on the platform, four needed a particular OS to show the failure.

The authors caution that Apache has few mobile applications or GUI tests, so some findings, such as platform independence, may not carry over to those. Server packages and locale data fit the paper's definition of the platform. A regression suite that drives a deployed application and its database touches them at every step, so your own suite may show a larger share of platform failures than the study found. Use the rerun table to measure that share.

Some teams have less drift to look for. When the whole suite, database included, runs in containers started from images pulled by digest, the packages and locale data come from the image. Docker's documentation says pulling by digest pins the image to that version, so the image in use is always the same. On a team like that, most of the flaky list is probably test code, and the hours belong on waits and test order. Configuration passed in at run time and the data loaded into the database can still differ between runs, so keep saving the settings and row counts beside each report (our recommendation).

Talk to a consultant