Repository navigation
perf(workers): centralize bounded worker pool sizing - #167060
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed October 8, 2026, 8:09 AM ET / 12:09 UTC (Revision 7). ClawSweeper reviewWhat this changesThis PR centralizes CPU-based worker sizing, bounds independent parallel work, and preserves serial execution for stateful or ordered operations. Review scores
ProductKind: Performance · Worth it: Yes Merge readiness✅ Ready for maintainer review This PR remains useful and has sufficient runtime evidence. The workspace-heap finding is repaired, and the previous stored-data compatibility blocker does not apply to this diff; no actionable introduced defect remains. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherOpenClaw runs expensive computation and database reads in background workers so the Gateway can keep handling requests. The changed sizing owner selects worker counts and heap defaults while the existing scheduler retains admission, cancellation, and cleanup. flowchart TD
A[Agent and plugin requests] --> B[Existing worker pool]
C[Available CPU capacity] --> D[Central sizing policy]
D --> E{Independent or serial work}
E --> F[Bounded parallel workers]
E --> G[Single worker]
B --> F
B --> G
F --> H[Results and owned cleanup]
G --> H
Technical reviewBest possible solution: Keep one sizing owner while retaining the existing scheduler, serial lifecycle owners, numeric SDK compatibility, and explicit resource exceptions. Do we have a high-confidence way to reproduce the issue? Not applicable as an existing-behavior bug report; replicated prompt-worker measurements establish the bottleneck, and supplied before/after controls establish both repaired regressions. Is this the best way to solve the issue? Yes. The patch moves sizing into the existing host boundary and reuses the scheduler while preserving the intentional serial and resource-qualified paths. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against b925148b83b7. Provenance checked
TestingProof path: shipped entry point. Added test files: 4. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +71, Tests +113, Docs +29, Other +1. Total +214 across 46 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (6 earlier review cycles)
|
bd07bd0 to
8274df3
Compare
bca3f0c to
304cdd3
Compare
Keep the retained shared-state reader pool at its existing minimum of two workers while scaling through the central reader cap. A held settlement read must leave room for fresh catalog reads before the caller releases it. Exercise the existing avatar regression with a two-CPU OS input. Node 24 two-CPU rig proof: 83 passed, two existing Bun-only skips; the late-catalog case completes in 2.052 seconds instead of timing out at 120.
|
The stored-data compatibility flag is a false positive for this diff. In Head |
|
Final CI run |
Derive bounded reader and compute capacities from available CPUs through one host sizing owner, preserving serial owners, SQLite writer ownership, and existing numeric SDK contracts. Keep the shared-state reader minimum of two for retained-read progress and a workspace-specific 1 GiB heap for supported maximum manifests. Controlled prompt throughput improved 1.86x with explicit memory tradeoffs; whole-Gateway measurements remain observational. Focused remote tests, types, lint, export/closure guards, and independent review passed. Final CI contains only inherited UI streaming failures: all 14 cases reproduced unchanged on its main parent. Landed under the authorized inherited-failure exception; see PR for evidence and limitations.
What Problem This Solves
Independent prompt preparation and reads can wait behind unrelated worker tasks, while uncapped pools can allocate an isolate for every available CPU.
User Impact
Independent work gains bounded parallelism, with one host owner for pool sizing. Node continuations, catalog generations, usage-cost lanes, ordered side effects, and shared native heaps retain serial execution. SQLite still has exactly one writer per physical database. Current main's parallel transcript history/context and pool-wide cleanup are preserved.
No operator setting, dependency/version change, or storage migration is introduced. Memory-core changes worker capacity only: embedding/vector metadata, persisted shapes, SQL, and writer ownership are unchanged.
Why This Change Was Made
The host derives class limits from
os.availableParallelism(), reserving one CPU when possible: readers cap at eight, small-file readers at two, compute at four, and writers/singletons at one. All productionWorkerTaskPoolsites in core and bundled plugins consume the sizing owner, either through a class or a prepared numeric budget. Shared-state readers keep their existing two-worker minimum for retained-read progress and scale to eight. Existing broker/preflight, foreground transcript, and inventory-hashing budgets move there unchanged. Foreground history/context each keep half the CPU headroom, capped at eight; background transcript owners remain serial. Hashing retains its CPU/memory admission and low-memory/Bun-Linux inline fallback.The existing scheduler still owns FIFO admission, shared compute, cancellation, and cleanup. Independent parallel work may finish out of order. Prepared host capacity leaves caller options intact, preserving inherited preparation hooks and lazy getters. Scalable classes default to a 512 MiB V8 old-generation limit, with explicit caller resource limits preserved. Workspace computation alone uses 1 GiB to preserve the supported three-way overlay of 64 MiB manifests; measured maximum-input live worker heap was about 648 MiB. Native/Buffer/WASM memory is additional, so these are not total RSS caps.
Numeric-only SDK callers retain their behavior. Three separately published plugin sites keep numeric fallbacks for supported older hosts; current hosts prioritize class sizing. Remove these fallbacks when their minimum host version includes the policy.
Production LOC: +72 (151 added, 79 removed using the requested test/test-support/docs exclusions, including one wrapper-inventory line). Growth establishes the typed sizing contract, heap defaults, SDK/lifecycle compatibility, the existing maximum-manifest input contract, and retained shared-state read progress on small hosts. Scattered CPU formulas and capacities are removed, including the newly integrated transcript/hash owners; no second scheduler, cache, or registry is added.
Evidence
Prompt-worker performance
Production prompt workers, 20 concurrent synthetic requests, four available CPUs, three fresh-process replicates per variant, 300 measured requests each; table values are medians:
1.86× throughput, 56% lower mean queue wait, and 42% lower pool-call p99, at about 101 MiB incremental process RSS per added source-mode worker. These are component timings. Increasing small-file readers from two to three regressed throughput 5.2% and p99 6.8%, so their final cap stays two. Wider pools also regressed on an initially CPU-saturated rig; no improvement under CPU oversubscription is claimed.
Provider
blacksmith-testbox, profileopenclaw-check, leasetbx_01m4d0d7f2027xqy04jr19nkx9:node --expose-gc --import ./scripts/tsx.mjs <synthetic-pool-benchmark> <kind> <variant> <replicate>. Six baseline runs passed in 41.967 s including dependency installation; six candidate runs passed in 29.851 s. Every reply validated; lease stopped.Actual Gateway measurement
Eight-CPU Linux rig, Node 26.8.1, matched baseline
d3309e5760116877852a800c2ed21f9d15864c8eversus candidate tree2f27804ff02865e5b694f42803871b1c106ade5e(measured head8274df39f339f60cc083dbda39a577071a8386ca, before the narrow workspace-heap compatibility repair). The subsequent workspace-heap repair changes no pool count; the shared-state reader minimum repair only changes hosts with fewer than three available CPUs, so the measured eight-CPU pool sizing is unchanged. Each run used 20 seeded sessions, 20 WebSocket clients, two measured minutes, 50 ms RPC cadence, and exactly four serialized synthetic turns. This is not 20 simultaneous model turns or a production deployment.These Gateway numbers are observational, not a causal speedup claim. Whole-host CPU busy fractions differed: baseline 87.1%/69.2% across the two minutes, candidate 43.5%/73.5%. The prompt pool stayed at one physical worker with seven tasks in each run, so this workload did not exercise the component gain above. Method results were mixed, including a substantially higher
cron.listtail in the candidate; unequal host contention and one matched pair leave that direction unattributed, not a demonstrated improvement or an established policy-caused regression.sessions.listhandler p99 estimatechat.historyhandler meanchat.historyhandler p99 estimatechat.historyp99chat.metadatahandler p99 estimatemodels.listhandler p99 estimatecron.listhandler p99 estimatecron.listp99cron.statushandler p99 estimatesessionTranscriptqueue waitstateReadqueue waitServer p99 values use official Prometheus histogram interpolation; brackets show the containing bucket, not confidence intervals. Client p99 uses exact observed RPC durations. Startup counters are excluded, all received handlers completed, and no diagnostics/series were dropped. The three added state readers corresponded to about 52 MiB additional process RSS per worker at the late heartbeat; GC-sensitive process differences are observations, not independently attributable per-thread RSS or a bound. Worker-heap delta was about 42 MiB per added worker.
The first baseline attempt stopped before measurement because WebSocket readiness preceded agent-store preparation. The fixture now waits for the documented
/startupzthen/readyzbarriers before unchanged seeding; the recovered baseline had no seed retry or schema error. Its existingprojects.listaccess-revision retry path ran five times during measured load (candidate: zero); no new measured-call retry logic was added. Both measured variants completed four turns and shut down with Gateway exit 0.node --import ./scripts/tsx.mjs scripts/build-all.mts sourcePerformancepassed for both matched trees (121.3 s baseline, 115.0 s candidate). A compiled SDK probe also confirmed reader/file-reader/compute caps 7/2/4, serial caps one, class precedence over numeric fallback, and 20 valid prompt requests across four physical workers. Rig commands used isolated state/TMPDIR and loopback ports undernice -n 10 ionice -c3; runtime inherited no build-only heap setting. Rig fallback followed two Testbox sync timeouts and AWS/Hetzner fleet-cap admission refusals.Correctness and validation
The integrated sizing revision passed 87 tests across ten files in 143.69 s: policy/preparation, transcript lanes/readers/context/readiness, hashing/resource limits, copy scheduling/file transport, and Codex history. Core production types, infrastructure/session test types, targeted lint, export-collision checks, and both closure suites passed. Commands use
node scripts/run-tsgo.mjs,node scripts/run-oxlint.mjs,node --import ./scripts/tsx.mjs scripts/check-export-name-collisions.mts, andnode scripts/run-vitest.mjsagainst those owners.The prior-base full changed gate passed all production types, all 27 core-test type groups, extension-test types, guards, dead exports, and lints after two test-only lint corrections. The first segment took 2929.94 s; its canonical continuation from lint took 776.06 s. Ten prior rebase-overlap files passed 92 tests with two filesystem-alias skips. That proof is reused only for unchanged inputs; the scoped integration checks above cover the conflict resolution. Earlier wider sibling coverage included 207 passing tests, eight Darwin-only skips, and two Bun-only skips.
New preparation regression cost:
node scripts/run-vitest.mjs src/infra/worker-task-pool.preparation.test.ts --maxWorkers=1passed 20 tests in 38.52 s wall time; cold transformation was 98% of the 35.30 s runner duration, and the twelve added cases totaled 0.126 s of test execution. Original sizing fails all ten class-admission cases; the rejected option-copying implementation fails both inherited/lazy-option cases for the intended reasons. CI run37769955590, job113287437575, passed the same 20 cases with 0.298 s summed test execution; the twelve added cases consumed 0.202 s. Shared import/setup and file wall time were not separately logged.Known historical fixture failure:
session-transcript-reconcile.lifecycle.test.ts:217timed out at the original branch base, followed by deleted-fixture cleanup errors. The same selection on unchangedc531ab224174d94e78e803de46355915298ab477reproduced that timeout and cascade (204 passed / 66 failed, 395.72 s). This PR does not claim to repair that fixture, and this is not current-main CI qualification.Fresh independent review of the integrated candidate completed with no actionable P0–P2 findings. No full 128-CPU host comparison or live production before/after deployment is claimed.
CI run
37763793380caught one introduced regression: the generic 512 MiB heap was too small for maximum-size workspace overlays. The original test failed on the candidate and passed on unchanged main under exact Node 24.19 with no old-space override. The final repair (bca3f0ca41ae0e998953e2542e4b9b5684af2178, tree6ef19cbfc8ae6275d00be0944866e3167e21cb6e) gives only the workspace owner a 1 GiB ceiling. All 33 manifest/Git-worker tests passed in 84.20 s external wall with a constrained young generation. The actual repaired owner processed all 250,000 entries changed, with an effective 1036 MiB heap, sampled peak 648.02 MiB used, and process RSS peak 1343.33 MiB. Input limits and test assertions are unchanged. Targeted lint and incremental core types passed; fresh independent review found no actionable P0–P2 issue.An inherited 8 GiB
NODE_OPTIONSold-space setting overrides actual worker limits, so passes with that setting were excluded from the heap proof. The final tests use only--max-semi-space-size=4, preserving the actual 1 GiB old-generation limit. The measured process RSS includes the fixture parent and worker and is not a per-thread RSS bound.Two other first-run failures were independently reproduced on unchanged main
4f44864c33c81ba96ade354c7f26e2a0d8617e24: context-read completion ordering (45 other cases passed) and local model-owner lookup count (eight other cases passed). Those assertions were corrected upstream ind8c8047cab63and839ad946cf2d; this PR does not claim their fixes. The new push contains the verified heap repair; no workflow rerun or branch update was dispatched merely to chase green.The preceding head
304cdd3abcf5f7175936ce25a86f20af69e9ee2awas a required conflict rebase onto9c057a3916bd584fb5eb8ff1d436533b67771575. Main inlined the Codex worker-URL helper; the resolution preserves that cleanup and the same reviewed reader class/numeric fallback. The heap repair is patch-identical, its manifest dependencies are byte-unchanged, and no new pool sites appeared. A focused Codex replay verifies the resolved owner; prior evidence is reused for unchanged inputs.CI run
37769955590caught a second introduced regression on its two-CPU runner: applying generic CPU headroom reduced shared-state readers from two to one. An avatar settlement read retains its worker until caller release, while a fresh catalog read must complete before that release; one slot deadlocked. The sizing owner now preserves the shared-state pool’s two-worker minimum, still capped at eight, with its existing 512 MiB heap limit. Other reader classes are unchanged. The existing avatar regression supplies a two-CPU OS input; no new test case, timeout change, or scheduler/SQLite custody change was needed.On the Linux rig under Node 24.19 and
taskset -c 0,1, withNODE_OPTIONSunset, the original candidate timed out only in that case at 120.066 s while unchanged main977b46b22f21a1dbb98be73ba2fac779642ae817passed all 11 cases (affected case 2.054 s). Repaired tree9a6cfea3873d459aa6be48f91a2596a794f1b09fpassed 83 tests across seven files, with two existing Bun-only skips, in 77.70 s external wall / 76.93 s wrapper time. The affected case took 2.052 s. Avatar cases consumed 15.957 s summed execution; its shared two-file shard took 29.07 s, so that is not an isolated avatar wall-time measurement. This includes shared-state reader ownership, settlement, MCP/source generations, and ordinary pool-preparation coverage.The shared-state repair received fresh independent P0–P2 review with no actionable findings. Production retains one sizing owner and unchanged SQLite writer/retained-task ownership.
Final repair head:
afb7ef6fbc37569873a143190d2b335ee3cfc790, tested tree9a6cfea3873d459aa6be48f91a2596a794f1b09f. On the isolated Linux rig,node scripts/run-oxlint.mjspassed the three changed TypeScript files (20.27 s);node scripts/run-tsgo.mjspassed core production types (76.24 s) and the canonical state/logging test-type group (66.21 s);node --import ./scripts/tsx.mjs scripts/check-export-name-collisions.mtspassed (41.65 s);node scripts/run-vitest.mjs test/scripts/eager-import-closure.test.ts test/scripts/pr-wrapper-source-closure.test.tspassed 20 cases (35.78 s wall). Changed-file formatting andgit diff --checkpassed. The actual reader regression command usednode scripts/run-vitest.mjswith the eight named avatar/read-worker/read-source/preparation files under two-CPU affinity; remote runtime proof retained no old-generation override.Final CI run
37774099261completed forafb7ef6fbc37569873a143190d2b335ee3cfc790. Every selected Node, type, lint, build, and guard job passed. Only UI E2E shards 3/7 and 4/7 failed, plus their aggregate gate. On unchanged mainb925148b83b7ebddb32e1dd68769d6588d16f800, the repository test CLI reproduced the exact same 14 failing cases and assertions, with 15 passes, acrosschat-flow.active-run-follow-ups.e2e.test.ts,chat-flow.stream-reconciliation.e2e.test.ts, andsession-placement.move.e2e.test.ts(Node 24.19, existing Chrome 153, isolated Linux rig, 126.26 s wall). The entire UI tree and UI test configuration are byte-identical between that main parent and tested mergec63a712a5629b92ee2b1f206e087b221bb4d42ea. These mocked-Gateway UI flows do not invoke the changed Node worker pools. Landing uses the authorized inherited-failure exception; CI is not described as green, and no workflow rerun or update-branch was requested.