Sub topic 8
Recording Test Durations Between Runs
Timing-based splitting needs data: how long each test file took last time. This chapter covers how to record that data, where to keep it, and how to keep it trustworthy. It assumes you can read YAML and Python, and that you have run a suite from the command line in a CI job.
Why durations matter
Count-based and hash-based splits treat every test file as equal. Real files are not equal. One end-to-end file may take two minutes while ten unit files take two seconds each. A greedy splitter, covered in the next chapter, can only balance shards if it knows each file's cost. Durations are its input.
Where durations come from
Most runners already measure time. You only need to export it in a machine-readable form.
- JUnit XML reports record a
timeattribute on eachtestcaseandtestsuiteelement. Many runners and plugins can write this format. - Playwright's JSON reporter records a
durationin milliseconds for each test. - Jest can write JSON output with
--json --outputFile=results.json.
Aggregate per file, because shards are assigned per file. A file's cost is the sum of its test durations.
import json
import sys
from collections import defaultdict
def durations_from_playwright(report_path: str) -> dict:
"""Sum test durations (seconds) per spec file from a Playwright JSON report."""
with open(report_path, encoding="utf-8") as f:
report = json.load(f)
totals = defaultdict(float)
def walk(suite):
for spec in suite.get("specs", []):
for test in spec.get("tests", []):
for result in test.get("results", []):
totals[spec["file"]] += result["duration"] / 1000.0
for child in suite.get("suites", []):
walk(child)
for top in report.get("suites", []):
walk(top)
return dict(totals)
if __name__ == "__main__":
print(json.dumps(durations_from_playwright(sys.argv[1]), indent=2, sort_keys=True))Each shard produces timings for only its own files. Merging the per-shard outputs gives the full picture.
Storing the data between runs
Timings must outlive the job that produced them. You have three common options.
| Storage | Strengths | Weaknesses |
|---|---|---|
| Committed file in the repository | Simple, versioned, works for every branch | Creates noisy commits, needs a refresh step |
| CI cache or artifact from the main branch | No commits, updates automatically | Entries can expire, and cache scoping rules vary by CI system |
| External store (object storage, database) | Shared across pipelines, keeps history | More infrastructure to run |
For most teams, saving a JSON file as an artifact on the main branch and downloading it in later runs is enough.
Keeping the data useful
Raw timings go stale and contain gaps. Handle these cases explicitly.
- New files have no history. Give them the median of known durations, so they are neither ignored nor treated as free.
- Deleted files linger. Drop entries for paths that no longer exist, or the splitter reserves capacity for tests that never run.
- Single runs are noisy. A slow runner or a cold cache can double one measurement. Blend new values into old ones, for example
0.7 * old + 0.3 * new. - Retries inflate time. Decide whether a retried test counts once or every attempt. Counting every attempt matches real shard cost, but it can penalize flaky files.
from statistics import median
def update_timings(old: dict, new: dict, existing_files: set, alpha: float = 0.3) -> dict:
"""Blend new measurements into old ones and drop files that were deleted."""
merged = {}
for path in existing_files:
if path in new and path in old:
merged[path] = (1 - alpha) * old[path] + alpha * new[path]
elif path in new:
merged[path] = new[path]
elif path in old:
merged[path] = old[path]
known = list(merged.values())
default = median(known) if known else 1.0
for path in existing_files:
merged.setdefault(path, default)
return mergedCommon errors
- Timing paths that do not match the paths the splitter sees, for example absolute paths in one and relative paths in the other. Normalize to repository-relative paths.
- Updating timings from pull request branches. Their changes may add slow tests that never reach main.
- Treating the data as exact. It guides the split. It does not guarantee equal shard times.
Exercise
A new test file checkout.spec.ts has no entry in your timing file, and the known durations are 4s, 10s and 40s. What default duration should the splitter use, and why not zero?
Show answer
Use the median, 10s. A value of zero makes the file look free, so the splitter may stack it onto an already full shard. The median is a neutral guess until a real measurement exists.