Section 10.38

Nondeterministic test

Definition

A nondeterministic test is a test whose verdict, pass or fail, can differ between runs of the same test on the same code, because something the test does not control differs between the runs: the scheduling of threads, timing, random inputs, or the environment, such as machine load or leftover files. Such a test is also called a flaky test. Varying output is not the problem in itself, since a system may be allowed several correct outputs. The problem is a verdict that changes while the code does not.

The idea

Two producer threads put items into a queue: one puts A, the other B. A test asserts that the consumer receives A and then B. Usually it does. Now and then it receives B first, and the test fails. The specification allows either order, so the system is right and the test is wrong. A second, rarer failure looks the same on a test dashboard: the consumer receives only A, and B has vanished. That is a real defect. Both show up as “failed once, passed on retry”.

A verdict depends on four things: the code, the inputs, the environment and the schedule. If the verdict changes while the code stays the same, one of the other three changed. Two questions then sort every case. First, does the specification allow the outcome that was observed? Second, does the test oracle §10.5, the check that decides pass or fail, accept exactly the outcomes the specification allows? Variation within the allowed outcomes is expected behavior, and an oracle that rejects some of them is a flaky oracle. An outcome outside the allowed set is a real failure, however rarely it occurs.

How it works

Every intermittent failure falls into one of four classes.

  1. Allowed variation, exact oracle. The output varies within the allowed set, and the oracle accepts every allowed output. The outputs differ between runs but the verdict is stable. Nothing needs fixing.

  2. Allowed variation, flaky oracle. The oracle rejects an output the specification allows, such as a second valid order, or a floating-point result that differs from the expected value only by a rounding error the specification permits. The test has the defect.

  3. Real intermittent defect. In some runs the output lies outside the allowed set, such as a lost item or an item delivered twice. The code has the defect, and its low rate makes it harder to catch, not less serious.

  4. Broken test assumption. The environment did not provide what the test assumes: the machine was overloaded, a network port was already in use, or a file from an earlier test remained. The setup has the defect, or the assumption must be stated and enforced.

Studies of flaky tests in large software projects keep finding the same causes: waiting a fixed time for an asynchronous operation instead of waiting for its completion; concurrency §9.1, such as a race condition §9.2 between threads; dependence on the order in which tests run, through shared state; dates, times and time zones; randomness without a recorded seed; resources that one test leaks to the next; and assumptions about the speed of the machine.

To diagnose and repair a nondeterministic test:

  1. Write down the allowed outcome set from the specification. For independent concurrent operations it is usually “any order, each result correct, each item exactly once”.

  2. Make each failure reproducible at the moment it happens, not after a retry: save the random seed, the available schedule information, timestamps, logs and the state of the machine.

  3. Classify the failure into one of the four classes before changing anything.

  4. Repair according to the class. Widen a flaky oracle to the allowed set. Fix a real defect in the code. Replace a fixed sleep with a wait for the completion event, bounded by a generous timeout §9.34. Isolate shared state. Record seeds.

  5. To search for rare interleavings on purpose, run the test many times under stress, under a tool that varies the thread schedule, or under ThreadSanitizer §10.25, a detector of data races §9.3 that the compiler builds into the program.

Worked example

The exact oracle. For the queue above, the oracle checks that the received items, compared as a multiset §14.13, equal the sent items A and B, and that each item was processed exactly once. A multiset is a collection in which order does not matter but repeats count. The oracle accepts A, B and B, A. It rejects A alone, because B is missing, and A, B, B, because B appears twice.

What retrying hides. Suppose a real defect makes the test fail in each run, independently, with probability p=0.1p = 0.1. The build system runs a failing test at most 3 times in total and reports a pass as soon as one attempt passes. The test is reported as failed only if all 3 attempts fail, which happens with probability 0.13=0.0010.1^3 = 0.001. A failed attempt appears in the log only when the first attempt fails, with probability 0.1, because a first pass ends the loop. So the defect, present in every build, shows up in the log of 1 build in 10 and is reported as a failure in 1 build in 1000.

How many runs a rare failure needs. If a failure occurs independently with probability pp in each run, then nn runs show no failure with probability (1−p)n(1 - p)^n. To see at least one failure with probability 0.95, solve (1−p)n≤0.05(1 - p)^n \le 0.05, which gives n≥ln0.05/ln(1−p)n \ge \ln 0.05 / \ln(1 - p), where ln\ln is the natural logarithm. For p=0.1p = 0.1: ln0.05/ln0.9=(−2.996)/(−0.1054)≈28.4\ln 0.05 / \ln 0.9 = (-2.996) / (-0.1054) \approx 28.4, so 29 runs. For p=0.01p = 0.01: ln0.05/ln0.99=(−2.996)/(−0.01005)≈298.1\ln 0.05 / \ln 0.99 = (-2.996) / (-0.01005) \approx 298.1, so 299 runs. Read the other way, 299 passing runs in a row are needed before one can state, with 95% confidence, that the failure probability is below 1%. That statement again assumes independent runs.

Stated precisely

Fix one test and its inputs. Let 𝒪\mathcal{O} be the set of outcomes the specification allows, and 𝒜\mathcal{A} the set of outcomes the oracle accepts. The oracle is exact when 𝒜=𝒪\mathcal{A} = \mathcal{O}. An outcome in 𝒪\mathcal{O} but not in 𝒜\mathcal{A} produces a false alarm §1.22: a flaky-oracle failure. An outcome in 𝒜\mathcal{A} but not in 𝒪\mathcal{O} is a real failure the test misses. An outcome in neither set is a real failure the test reports. The test is nondeterministic when, for the same code and inputs, some runs produce an outcome in 𝒜\mathcal{A} and others an outcome outside it.

Let qrealq_{\text{real}} be the probability per run of an outcome in neither set, and qoracleq_{\text{oracle}} the probability per run of an outcome in 𝒪\mathcal{O} but not in 𝒜\mathcal{A}, both measured in the environment the test assumes. The probability that a run fails is q=qreal+qoracle.q = q_{\text{real}} + q_{\text{oracle}}. A run in which the environment broke the test’s assumptions belongs to neither term: it gives no evidence about the system’s outcomes at all.

Limits and common mistakes

A retry policy that reports a pass after any passing attempt turns a real intermittent defect into a passing build. Record every failed attempt, and treat a test that failed and then passed as failing until the failure has been classified.

Making a test deterministic can remove the failure it should find. Running threads one at a time, or fixing one schedule, removes the interleaving in which a race condition occurs. A deterministic test of concurrent code checks one schedule out of many.

A stable pass is not evidence of correct concurrency. A test that passes 10,000 times on one machine may never have produced the rare interleaving; another machine, compiler or load produces other schedules.

Raising a timeout until a timing test stops failing can hide a real slowdown. A timing failure is a defect or a broken assumption only relative to a stated load, clock and deadline, so write those down first.

Failures are often not independent across runs: they cluster under load, at certain times or on certain machines. The run counts in the example are then too small.

Quarantining a flaky test, meaning removing it from the tests whose failure blocks a change, stops it from blocking work and also stops it from finding anything. Track every quarantined test until it is repaired.

Random testing is nondeterministic by design, and that is sound when every generated input is saved or can be regenerated from a logged seed, so that every failure can be rerun.

Questions answered

Is variability expected behavior or a flaky oracle?

Variability is expected behavior when every observed outcome is one the specification allows; it reveals a flaky oracle when the test fails on such an allowed outcome; and it reveals a real defect when an outcome lies outside the allowed set. A flaky oracle is a pass-or-fail check that is stricter than the specification, so its verdict changes from run to run although the system behaves correctly. To decide which case applies:

  1. Write down the allowed outcome set, for example “the two results in any order, each correct, each item exactly once”.

  2. Take the outcome of the failed run from its saved logs and seed, not from a rerun.

  3. If the outcome is allowed and the test rejected it, the oracle is flaky: widen it to the allowed set. If the outcome is not allowed, such as a lost or duplicated item, the code has an intermittent defect, however rare. If the run broke the test’s stated assumptions, such as machine load or free resources, fix the setup or state the assumption.

A pass on retry decides none of these questions. It only shows that the failing outcome does not occur in every run.

Related entries: Test oracle (§10.5), Deterministic replay (§10.37), Race condition (§9.2), Independent and identically distributed samples (§11.5), ThreadSanitizer (§10.25), False positive and false negative (§1.22).