TExcelTAD
Home › Monorepo Builds: Bazel (+ Buck2 & Pants) › Test Sharding & Flaky Tests

Test Sharding & Flaky Tests

A test suite that takes ten minutes as one process can take two minutes as five processes. Sharding splits one test target into N parallel test actions, each running a subset of the test cases. Bazel runs the shards in parallel locally or, with remote execution, on N different machines.

How sharding works

  1. You set shard_count = N on the test (or --test_sharding_strategy=forced=N on the command line).
  2. Bazel runs the test binary N times, with TEST_TOTAL_SHARDS=N and TEST_SHARD_INDEX=0…N-1.
  3. The test framework must pick its share of the cases (usually case_number % N == index) and touch the file named by TEST_SHARD_STATUS_FILE to say "I understood the sharding protocol".
  4. The target passes if every shard passes.

GoogleTest, JUnit (through Bazel's test runner), go test (through rules_go) and pytest with a sharding plugin implement the protocol. A plain test program doesn't, and Bazel refuses to pretend:

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_python", version = "2.4.5")' > MODULE.bazel
mkdir -p suite
cat > suite/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_test")
py_test(name = "naive_test", size = "small", srcs = ["naive_test.py"], shard_count = 3)
EOF
printf 'print("running all 10 cases")\n' > suite/naive_test.py
bazel test //suite:naive_test 2>&1 | grep -o 'Sharding requested, but the test runner did not advertise support for it' | sort -u
bazel test //suite:naive_test 2>&1 | grep -E 'NO STATUS|FAILED|Executed'
Sharding requested, but the test runner did not advertise support for it
//suite:naive_test                                                    NO STATUS
Executed 0 out of 1 test: 1 was skipped.

Without the status file, Bazel can't tell whether the three shards each ran a third of the cases or all of them, so it fails the target. (--noincompatible_check_sharding_support turns the check off, which you should only do while migrating.)

A test that supports sharding

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_python", version = "2.4.5")' > MODULE.bazel
mkdir -p suite
cat > suite/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_test")
py_test(name = "cases_test", size = "small", srcs = ["cases_test.py"], shard_count = 3)
EOF
cat > suite/cases_test.py <<'EOF'
import os, pathlib, sys

status = os.environ.get("TEST_SHARD_STATUS_FILE")
if status:
    pathlib.Path(status).touch()          # "I support sharding"
index = int(os.environ.get("TEST_SHARD_INDEX", "0"))
total = int(os.environ.get("TEST_TOTAL_SHARDS", "1"))

cases = {f"case_{n}": (lambda n=n: n * n >= 0) for n in range(10)}
mine = [name for i, name in enumerate(sorted(cases)) if i % total == index]
failed = [name for name in mine if not cases[name]()]
print(f"shard {index + 1}/{total}: {len(mine)} cases, {len(failed)} failed")
sys.exit(1 if failed else 0)
EOF
bazel test //suite:cases_test 2>&1 | grep -E 'PASSED|Stats|Executed'
for i in 1 2 3; do tail -n 1 bazel-testlogs/suite/cases_test/shard_${i}_of_3/test.log; done
echo "== sharding disabled"
bazel test //suite:cases_test --test_sharding_strategy=disabled --test_output=all 2>&1 | grep -E '^shard'
//suite:cases_test                                                       PASSED in 0.2s
  Stats over 3 runs: max = 0.2s, min = 0.2s, avg = 0.2s, dev = 0.0s
Executed 1 out of 1 test: 1 test passes.
shard 1/3: 4 cases, 0 failed
shard 2/3: 3 cases, 0 failed
shard 3/3: 3 cases, 0 failed
== sharding disabled
shard 1/1: 10 cases, 0 failed

Each shard has its own log directory (shard_1_of_3/…), and the summary line reports statistics over the shard runs. With --test_sharding_strategy=disabled the test runs once, as a single shard, and covers everything.

Choosing shard_count: aim for shards of a minute or two. Too many shards waste time on start-up (each shard starts the binary and loads its fixtures) and multiply the load on shared resources.

Flaky tests

A flaky test fails sometimes for reasons unrelated to the change being tested: timing, ordering, shared state, the network. Bazel gives you tools to find flakiness and to contain it:

Tool Effect
--runs_per_test=20 run each test 20 times; any failure shows the test is not deterministic
flaky = True on the test Bazel retries a failing test up to 3 times and reports FLAKY if a retry passes
--flaky_test_attempts=3 (or =regex@N) the same retry behaviour from the command line, for chosen tests
--runs_per_test_detects_flakes with --runs_per_test, report FLAKY instead of FAILED when some runs pass

This test fails on its first attempt and passes afterwards (it keeps a counter in a file outside its sandbox, exactly the kind of shared state that causes real flakiness):

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_python", version = "2.4.5")' > MODULE.bazel
mkdir -p suite
cat > suite/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_test")
py_test(name = "wobbly_test", size = "small", srcs = ["wobbly_test.py"])
EOF
cat > suite/wobbly_test.py <<'EOF'
import pathlib, sys
counter = pathlib.Path("/tmp/wobbly-attempts")
attempt = int(counter.read_text()) + 1 if counter.exists() else 1
counter.write_text(str(attempt))
print("attempt", attempt)
sys.exit(1 if attempt == 1 else 0)
EOF
bazel test //suite:wobbly_test 2>&1 | grep -E 'PASSED|FAILED|FLAKY'
rm /tmp/wobbly-attempts
bazel test //suite:wobbly_test --flaky_test_attempts=3 2>&1 | grep -E 'PASSED|FAILED|FLAKY'
INFO: Build completed, 1 test FAILED, 13 total actions
//suite:wobbly_test                                                      FAILED in 0.2s
FLAKY: //suite:wobbly_test (Summary)
//suite:wobbly_test                                                       FLAKY, failed in 1 out of 2 in 0.2s

FLAKY is a pass for the build, but it is recorded as such in the test logs and the Build Event Protocol, so CI dashboards (BuildBuddy, EngFlow, your own) can track flaky tests over time. Treat flaky = True as a temporary quarantine with an owner and a ticket, not a fix: retries hide real bugs and triple the cost of a failing test.

Test yourself

What must a test do so that Bazel accepts it with shard_count = 3?

  1. Nothing
  2. Run its share of cases based on TEST_SHARD_INDEX/TEST_TOTAL_SHARDS and touch TEST_SHARD_STATUS_FILE
  3. Print 'SHARDED'
  4. Use the size enormous

Which flag helps you discover whether a test is flaky?

  1. --test_output=errors
  2. --runs_per_test=20
  3. --nocache_test_results only
  4. --keep_going

What does flaky = True do?

  1. Skips the test
  2. Retries a failing test up to 3 times and reports FLAKY if a retry passes
  3. Runs the test without a sandbox
  4. Disables caching