Size CI Workers From cgroup cpu.max, Capped at 4
Read CPU affinity and every cgroup-v2 cpu.max quota at job start to pick a parallel worker count. A fixed --max-children 4 can oversubscribe a smaller runner.
A CI job that asks for four parallel workers is assuming four CPUs. When the container or runner it lands on is limited to fewer, the extra workers just wait for a turn on a smaller CPU budget. This post replaces a fixed worker count with a number computed when the job starts, and lists the cases where the code refuses to guess and drops to one worker.
Linux expresses those limits in two places. CPU affinity is the set of CPUs a process may run on. A cgroup (a Linux group of processes sharing resource limits) can carry a CPU quota in a file named cpu.max, and groups nest, so a parent group’s quota also applies. By the end you will have a startup check that reads the affinity and every quota from the job’s own group up to the top, takes the minimum, and falls back to one worker when the layout is unclear.
How do you size CI worker counts from cgroup cpu.max?
Compute the count when the job starts, as the minimum of the requested ceiling, a hard cap of 4, the CPU affinity from len(os.sched_getaffinity(0)), and every finite cpu.max quota from the job’s cgroup up to the root. If the topology cannot be read unambiguously, run one worker.
Why a fixed –max-children 4 oversubscribes smaller runners
Mutation testing deliberately breaks copies of your code to check that the tests notice. Each break is a unit of work, and the units run in parallel. The mutation runner here is mutmut, the Python mutation testing tool. It accepts --max-children, which sets how many worker processes run at once. The wrapper script passed it ${MUTMUT_CHILDREN:-4}. Nothing else decided the worker count.
That policy oversubscribes when the runner grants less than four CPUs. The job then runs more busy workers than the CPU budget allows, which is what CPU oversubscription means here: workers can end up waiting on each other, and the extra processes may buy no speed.
In cgroup v2, the current version of the interface, each group can have a cpu.max file that holds a quota and a period in microseconds. The value 200000 100000 means 200 ms of CPU time per 100 ms period, which is two CPUs. The word max in place of a quota means no limit. The CPU limit that matters may sit in a parent cgroup rather than the job’s own, so the job has to read the whole chain.
The sizing rule: affinity and cpu.max
The helper is scripts/dev/mutation_workers.py. Its sizing rule is the minimum of four kinds of limit: the caller’s ceiling, a hard cap of 4, the affinity count, and every finite CPU quota (cpu.max) found on the walk up to the root.
CAP = 4
def select_workers(requested, affinity, membership, mounts, root):
if requested < 1 or affinity < 1:
raise ValueError("invalid worker ceiling or CPU affinity")
return min(CAP, requested, affinity, *quota_limits(membership, mounts, root))
The affinity value is len(os.sched_getaffinity(0)). The caller’s value is a ceiling, not a target. Asking for 8 on a budget of 2 gets 2. Explicit values above 4 are clamped to 4. The cap is a ceiling kept from the old default, not a guess at the hardware: the affinity and quota terms do the sizing.
Quota parsing is strict:
def quota_workers(value: str) -> int | None:
fields = value.split()
if len(fields) != 2:
raise ValueError("malformed CPU quota")
period = positive(fields[1])
return None if fields[0] == "max" else max(1, positive(fields[0]) // period)
Fractions round down, with a floor of one. A 250000 100000 quota gives 2, and a 50000 100000 quota gives 1. The tests refuse empty, max-only, zero, negative, non-integer and zero-period values, and never read any of them as unlimited. A bad value raises an error, which drops the job to one worker, never to unlimited. The positive() helper is not shown here.
quota_limits then applies the layout checks before it reads anything:
/proc/self/cgroupmust be exactly one line of the form0::/path. That rejects cgroup v1 and hybrid layouts.- A membership of
/is refused, because root membership may hide an ancestor quota. - Exactly one cgroup2 mount must appear in
/proc/self/mountinfo, mounted at/sys/fs/cgroupwith its own root at/. Zero or several mounts mean the ancestors are hidden or ambiguous.
Only after those checks does it walk from the leaf cgroup toward the root, reading each cpu.max and collecting every finite quota. The root carries no cpu.max on native Linux, so the walk stops there rather than expecting one.
The shell wiring is two lines:
CHILDREN="$(python3 scripts/dev/mutation_workers.py --max-children "${MUTMUT_CHILDREN-4}")"
WG_FAST=1 mutmut run --max-children "$CHILDREN"
The new default drops the colon (${MUTMUT_CHILDREN-4} rather than :-4), so a value set but empty reaches the helper instead of silently becoming 4. An invalid explicit ceiling such as that is refused with an error before staging; it does not fall back to one worker.
The script prints the bare number to stdout, which is the only thing the shell captures. The diagnostic goes to stderr in the form mutation-workers: N worker(s), REASON; cap C, so the job log shows the chosen count and why. Any AttributeError, OSError, UnicodeError, ValueError or IndexError during detection, and any non-Linux platform, produces one worker with the reason “unknown CPU topology; conservative fallback”.
Why not the obvious approaches?
Changing the constant keeps the guess, and adding a limit inside the script duplicates a boundary the runner’s cgroup already enforces. The helper instead reads the visible quota and refuses to guess when the layout is unclear, which uses fewer workers on those runners by design.
Change the constant to 2. That is still a guess about hardware. It is right on a 2-CPU runner, leaves capacity idle on a larger one, and oversubscribes a 1-CPU runner. A constant used as the target was the problem, and a different constant keeps the problem.
Enforce a CPU limit inside the script. The change deliberately did not do this. The reasoning in the change description was that the runner’s own cgroup already enforces the CPU limit, so the script only has to stop requesting more fanout than the visible quota. The repository’s testing notes say it plainly: sizing observes capacity at startup only. It does not reserve CPU, account for competing jobs, or replace existing runner cgroup limits.
Let the fallback guess when the layout looks familiar. The helper refuses instead. Cgroup v1, hybrid layouts, ambiguous mounts, hidden mount ancestors and root membership all produce one worker with a stated reason. That means fewer workers on those runners, and it is intended. A wrong guess in the other direction is the oversubscription this change exists to remove.
What broke along the way
The change sat staged and uncommitted in a temporary worktree under /tmp for 18 days before it was recovered and shipped. Nothing in the repository showed it was missing. Work that lives only in a scratch directory is invisible to every other session and to CI.
Review caught two overstated claims. MiniMax, an advisory AI review bot that never blocks merges, flagged both.
- The first commit called 4 “the existing cap.” The old
${MUTMUT_CHILDREN:-4}was only a default, so a follow-up docs commit corrected the testing notes and changelog to describe 4 as a new hard cap, with larger explicit values clamped. - The second pass said the change inferred a local pre-commit pass from the commit existing, and asserted that the audit-harness (the in-repo package of deterministic test-quality checks) verification had passed, with no output attached. The lane was re-run on the exact head commit, and the results were attached: harness hash OK, gitleaks found no leaks, and the fast tier reported 35 PASS lines and 0 FAIL.
The lesson is narrow. A claim in a pull request describes one exact commit. Re-run it on that commit before writing it down, and attach the output.
What the tests cover and what remains unmeasured
The change touched 9 files, +253/-14. The CI run on head commit 51f7eaf5 succeeded. The mutation gate’s evidence envelope now hashes scripts/dev/mutation_workers.py as an input, so editing the helper invalidates earlier gate evidence. The full mutation population, the selected tests, the timeout and the 74% floor are unchanged.
The unit tests use a fake cgroup tree in a temporary directory. They cover these cases:
- Affinity bounds the result: a ceiling of 4 on affinity 2 gives 2.
- The hard cap bounds the result: 8 on affinity 32 gives 4.
- The ceiling is honored: a request of 1 gives 1.
- Malformed or missing quotas are never read as unlimited.
- Hidden, hybrid and escaping layouts are refused, and a detection failure falls back to one worker with a diagnostic.
- An invalid explicit ceiling is refused instead of falling back.
- A parent quota bounds an unlimited child: parent
200000 100000over childmax 100000gives 2. - Fractional quotas round down with a floor of one: a parent of
300000 100000over a child of250000 100000gives 2, and a child of50000 100000gives 1.
What this does not show is speed. The effect on elapsed time and timeout risk has not been measured. This is a worker-sizing pilot, not a demonstrated speed or billing improvement. The next step is to time the same mutation job before and after on the same runner class, and record the numbers.
The kernel’s cgroup v2 guide at https://docs.kernel.org/admin-guide/cgroup-v2.html is the reference for the cpu.max format the parser depends on.
Use this
- Before any parallel job starts, compute the worker count as the minimum of the requested ceiling, a hard cap,
len(os.sched_getaffinity(0)), and every finitecpu.maxquota from the leaf cgroup to the root. Print the diagnostic line to stderr so the chosen count appears in the job log. - Write tests against a fake cgroup tree in a temp directory for four things: a parent quota bounding an unlimited child, a fractional quota, each malformed
cpu.maxvalue, and a layout that must fall back to one worker. - Read the kernel’s cgroup v2 guide at https://docs.kernel.org/admin-guide/cgroup-v2.html before writing a parser, and time one real job before and after the change so the elapsed-time claim gets a number.
Frequently asked questions
What does a cgroup v2 cpu.max value mean?
The file holds a quota and a period, both in microseconds. 200000 100000 means 200 ms of CPU time per 100 ms period, which is two CPUs. The word max in place of a quota means no limit. Groups nest, so a parent’s quota also bounds a child that reads max.
Why is a fixed –max-children 4 a problem on CI?
A fixed count assumes a machine. When the runner grants fewer CPUs than workers, the extra workers compete for a smaller CPU budget. The old wrapper passed ${MUTMUT_CHILDREN:-4} to mutmut, and nothing else decided the count.
What happens when the cgroup layout cannot be read?
The helper runs one worker and prints the reason to stderr. It refuses cgroup v1, hybrid layouts, root membership, and zero or several cgroup2 mounts. A malformed cpu.max value raises an error, which drops the job to one worker, never to unlimited.