STAFFCHAPTER 27

CI at scale: speed, sharding and test selection

When the suite takes 41 minutes, nobody waits for it: split the files by measured time, run only what a change can reach, and keep one full run as the net

55 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-24
PREDICT

You have a suite of 16 test files that takes 11 seconds on one process. Three of the files take about 2 seconds each and the other thirteen take well under a second. You run it as four parallel shards. Which way of dividing the files finishes first?

A pipeline has two costs. One is the machine time, which you can pay for. The other is the wait, which the people pay, and it is the one that shapes behaviour. Software Engineering at Google (chapter 23) says the same of its own pipelines: a bug caught later costs more, partly because it takes more work for the author to recollect and investigate the change, and the cost grows almost exponentially the later it is caught. Its presubmit checks run only fast, reliable tests, and the slower ones move to after the merge. Once a suite is slow, three levers are left: run it on more machines at once, run less of it for a given change, and make the slow parts faster. This chapter takes the first two, and ends with the part people forget: what you give up when you pull them.

Know where the time goes first

Running tests on every change set budgets for each ring of feedback, and the project suite measured -n auto on the lab’s small suite and found it no faster. Both numbers were honest, and both were for a suite that finishes in a few seconds. A suite that takes 41 minutes is a different animal, and the first step is the same one: measure.

pytest --durations=0 lists every setup, call and teardown with its cost. Add -vv and it stops hiding the cheap ones. Three shapes turn up in a real suite, and each wants a different cure.

Shape What it looks like in the list The cure
A few giant files The top five entries are half the total Split the file; shard so the giants sit apart
A long even tail Thousands of entries, none big Parallelism; more shards
Slow fixtures setup lines dwarf call lines Share the fixture (a wider scope), or fake the dependency

Do the cure in the order of the table’s cost. A slow fixture that every test pays for is cheaper to fix than a pipeline to shard, and sharding a suite whose time is all in one file only moves the wait to one shard. Measure, then choose.

Parallel on one machine: what -n does and does not do

pytest -n 4 from pytest-xdist starts four worker processes on your machine. Each imports pytest and your app, then pulls tests from a shared queue. The cost is a fixed start-up for each worker; the gain is that the queue keeps every core busy. The default mode, --dist load, hands out single tests to whichever worker is free, so one slow file does not stall a worker for long. The alternatives group tests: loadfile keeps every test of a file on one worker, and loadscope keeps a module or class together. Grouping suits tests that share an expensive fixture, and it costs balance.

The next section’s lab measures all of this. On a suite of 62 sleeping tests that takes 10.9 s serial, -n 2 takes 6.1 s, -n 4 takes 3.7 s and -n auto (12 CPUs here) 2.8 to 3.6 s. On the lab’s real 23-test suite, the earlier chapters found it no faster. Both are true. The crossover is the point where the serial run is much longer than the workers’ start-up, and a suite of 41 minutes is far past it.

So why shard, if -n works? Three reasons, and they are why large teams do both.

  • One machine has a ceiling. A CI runner typically has a few cores. At 41 minutes, four cores bring you to ten or so. You want twenty cores, and the way to get them is more machines.
  • Isolation. Separate machines share no memory, no ports and no files. A test that passes under -n only because workers use different temporary directories fails in a shared-database or fixed-port setup. Separate runners expose that earlier and cleanly.
  • Control. -n decides the split at run time and you cannot see it. With your own split, you know which tests ran where, so a shard that is slow or red is a single place to look.

Sharding: splitting files by measured time

A shard is a slice of the suite that runs as its own job. Bazel’s test encyclopedia describes the contract most runners follow: the runner is launched once per shard, and it is told how many shards there are (TEST_TOTAL_SHARDS) and which one it is (TEST_SHARD_INDEX, counting from 0), and picks its tests from that. Round-robin is one simple way to pick them. We saw what round-robin costs: it ignores how long each file takes.

The better split is a classic scheduling heuristic. Sort the files from slowest to fastest. Give each to the shard that currently has the least total work. This is the “longest processing time first” rule, and it is cheap and good: the slowest shard ends within a third of the best possible split in the worst case, and nearer to it in a real suite with a long tail. It needs one input, the duration of each file, which --durations=0 already gives you.

Four rules keep it honest.

Every shard must compute the same plan. The CI system starts four jobs, and each one runs your script and picks its slice. If the durations differ between jobs, or ties are broken differently, a file is in two slices or none. The second case is the dangerous one: a test never runs and the build is green. Commit the durations file so every job reads the same bytes, and sort with a tie-break (the file name) so equal times land the same way every time.

A new file has no duration. Give it the median of the known files. The next recording fixes it. A guess too low makes one shard slow for a day; it never makes a test vanish.

The plan goes stale. Files change, and a split from last month is a poor split today. Re-record on a schedule (the nightly run is the place) and commit the result. A stale plan is slow, not wrong, which is why it can sit for a year.

Check the union. The cheapest safety test you can write for a sharder is: the files of all the shards, put together, are exactly the files of the suite. Run it in the pipeline.

The lab has you write the script, scripts/shard.py, and read the matrix that runs it. A matrix is the CI feature for this: one job definition, run once for each value in a list, each on its own runner.

Selection: running only what a change can reach

Sharding runs everything faster. Selection runs less. The idea is old and the obvious version is wrong.

The obvious version is to run the tests of the files that changed. You have already seen why it fails: a change to a helper breaks the code that imports the helper, and those tests are in other files. Walk the import graph backwards instead: from each changed file to every file that imports it, directly or through others, and run the tests of every file you reach. That is what the lesson below shows on a toy repository.

▶ SIMULATION
PULL REQUEST
changes: nothing yet
selection: —
CI
tests run: — of 14
build: —
THE CODE
tests that would fail: none
skipped dependents: 0
util.jsutil.test ; util-format.test
db.jsdb.test
billing.jsbilling.test
orders.jsorders.test
api.jsapi.test
report.jsreport.test
ring-a.jsring-a.test
ring-b.jsring-b.test
chain-a.jschain-a.test
chain-b.jschain-b.test
chain-c.jschain-c.test
chain-d.jschain-d.test
chain-e.jschain-e.test
✓ the build is red exactly when the change breaks a test✓ every test that depends on a changed file was selected
SCHEDULE
01[DEV]DEV: opens a PR that changes util.js
02[CI]CI: selects the tests of the changed files
03[CI]CI: runs the selected tests and reports the build
Start of own tests only scenario. 3 steps.
// CI: only the tests next to the files that changed
const tests = changedFiles.flatMap((f) => testsByFile[f] || []);
// util.js changed -> util.test runs. billing.test never does.

Watch the three selection modes on the same change to util.js. Own tests only and name matching both go green while a dependent is broken; the reverse-dependency walk goes red, as it should. Then run CAUGHT AFTER MERGE, where the full run on main finds what the shortcut missed. The sim proves two things: selection by changed file is unsafe, and even the safe walk is a claim that depends on a model of the code. The lesson walks through both.

The lab builds the walk for real, in about 80 lines of Python, and the real code shows three things the toy cannot.

The conftest fans in. tests/conftest.py imports clock, db and payments_client, and it applies to every test below it. So a change to checkout/db.py reaches every test in the lab, including ones that never mention the database. The graph is right and the selection is the whole suite. A module that sits under a shared fixture is, for selection, a central file.

Some files are not in the graph. pyproject.toml and requirements.txt change how every test runs. A file the walk does not know could affect anything, so the safe answer is to run everything. The lab script does that for config files and for any source file it has not seen.

A static graph misses a process boundary. The browser test in tests/e2e/ starts the checkout API and the fake provider with subprocess.Popen. Nothing in it imports checkout.api. Walk the graph backwards from pricing.py and you reach the API tests, the order tests and the extras, but not the browser test, though a wrong price shows on the very page it checks. The selector says the browser tier cannot be affected, and it is wrong. The fix is a hand-written edge, a line that says the browser test depends on checkout/api.py and fake_provider/app.py. Someone has to maintain it, and forgetting is the failure mode. Build tools such as Bazel avoid the problem by making the dependency declared and checked, which is one reason monorepos adopt them.

A second way to select is to learn it. Machalica and colleagues at Facebook trained a model on past test outcomes, and report that it cut the infrastructure cost of testing by about half while still reporting over 95% of individual test failures and over 99.9% of faulty changes. That is a trade, and the paper states it: some failures are not reported on the change, in return for half the cost. It is a tool for a very large suite and a team with the data to train and watch it. pytest-testmon is a smaller cousin that records which lines each test ran and re-runs those that touch changed lines; this lab does not install or run it.

Selection is only half of a policy. The other half is when the full suite runs. A pull request runs the selected tests and the fast tier. Every merge, or the merge queue, runs everything. Selection is what makes the first step fast, and the full run is what makes it safe to be wrong.

Flaky tests cost more at scale

A flaky test that fails one run in fifty is an annoyance on a team of nine. On 300 engineers pushing all day it is a standing tax: someone re-runs, 41 minutes pass, and the cost lands on a person who did nothing wrong. The flaky tests chapter covered causes and cures; the new fact at scale is the arithmetic. If a suite has 2,000 tests and each flakes once in 10,000 runs, the chance a build goes red for no reason is about 18% (one minus 0.9999 to the power of 2,000). That is the same kind of effect as one test with a small flake rate, multiplied by suite size. GitHub described the effect in its monolith: about 9% of commits had at least one red build caused by a flaky test, until it changed how failures were retried and brought it under 0.5%. Its blog post is worth reading for the retry design: three reruns, each under a different condition (same process, shifted time, different host), so the way a test passes again tells you why it flaked.

Two rules for CI. A retry is a stop-gap, never the fix: it hides the flake and spends the time on every real failure as well. And sharding changes flakiness. Tests that shared state by accident under one process may fail on separate machines, and tests that ran in a lucky order under serial may fail when a shard changes the order. That exposure is useful, since the next engineer would have met it anyway. Run each shard with -p no:randomly while you shard for the first time, so a failure is about the split, then turn the shuffle back on.

The policy: what runs when

Put the pieces together and you have the beat of feedback the earlier chapter described, with numbers that now fit 41 minutes.

Ring What runs Why it is cheap
Pre-push the selected tests, serial the selection is small
Pull request lint, selected tests, sharded across four runners selection and sharding, plus a required gate job
Merge queue or main the full suite, sharded across more runners the net: it catches what selection missed
Nightly re-record the durations, mutation testing, the slowest checks slow work with a day’s notice

Two details bite. First, a required status check on a matrix names each shard’s job, and a rename or a change in the number of shards leaves the branch protection waiting for a check that never reports. The common fix is one final job, tests-passed in the lab’s example, that needs the whole matrix and is the only name the rule requires. Second, a skipped selection is a red flag, not a saving: when the selector returns nothing, as it does for checkout/legacy.py because nothing tests it, say so in the log. A green build that ran zero tests looks the same as a green build that ran them.

Finally, put a number on it. The metric that matters is the time from push to a result a person trusts, at the median and at the 95th percentile, not the average run. A later chapter in this module is on which numbers to watch.

LAB Time a grown suite serial and parallel, shard it by duration, then select by change ~50 MIN
YOU NEEDlabs/testing set up (README, 'Set up'), Python 3.9+git, and a clone of the lab you may editno Docker, no network beyond pipChromium is optional: without it the browser test is skipped and every step still works

The lab’s own suite finishes in under a second, which is too short to shard. You will make a stand-in for a suite that has grown, time it three ways, write scripts/shard.py, then write scripts/select_tests.py and see which tests a change reaches. Work from labs/testing with the venv from the README, in a throwaway clone you can edit (step 8 commits in it). You add files, and append one job to ci/github-actions.yml; the last step puts the lab back. Timings are from a 12-CPU Mac on Python 3.9.6, 2026-11-24, so yours will differ in size and agree in shape.

1. Make a suite that has grown. The script writes 16 test files under tests/scale/, each test sleeping for a fixed time, so the timings are stable and the shape is uneven on purpose: three heavy files and a tail of light ones. Create scripts/make_scale_suite.py:

"""Write a stand-in for a suite that has grown: 16 test files with uneven costs.

Each test sleeps for a fixed time, so the timings are stable and a shard script has
something real to balance. Run it from labs/testing; delete tests/scale/ when done.
"""
from pathlib import Path

# seconds per test, tests per file: three heavy files, the rest light
SHAPE = [(0.60, 4), (0.55, 4), (0.50, 3), (0.20, 4), (0.20, 3), (0.15, 4), (0.15, 3), (0.10, 4),
         (0.10, 3), (0.08, 4), (0.05, 5), (0.05, 4), (0.03, 5), (0.02, 5), (0.01, 4), (0.01, 3)]

out = Path(__file__).resolve().parents[1] / "tests" / "scale"
out.mkdir(exist_ok=True)
(out / "__init__.py").write_text("")
for i, (secs, n) in enumerate(SHAPE, start=1):
    body = "import time\n\n\n"
    for j in range(1, n + 1):
        body += f"def test_case_{j}():\n    time.sleep({secs})\n    assert True\n\n\n"
    (out / f"test_scale_{i:02d}.py").write_text(body.rstrip() + "\n")
print(f"wrote {len(SHAPE)} files, about {sum(s * n for s, n in SHAPE):.1f} s of sleeping")
.venv/bin/python scripts/make_scale_suite.py
for i in 1 2 3; do /usr/bin/time -p .venv/bin/pytest tests/scale -q 2>&1 | grep -E "passed|^real" | tr '\n' ' '; echo; done
wrote 16 files, about 10.3 s of sleeping, then three lines like 62 passed in 10.88s real 11.26. Serial: 10.9 s of tests and about 11.3 s of wall-clock time. (Pytest may print a warning about urllib3 and LibreSSL on a stock macOS Python; it is about the interpreter, not your code.)

2. Try the parallel flags. Time the same suite with xdist, a few times each:

for opt in "-p no:xdist" "-n 2" "-n 4" "-n auto" "-n 4 --dist loadfile"; do
  echo "== $opt"
  for i in 1 2 3; do /usr/bin/time -p .venv/bin/pytest tests/scale -q $opt 2>&1 | grep -E "passed|^real" | tr '\n' ' '; echo; done
done

(In zsh the unquoted $opt is not split into words; run the loop under bash.)

Serial: real 11.4 to 11.5. -n 2: 6.7 to 6.9. -n 4: 4.1 to 4.3. -n auto (12 workers): 3.6 to 4.2. -n 4 --dist loadfile: 4.8 to 6.4, slower than plain -n 4 because the biggest files stay whole and one worker gets stuck behind them. Compare this with the shop suite project: the same flag that made a 3-second suite slower makes an 11-second one three times faster. Returns shrink with more workers: -n auto (12 workers) was only slightly faster than -n 4 here (about 3.3 to 3.7 s against 4.2 to 4.4 s in a second set of runs), for three times the processes.

3. Record the durations. The sharder needs the cost of each file. Pytest prints it: --durations=0 -vv lists every setup, call and teardown. You will write the script in the next step; first look at the raw material.

.venv/bin/pytest tests/scale -q -p no:randomly --durations=0 -vv 2>&1 | grep -E "^\s*[0-9.]+s call" | head -4
Four lines of the form 0.60s call tests/scale/test_scale_01.py::test_case_1: a time, the phase, and the test’s id. Add the call lines of one file to get that file’s cost; the script does it for every file and adds setup and teardown too.

4. Write the sharder. Create scripts/shard.py. Read it before you run it: record times every file, split is the whole idea (sort by cost, biggest first, give each file to the lightest shard, with the file name as the tie-break), files prints one shard’s files for a CI matrix job, and run starts all the shards as separate processes at once.

"""Split test files into shards by measured duration, and run the shards in parallel.

  python scripts/shard.py record tests/scale           # time every file, write .durations.json
  python scripts/shard.py plan   tests/scale -n 4      # show the split and its predicted times
  python scripts/shard.py files  tests/scale -n 4 -i 2 # one shard's files, for a CI matrix job
  python scripts/shard.py run    tests/scale -n 4      # run the shards as separate processes
  add --naive to plan, files or run to deal files out in turn instead (the comparison)
"""
import argparse
import json
import re
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

LAB = Path(__file__).resolve().parents[1]
STORE = LAB / ".durations.json"
LINE = re.compile(r"^\s*([\d.]+)s (?:setup|call|teardown)\s+(\S+?)::")

def collect(paths):
    files = []
    for p in paths:
        p = LAB / p
        files += [p] if p.is_file() else sorted(p.rglob("test_*.py"))
    return [str(f.relative_to(LAB)) for f in files]

def record(paths):
    cmd = [sys.executable, "-m", "pytest", *paths, "-q", "-p", "no:randomly", "-p", "no:xdist",
           "--durations=0", "-vv"]
    out = subprocess.run(cmd, cwd=LAB, capture_output=True, text=True).stdout
    seen = {}
    for line in out.splitlines():
        m = LINE.match(line)
        if m:
            seen[m.group(2)] = seen.get(m.group(2), 0.0) + float(m.group(1))
    STORE.write_text(json.dumps(seen, indent=1, sort_keys=True))
    return seen

def split(files, n, naive=False):
    known = json.loads(STORE.read_text()) if STORE.exists() else {}
    guess = sorted(known.values())[len(known) // 2] if known else 1.0   # new files get the median
    cost = {f: known.get(f, guess) for f in files}
    shards = [[] for _ in range(n)]
    if naive:
        for i, f in enumerate(sorted(files)):
            shards[i % n].append(f)
    else:
        load = [0.0] * n
        for f in sorted(files, key=lambda f: (-cost[f], f)):      # biggest first
            k = load.index(min(load))                            # onto the lightest shard
            shards[k].append(f)
            load[k] += cost[f]
    return shards, cost

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["record", "plan", "files", "run"])
    ap.add_argument("paths", nargs="+")
    ap.add_argument("-n", type=int, default=4)
    ap.add_argument("-i", type=int, default=1, help="shard number, 1 to n (files)")
    ap.add_argument("--naive", action="store_true")
    a = ap.parse_args()

    if a.cmd == "record":
        seen = record(a.paths)
        print(f"recorded {len(seen)} files, {sum(seen.values()):.2f} s in all -> {STORE.name}")
        return 0
    shards, cost = split(collect(a.paths), a.n, a.naive)
    if a.cmd == "files":
        print(" ".join(shards[a.i - 1]))
        return 0
    if a.cmd == "plan":
        for k, s in enumerate(shards, 1):
            print(f"shard {k}: {len(s):2d} files, predicted {sum(cost[f] for f in s):5.2f} s")
        return 0
    def run_one(k, files):
        cmd = [sys.executable, "-m", "pytest", *files, "-q", "-p", "no:randomly", "-p", "no:xdist"]
        t0 = time.time()
        done = subprocess.run(cmd, cwd=LAB, capture_output=True, text=True)
        return k, done.returncode, done.stdout.strip().splitlines()[-1], time.time() - t0

    live = [(k, s) for k, s in enumerate(shards, 1) if s]
    with ThreadPoolExecutor(len(live)) as pool:                  # one process per shard, all at once
        results = list(pool.map(lambda ks: run_one(*ks), live))
    worst, status = 0, 0
    for k, code, last, took in results:
        worst, status = max(worst, took), status or code
        print(f"shard {k}: {last}  (process took {took:.2f} s)")
    print(f"slowest shard {worst:.2f} s, exit {status}")
    return status

if __name__ == "__main__":
    sys.exit(main())
.venv/bin/python scripts/shard.py record tests/scale
for m in "" "--naive"; do echo "== plan $m"; .venv/bin/python scripts/shard.py plan tests/scale -n 4 $m; done

recorded 16 files, 10.87 s in all -> .durations.json. The greedy plan is level: shards of 3, 3, 4 and 6 files predicted at 2.74, 2.69, 2.70 and 2.74 s, against an ideal of 10.87 / 4 = 2.72 s. The --naive plan, which deals files out in turn, has four files on each shard and predicts 3.62, 3.35, 2.34 and 1.56 s: the same number of files and a 2.3-second gap between the first and last shard.

5. Run the shards as separate processes. Four processes, as four CI runners would be:

for m in "" "--naive"; do echo "== run $m"; /usr/bin/time -p .venv/bin/python scripts/shard.py run tests/scale -n 4 $m; done

Greedy: four lines like shard 1: 12 passed, 1 warning in 2.75s (process took 3.33 s), then slowest shard 3.38 s, exit 0 and real 3.43. Naive: slowest shard 4.19 s, with shards at 4.19, 3.97, 2.98 and 2.17 s (real 4.2). Each process takes about 0.6 s longer than pytest reports, which is Python and the app’s imports starting up: the fixed cost of every shard, and the reason to stop adding shards when each has under a few seconds of work. Against -n 4 on one machine (4.1 to 4.3 s) the greedy shards are about 20% faster, because each shard is a plain serial run with no coordinator, and the split is known in advance.

Now check the property that matters most: the shards together are the suite, and each file runs once.

.venv/bin/python - <<'PY'
import subprocess, sys
got = []
for i in range(1, 5):
    out = subprocess.check_output([sys.executable, "scripts/shard.py", "files", "tests/scale", "-n", "4", "-i", str(i)], text=True)
    got += out.split()
print(len(got), "files across the shards;", len(set(got)), "distinct")
PY
16 files across the shards; 16 distinct. Put a check like this in the pipeline and a plan that drops or doubles a file fails the build.

6. Shard the real suite, as CI would. Record the whole tests/ folder, then run each shard the way a matrix job does:

.venv/bin/python scripts/shard.py record tests
for i in 1 2 3 4; do .venv/bin/pytest $(.venv/bin/python scripts/shard.py files tests -n 4 -i $i) -q -p no:randomly 2>&1 | tail -1; done

Four summary lines: 13 passed, 1 deselected, 22 passed, 1 skipped, 24 passed and 26 passed, each in about 2.8 to 3.2 s. The total is 85 passed, 1 skipped (the browser test, without Chromium) and 1 deselected (the flaky test): the same as pytest tests in one process, which takes 11.5 s. The recorder saw 20 of the 24 files: the skipped browser test and the deselected flaky file have no timings, and two more were absent, so they take the median. A shard that held only the deselected file would exit 5 (no tests collected), which a pipeline reads as failure; that is a real thing to guard against when files are skipped by marker.

7. Read the matrix. The matrix that runs those commands is below. It is not in the lab’s ci/github-actions.yml, which has no shard job. Append it to the jobs: section of your copy (at the same two-space indent as unit:), then read it as you did the other jobs.

  sharded:
    runs-on: ubuntu-latest
    needs: lint
    strategy:
      fail-fast: false
      matrix:
        shard: [1, 2, 3, 4]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: {python-version: "3.9"}
      - run: pip install -r requirements.txt
      - run: pytest $(python scripts/shard.py files tests -n 4 -i ${{ matrix.shard }}) -q -p no:randomly

  tests-passed:
    if: always()
    needs: sharded
    runs-on: ubuntu-latest
    steps:
      - run: test "${{ needs.sharded.result }}" = "success"

Answer from the text: how many jobs does sharded start, what makes them differ, what does fail-fast: false change, and why does tests-passed use if: always(). Then check the YAML parses (any parser; this uses Ruby, which ships with macOS):

ruby -ryaml -e 'y = YAML.load_file("ci/github-actions.yml"); p y["jobs"]["sharded"]["strategy"], y["jobs"].keys'

sharded starts four jobs, one for each of [1, 2, 3, 4], and matrix.shard is the only difference: each passes its number to scripts/shard.py files ... -i. With fail-fast: false one red shard does not cancel the other three, so a failing run reports every shard’s failures at once (the default is to cancel the rest). tests-passed needs the whole matrix and runs even when it failed (if: always()), then fails if the matrix result was not success; the branch rule requires that one name. Ruby prints {"fail-fast"=>false, "matrix"=>{"shard"=>[1, 2, 3, 4]}} and the job list, ending with "sharded" and "tests-passed". This file was parsed here and not run on GitHub Actions. For the plan to be the same in every job, commit .durations.json (it is not in the lab’s .gitignore).

8. Select by change. Create scripts/select_tests.py. It parses every file with ast, finds the lab files each one imports, and walks that graph backwards from the changed files. EXTRA_EDGES is the hand-written edge for the browser test.

"""Pick the test files a change can affect: walk the import graph backwards.

  python scripts/select_tests.py checkout/pricing.py            # files named on the command line
  python scripts/select_tests.py --git                          # files changed against HEAD
  add --no-extra to drop the hand-written edges (shows the hole they close)
"""
import argparse
import ast
import subprocess
from pathlib import Path

LAB = Path(__file__).resolve().parents[1]
PACKAGES = ("checkout", "fake_provider")

# A static import graph cannot see this: the browser test starts both apps as separate
# processes, so nothing in it imports them. Say so by hand.
EXTRA_EDGES = {
    "tests/e2e/test_checkout_page.py": ["checkout/api.py", "fake_provider/app.py"],
}
RUN_EVERYTHING = {"pyproject.toml", "requirements.txt", "tests/conftest.py", "tests/__init__.py"}

def imports_of(path):
    """The lab files this file imports directly, as paths relative to the lab."""
    found = set()
    for node in ast.walk(ast.parse((LAB / path).read_text())):
        names = []
        if isinstance(node, ast.Import):
            names = [a.name for a in node.names]
        elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
            names = [node.module] + [f"{node.module}.{a.name}" for a in node.names]
        for name in names:
            if name.split(".")[0] in PACKAGES:
                for candidate in (name.replace(".", "/") + ".py", name.replace(".", "/") + "/__init__.py"):
                    if (LAB / candidate).exists():
                        found.add(candidate)
    return found

def build_graph(use_extra):
    files = [str(p.relative_to(LAB)) for pkg in (*PACKAGES, "tests") for p in (LAB / pkg).rglob("*.py")]
    deps = {f: imports_of(f) for f in files}
    if use_extra:
        for test, targets in EXTRA_EDGES.items():
            deps[test] |= set(targets)
    return files, deps

def closure(start, deps):
    seen, todo = set(), [start]
    while todo:                                   # a visited set, so cycles end
        f = todo.pop()
        if f not in seen:
            seen.add(f)
            todo += deps.get(f, ())
    return seen

def select(changed, use_extra=True):
    files, deps = build_graph(use_extra)
    tests = [f for f in files if Path(f).name.startswith("test_")]
    if any(c in RUN_EVERYTHING for c in changed):
        return sorted(tests), "a shared config file changed: run everything"
    chosen = set()
    for c in changed:
        if c.endswith(".md"):
            continue
        if c not in deps:
            return sorted(tests), f"{c} is not in the graph: run everything"
        for t in tests:
            conftest_deps = set()
            for parent in Path(t).parents:       # a conftest.py applies to every test below it
                conf = str(parent / "conftest.py")
                if conf in deps:
                    conftest_deps |= closure(conf, deps)
            if c in closure(t, deps) | conftest_deps:
                chosen.add(t)
    return sorted(chosen), "walked the import graph backwards"

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("changed", nargs="*")
    ap.add_argument("--git", action="store_true")
    ap.add_argument("--no-extra", action="store_true")
    a = ap.parse_args()
    changed = a.changed
    if a.git:
        out = subprocess.run(["git", "diff", "--name-only", "--relative", "HEAD"], cwd=LAB,
                             capture_output=True, text=True).stdout
        changed = out.split()
    chosen, why = select(changed, not a.no_extra)
    print(f"# {why}")
    print("\n".join(chosen))

if __name__ == "__main__":
    main()

Commit your new scripts first, then ask what a change in pricing.py reaches, and what a change in api.py does:

git add scripts tests/scale && git commit -qm "scale suite, shard and select scripts"
for f in checkout/pricing.py checkout/api.py checkout/ai_summary.py checkout/legacy.py; do echo "== $f"; .venv/bin/python scripts/select_tests.py $f; done
echo "== pricing, without the hand-written edge"; .venv/bin/python scripts/select_tests.py checkout/pricing.py --no-extra

For pricing.py: the comment line # walked the import graph backwards, then tests/e2e/test_checkout_page.py, tests/extras/test_extras.py, tests/integration/test_api.py, tests/integration/test_place_order.py and tests/unit/test_pricing.py. For api.py: only tests/e2e/test_checkout_page.py and tests/integration/test_api.py; the pricing unit tests do not run, since nothing in them touches the API. For ai_summary.py: only tests/extras/test_extras.py. For legacy.py: the comment and an empty list, because no test imports it. With --no-extra, pricing.py selects the same list without the browser test: the hole. A change that can change the price on the checkout page would skip the one test that looks at the page.

9. Time what selection saves, and use git. Run the selected tests for a pricing.py change against the full suite (which now includes the scale files):

.venv/bin/pytest tests -q 2>&1 | tail -1
.venv/bin/pytest $(.venv/bin/python scripts/select_tests.py checkout/pricing.py | grep -v '^#') -q 2>&1 | tail -1
echo "# edit" >> checkout/pricing.py; .venv/bin/python scripts/select_tests.py --git; git checkout checkout/pricing.py
The full run: 85 passed, 1 skipped, 1 deselected in about 11.5 s. The selected run: 20 passed, 1 skipped in about 0.65 s. After the edit --git lists the same five files as step 8; git checkout restores the file. The saving is large here because the scale files import nothing from checkout and are reached only by a change to a file under the conftest (db.py, clock.py, payments_client.py, or the conftest itself). Try db.py: the selector returns nearly everything.

Break each safeguard once. First, add a failing test file, printf 'def test_new():\n assert 1 == 2\n' > tests/scale/test_scale_17.py, and run scripts/shard.py plan tests/scale -n 4 and then run: the new file, which has no duration, gets the median and lands on a shard (plan says 2.76 to 2.90 s on each); run ends 1 failed on one shard and slowest shard ... exit 1, so the build is red as it should be. Delete the file. Second, delete .durations.json (a fresh clone that never recorded one) and run plan again: every file is guessed at 1.0 s, the split is four files on each shard, predicted 4.00 s apiece, and the real times are 3.4 s to 4.2 s or worse on a different suite; nothing warns you that the plan is blind. Restore it with record. Third, put tests/e2e/test_checkout_page.py out of EXTRA_EDGES, change api.py, and note the browser test is gone from the selection. Each breakage is silent: nothing errors, the build is green, and a test did not run.

10. Put the lab back. Step 8 committed your scripts, so the cleanest undo is to drop that commit. Do this only in the throwaway clone, because git reset --hard discards work in whatever repository you run it in. Deleting the clone does the same job.

git reset --hard HEAD~1
rm -rf tests/scale .durations.json
git checkout ci/github-actions.yml
git status --short .
.venv/bin/pytest -q 2>&1 | tail -1
git status --short . prints nothing and the suite ends 23 passed, 1 skipped, 1 deselected.
DECIDE

Ojaline's suite takes 41 minutes and every pull request waits for it. Soukaina has four proposals. The suite is 4,000 tests in about 600 files, with a long tail and a few giants, and no one has measured where the time goes. A flaky failure forces a full re-run on about one pull request in six. Which first step is best?

READING
  1. BOOK
    Software Engineering at Google, chapter 23: Continuous Integration Rachel Tannenbaum, edited by Lisa Carey, in the book edited by Winters, Manshreck and Wright, 2020

    How a very large organisation keeps feedback fast: what runs before a merge, what runs after, and why a slow or unreliable check changes how people work. Read: The whole chapter; read the sections on presubmit versus post-submit and on fast feedback and flaky tests, and skip the passages on Google's own tooling..

  2. PAPER
    Predictive Test Selection Machalica, Samylkin, Porth and Chandra (Facebook), 2019

    Selection by learning instead of by a dependency graph, and the trade stated with numbers: about half the cost of testing, over 95% of individual failures still reported, over 99.9% of faulty changes. Read: The abstract, the introduction and the evaluation; skip the details of the model's features..

  3. DOC
    Bazel: Test Encyclopedia

    The contract between a test runner and a sharding system: how many shards, which one this is (TEST_TOTAL_SHARDS and TEST_SHARD_INDEX), and what the runner may assume. Read the 'Test sharding' section; skip the rest unless you use Bazel. Read 2026-11-24.

  4. DOC
    pytest-xdist: running tests in parallel, the distribution modes

    What load, loadscope, loadfile, loadgroup and worksteal do, and why grouping tests costs balance. Read it before choosing a mode. Read 2026-11-24.

  5. POST
    Reducing flaky builds by 18x Jordan Raine, GitHub Engineering, 2020

    A measured account of flaky builds in a large monolith (about 9% of commits down to under 0.5%) and a retry design that tells you why a test flaked. Read the retry section closely; skip the tooling detail.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Testing in production: canaries, flags and synthetic checks →