Skip to content

fix(supervisor): default W from availableParallelism(), not the host's core count (#341) - #343

Merged
pdettori merged 1 commit into
mainfrom
fix/341-sh-workers-cgroup-aware
Sep 25, 2026
Merged

pdettori merged 1 commit into
mainfrom
fix/341-sh-workers-cgroup-aware

Conversation

@pdettori

Copy link
Copy Markdown
Member

Fixes #341.

The bug

readConfig computed SH_WORKERS's default as defaultWorkers(cpus().length). os.cpus() enumerates the host's physical CPU list and never consults a cgroup CPU quota, so under docker run --cpus=N, a Kubernetes CPU limit, or any quota-based cap the default described the whole machine rather than the allocation the supervisor actually has. Node's own documentation for os.cpus() says not to do this outright:

os.cpus().length should not be used to calculate the amount of parallelism available to an application. Use availableParallelism for this purpose.

Two consequences, both silent:

  • an operator deploying P6 in a CPU-limited container got an oversized, thrashing worker pool, with no error and no warning;
  • because P6's thesis is density against a fixed W (spec §5.1; E8/E9), any density number gathered in such a container measured the host, not the deployment under test.

It is the same failure defaultWorkers's docstring already worried about for the os.cpus() === [] case, from the opposite direction — too many, not too few.

The fix

availableParallelism() wraps libuv's uv_available_parallelism(), which reads cpu.max (cgroup v2) / cpu.cfs_quota_us (v1) and clamps to the quota. The change is the call site alone:

  • defaultWorkers keeps its signature and its Math.max(1, n) clamp untouched, so it stays a pure function of a count and its existing 0/1/8 tests are unchanged. The clamp is now belt-and-braces rather than load-bearing, since availableParallelism() is documented to always return a value greater than zero; the docstring says that instead of naming os.cpus() as the source.
  • No change on the explicit path — an operator's SH_WORKERS is read and validated exactly as before.

The test had to force the two sources apart

The pre-existing default-value assertion could not catch this and still cannot: both sources return 10 on the machine this was written on, so they agree on any unconstrained host. config-workers-cpu-source.test.ts mocks node:os so cpus() reports 8 (the host) while availableParallelism() reports 2 (a --cpus=2 quota), then asserts the literal 2. It also guards the fixture by asserting the two counts differ — were they ever equalised, the file would pass whichever source readConfig read and silently test nothing. A second case pins that an explicit SH_WORKERS=5 still wins under the same mock: the quota is the default's source, not a ceiling, or pinning W across an E8 ladder on a quota'd host would break.

Docs that stated the old behaviour as fact move with the code: the spec §3.8 table and supervisor.env.example both named os.cpus().length.

Verification

  • Red/green proven on this base: reverting just the call site fails the new test (expected 8 to be 2); restoring it passes.
  • Full supervisor suite green — 117 passed, 2 skipped.
  • tsc --noEmit clean; prettier and pre-commit clean on the touched files.
  • No consumers outside the package: nothing depends on @sh/supervisor, and defaultWorkers has no caller beyond this file.

Verifying against a real CPU-limited container is explicitly out of scope per the issue, pending a Docker Compose deployment for P6.

🤖 Generated with Claude Code

…s core count (#341)

`readConfig` computed `SH_WORKERS`'s default as `defaultWorkers(cpus().length)`.
`os.cpus()` enumerates the HOST's physical CPU list and never consults a cgroup CPU
quota, so under `docker run --cpus=N`, a Kubernetes CPU limit, or any quota-based cap
the default described the whole machine rather than the allocation the supervisor
actually has. Node's own documentation for `os.cpus()` says not to do this outright:
"`os.cpus().length` should not be used to calculate the amount of parallelism
available to an application. Use `availableParallelism` for this purpose."

Two consequences, both silent. An operator deploying P6 in a CPU-limited container
got an oversized, thrashing worker pool with no error and no warning. And because
P6's whole thesis is density against a fixed W (§5.1; E8/E9), any density number
gathered in such a container measured the host, not the deployment under test. This
is the same failure `defaultWorkers`'s docstring already worried about for the
`os.cpus() === []` case, from the opposite direction: too many, not too few.

`availableParallelism()` wraps libuv's `uv_available_parallelism()`, which reads
`cpu.max` (cgroup v2) / `cpu.cfs_quota_us` (v1) and clamps to the quota. The fix is
the call site alone: `defaultWorkers` keeps its signature and its `Math.max(1, n)`
clamp untouched, so it stays a pure function of a count and its 0/1/8 tests are
unchanged. The clamp is now belt-and-braces rather than load-bearing, since
`availableParallelism()` is documented to always return a value greater than zero,
and the docstring says so instead of naming `os.cpus()` as the source.

THE TEST HAD TO FORCE THE TWO SOURCES APART. The pre-existing default-value
assertion could not catch this and still cannot: both sources return 10 on the
machine this was written on, so they agree on any unconstrained host. The new
config-workers-cpu-source.test.ts mocks `node:os` so `cpus()` reports 8 (the host)
while `availableParallelism()` reports 2 (a `--cpus=2` quota), asserts the literal 2,
and guards the fixture by asserting the two counts differ -- were they ever equalised
the file would pass whichever source `readConfig` read and silently test nothing. A
second case pins that an explicit `SH_WORKERS=5` still wins under the same mock: the
quota is the default's source, not a ceiling, or pinning W across an E8 ladder on a
quota'd host would break.

Docs that stated the old behaviour as fact move with it: the §3.8 table and
supervisor.env.example both named `os.cpus().length`.

Verified: red/green proven on this base -- reverting just the call site fails the new
test ("expected 8 to be 2") and restoring it passes. Full supervisor suite green (117
passed, 2 skipped), tsc --noEmit clean, prettier and pre-commit clean. No consumers
outside the package: nothing imports `@sh/supervisor`, and `defaultWorkers` has no
caller beyond this file.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>

@mrsabath mrsabath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified the fix and its claims against origin/main, and confirmed the central methodological point holds on my machine too.

The bug is real and the fix is right. config.ts:90 on main was the tree's only cpus() consumer for parallelism — every other node:os import across packages/ and harness/ is tmpdir/homedir. availableParallelism() is the documented replacement, and Node says so in the terms the PR quotes.

The "both sources agree" claim reproduces. On this machine cpus().length === 16 and availableParallelism() === 16. That is the load-bearing justification for the new test file, and it checks out: the pre-existing config.test.ts default assertion genuinely could not have caught this, and still can't. Mocking the two apart is the only way to pin which source readConfig reads.

The test is well-built. vi.hoisted is established practice here (8 other files use it). The mock spreads ...actual and overrides both functions, so tmpdir and friends survive for any transitive consumer. The named import import { availableParallelism } from 'node:os' is correctly intercepted. { min: 1 } with no max means both QUOTA_CORES=2 and SH_WORKERS=5 pass validation, so both assertions are sound. The fixture guard (expect(QUOTA_CORES).not.toBe(HOST_CORES)) is the right instinct — without it the file would silently test nothing if the constants were ever equalised. vitest.config.ts's include: ['test/**/*.test.ts'] matches the new filename, so it actually runs.

Blast radius confirmed minimal. defaultWorkers has no caller outside config.ts and its tests; nothing in the repo depends on @sh/supervisor. The readInt fallback-bounds reasoning is accurate: Math.max(1, n) guarantees ≥1, so that branch can't fire for SH_WORKERS, and framing it as a net for future defaults rather than dead code is the correct read.

Docs claims verified. main really did state os.cpus().length as fact in both places the PR updates — spec §3.8 table (line 373) and supervisor.env.example (line 3). Issue #341 is open and describes exactly this.

fix(supervisor): conforms to CONTRIBUTING's conventional-commit format; signed off, DCO green.

CI: proto is failing, and I could not attribute it

proto fails here but passes on main (3057c5f). I chased it rather than assuming:

  • The failing step is "Build and test remote-worker" (ci.yml:219-224) — gofmt, go vet, go test -race, all scoped to working-directory: remote-worker.
  • This PR touches zero files under remote-worker/ and nothing Go code can import. The step is structurally incapable of being affected by this diff.
  • gofmt -l . and go vet ./... are clean on this base, so the failure is inside go test -race.

I could not read the actual failure: my environment's TLS interception blocks the Actions log blob URLs, and the check-run annotation carries only "Process completed with exit code 1" with no test name. So I am not claiming I verified this is a flake — only that it cannot be caused by these changes. There is precedent for flakiness in this job (fix/prompt-workload-routing flipped success→failure across reruns on the same head).

Worth a rerun to confirm before merge. If it reproduces, it is a pre-existing remote-worker break that deserves its own issue rather than blocking this PR.

One nit

The commit subject is 88 characters — over the conventional 72. CONTRIBUTING doesn't state a limit and no check enforces it, so this is not worth a re-push on its own; flagging it only in case you're amending for another reason.

Nothing here blocks the merge.

@rubambiza rubambiza left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Tight, correct, well-scoped fix. Swaps os.cpus().length -> os.availableParallelism() at the single readConfig call site so the default worker count W respects a cgroup CPU quota (--cpus=N, a K8s CPU limit) instead of reporting the host's physical cores. defaultWorkers keeps its signature and Math.max(1, n) clamp (now belt-and-braces), the explicit SH_WORKERS path is untouched, and the co-located comments, spec 3.8 table, and supervisor.env.example all move with the behavior.

The new config-workers-cpu-source.test.ts is the highlight: it mocks node:os to force the two sources apart (host 8 vs quota 2), asserts the literal quota, and guards the fixture with expect(QUOTA_CORES).not.toBe(HOST_CORES) so it can never silently test nothing. A second case pins that an explicit SH_WORKERS still wins, so the quota is the default's source and not a ceiling. Red/green is proven on this base.

Author: pdettori (MEMBER - maintainer)
Areas reviewed: TypeScript (supervisor config + tests), Docs (spec + env example)
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, signed-off: yes
CI status: one check failing - proto / Build and test remote-worker - but that step lives in the Go remote-worker module (go.mod not found), which this PR does not touch. Unrelated to this change; all TypeScript checks (check, lint) pass.

No must-fix or suggestion findings. LGTM.

@pdettori
pdettori merged commit 20ba3b8 into main Sep 25, 2026
12 of 13 checks passed
@pdettori
pdettori deleted the fix/341-sh-workers-cgroup-aware branch September 25, 2026 16:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

supervisor: SH_WORKERS default reads host CPU count via cpus().length, blind to container/cgroup CPU limits

3 participants