Sub topic 9
Balancing shards by time with a greedy algorithm
This chapter assumes you know how a CI matrix runs one shard per job, and that you have per-file test durations recorded from earlier runs. Count-based and hash-based splitting ignore how long each file takes. When one file takes 120 seconds and another takes 5, equal file counts can give very unequal shards. The slowest shard sets the total CI time, so balance matters.
The problem: bin packing
Balancing by time is a bin-packing problem. You have a set of items (test files) with sizes (durations) and a fixed number of bins (shards). You want the largest bin to be as small as possible. Finding the perfect answer is expensive for large suites, but a simple heuristic gets close.
The heuristic is called longest-processing-time-first (LPT):
- Sort the test files by duration, longest first.
- Keep a running total for each shard.
- Give each file to the shard with the smallest total so far.
Placing big files first leaves the small files to fill the gaps at the end. That is why the result is usually close to even.
Implementation
The code below uses a heap, which always returns the least-loaded shard in logarithmic time. Each heap entry is a tuple of (total, index, items). The index breaks ties, so Python never has to compare the lists.
import heapq
def split_by_time(durations: dict, shards: int) -> list:
"""Assign each test file to the currently least-loaded shard, longest files first."""
heap = [(0.0, i, []) for i in range(shards)]
heapq.heapify(heap)
for name, secs in sorted(durations.items(), key=lambda kv: kv[1], reverse=True):
total, i, items = heapq.heappop(heap)
items.append(name)
heapq.heappush(heap, (total + secs, i, items))
return [(total, items) for total, i, items in sorted(heap, key=lambda b: b[1])]
durations = {"a.test": 120, "b.test": 90, "c.test": 60, "d.test": 50, "e.test": 40, "f.test": 30}
for n, (total, items) in enumerate(split_by_time(durations, 2), start=1):
print(n, total, items)Tracing the example
With two shards, the files are handled in this order: a (120), b (90), c (60), d (50), e (40), f (30).
| Step | File | Goes to | Shard 1 total | Shard 2 total |
|---|---|---|---|---|
| 1 | a.test (120) | shard 1 | 120 | 0 |
| 2 | b.test (90) | shard 2 | 120 | 90 |
| 3 | c.test (60) | shard 2 | 120 | 150 |
| 4 | d.test (50) | shard 1 | 170 | 150 |
| 5 | e.test (40) | shard 2 | 170 | 190 |
| 6 | f.test (30) | shard 1 | 200 | 190 |
Compare this with the table above. Run the script and check its output against it: the totals depend on tie-breaking and order, so trust the program's output over a hand trace. The steps show the idea, which is that each file lands on whichever shard is lighter at that moment.
Using the result in CI
A runner's --shard=index/total flag cannot take a custom list. Instead, run the splitter in a setup step, then pass the chosen files to the runner as arguments. Make sure every shard computes the plan from the same duration data. Otherwise two shards can pick overlapping lists, or leave files out entirely.
Common errors
- New files have no timing. Assign them the average duration of known files, or a fixed default, so they are not treated as free.
- Deleted files remain in the data. Drop any entry with no matching file on disk, or you will schedule tests that do not exist.
- Stale numbers. Durations drift as tests change. Refresh the data on a regular schedule.
- One huge file. A single 300-second file cannot be split by this method. The longest shard will be at least that long. Split the file instead.
Exercise
Using splitbytime with durations {"a": 100, "b": 60, "c": 50, "d": 40} and 2 shards, what are the two shard totals, and why does sorting longest first help?
Show answer
Shard 1 gets a (100) and then d is placed on the lighter shard. Order: a goes to shard 1 (100), b to shard 2 (60), c to shard 2 (110), d to shard 1 (140). Totals are 140 and 110. Wait, check: after c, shard 1 is 100 and shard 2 is 110, so d goes to shard 1, giving 140 and 110. Sorting longest first helps because small files placed last can fill small gaps, while placing a large file last could leave one shard far heavier than the other.