Repository navigation
perf(infra): keep hot Workers warm and expose churn - #156387
Conversation
Retain one recently reused pool Worker for five idle minutes and extend the existing bounded Code Mode cache. Count per-script starts and confirmed exits through the existing resource registry and Prometheus heartbeat. Validated on Blacksmith Testbox: full changed checks, 153 focused tests, build and Telegram import profile. Intermittent owner rig reduces cron/Git starts by 80% and Code Mode starts by 90%. The requested 32-vCPU lease exposed 8 CPUs; allocator evidence remains exploratory and no service environment is changed.
|
🦞👀 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. |
Pressure tests must not assume the process-wide Worker lifecycle counters are empty after neighboring CI files retire Workers. Supply deterministic retained history at the existing sampler boundary and preserve exact emitted-event assertions. Reproduced the three original CI failures on Testbox. The correction passed three original-shard replays, 20 standalone runs, Worker/Prometheus siblings, focused typechecking and lint, and independent review. Production behavior is unchanged.
|
Codex review: needs maintainer review before merge. Reviewed September 23, 2026, 8:41 AM ET / 12:41 UTC (Revision 3). ClawSweeper reviewWhat this changesThe PR retains frequently reused Worker threads longer, adds per-script lifecycle counters to diagnostics and Prometheus, and repairs test cleanup. Merge readiness✅ Ready for maintainer review Keep open for normal merge review: current main does not contain the central improvement, the supplied runtime evidence is relevant, and this pass found no blocking defect. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw runs background tasks and Node Code Mode evaluations in Worker threads. The existing pool manages their reuse and retirement, while the resource registry feeds operator diagnostics and Prometheus. flowchart TD
A[Background tasks] --> B[Worker pool]
C[Code Mode evaluations] --> D[Single idle Worker cache]
B --> E[Reuse or retire Workers]
D --> E
E --> F[Resource registry]
F --> G[Diagnostics heartbeat]
G --> H[Prometheus counters]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +146, Tests +101, Docs +21. Total +268 across 27 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep adaptive retention and lifecycle accounting with their existing owners, using the established coordinated host/plugin release path. Do we have a high-confidence way to reproduce the issue? Not applicable as a broken-behavior report; the performance opportunity is supported by source and reported before/after production-owner measurements. Is this the best way to solve the issue? Yes. Extending the existing retirement owner and resource registry avoids competing lifecycle logic while preserving cleanup barriers. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 904f9c03a317. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
Remove the extra global database closer from the permission-root fixture. The shared Gateway session harness already drains admitted work and queued writes before scoped closure; the competing hook could revoke live reads ahead of that cleanup. CI reported four failures; the original Gateway shard and standalone file passed on Testbox, so the intermittent failure was not reproduced. The deletion preserves all four behavior tests and passed three 22-file shard replays, 20 standalone runs, focused typechecking and lint, and independent review. Production code is unchanged.
Integrate current main for the Worker churn candidate. Await the registered Telegram handler in the sticker ordering fixture and join deferred work before restoring runtime, removing an incidental webhook deadline that could leave work alive during teardown. Validated on Blacksmith Testbox: three original ordered Telegram shards, twenty standalone fixture runs, extension test types, targeted lint, and 106 focused Worker and metrics tests. Fresh independent review found no actionable issues.
What Problem This Solves
Intermittent tasks repeatedly recreate healthy Workers after the existing 30–60 second idle timeout, paying isolate startup costs and leaving resident memory behind after teardown. Existing metrics cannot distinguish which scripts are starting and exiting.
User Impact
Hot task pools retain one Worker for five minutes of inactivity after an idle-retired Worker is promptly needed again. Node Code Mode retains its existing one-worker cache for five minutes. Operators can graph
openclaw_worker_started_total{script}andopenclaw_worker_retired_total{script,reason}through the existing diagnostics heartbeat.Why This Change Was Made
The existing retirement owner now owns idle timers and the single warm slot. Other slots keep their ordinary timeout; native cleanup, cancellation, pressure retirement, and rotation retain their existing ownership barriers. Existing idle GC collects released payloads in place. Code Mode still checks the runtime entry and heap limit before reuse.
The existing Worker resource registry owns cumulative lifecycle counts, including bundled direct Worker constructors. Counts advance on successful creation and confirmed native exit, survive exporter restart, and use bounded labels. Eval/unknown Workers remain
other; nested Workers and V8-native threads remain outside the parent registry. Memory projection moves into a focused Prometheus module to keep the existing service below its growth ratchet.No new configuration, database changes, dependencies, or managed-service environment changes. Updating installs the new runtime behavior through the normal restart; no migration or operator-state mutation is needed.
Evidence
Real production-owner calls in source mode (Node/tsx), ten verified synthetic tasks at 70-second simulated idle intervals (630 seconds observed), with real Worker creation and native teardown:
cron-stream-matcher.worker.jsgit-operation.worker.jscode-mode-node.worker.jsThe original source fails both new warm-window regressions; the pool creates a third Worker and Code Mode creates a second pool. In-place GC proof releases a 138 MiB payload to a 7.4 MiB heap while reusing the Worker.
Allocator experiment and limits
Requested the largest advertised Blacksmith Linux class, 32 vCPUs, through a temporary proof-only workflow branch. The resulting guest exposes 8 online CPUs, so this does not fulfill ≥32-vCPU validation or prove production memory behavior. Node 24.19.0, glibc 2.39, 32 concurrent Workers, 1,000 identical tasks touching 8 MiB each:
MALLOC_ARENA_MAX=2The arena control reduces final residue 33.7%; reuse reduces it 19.9%. The churn proxy's post-100 slope is 102.63 KiB/task, versus 19.26 KiB/task with the arena control. A comparable retained-worker proxy slope is not interpretable: V8 heap capacity shrinks 992 MiB while RSS remains about 716.5 MiB, producing negative subtraction values and a false slope. Retained raw RSS grows only 0.152 MiB from tasks 400–1,000. These short exploratory results do not establish a many-core native-memory slope or allocator-contention tradeoff; consequently this PR does not set
MALLOC_ARENA_MAX. Live deployment/production attribution remains a follow-up.Validation
Provider:
blacksmith-testbox; profile:openclaw-check; lease:tbx_01m36makaczyy9pds4yt5t2pem; workflow run. One active remote command at a time, normal synchronization throughout. All test/typecheck/build work ran remotely.node scripts/check-changed.mjs --base HEAD -- <all 25 changed paths>: passed in 43m18s, including all 25 core-test typecheck graphs, core/extension production and test types, lint, documentation, SDK boundaries, dead exports, and import cycles.pnpm test <file> --maxWorkers=1for every changed test file, thennode scripts/run-vitest.mjsfor the five affected lifecycle/transport siblings: passed; 153 tests across 11 files. Final combined remote command: 59.2s. Original-source targeted runs failed both new regressions for the intended extra Worker/pool creation; candidate runs pass.pnpm buildfollowed byOPENCLAW_LOCAL_CHECK=0 node --import tsx scripts/profile-extension-memory.mts --extension telegram --skip-combined --concurrency 1: passed in 3m54s combined. All 95 plugin distributions built; bootstrap and 53 native control-plane module checks passed. Telegram isolated import exited cleanly, 160.09 MiB peak RSS (113.85 MiB above the profiler's empty-process baseline).git diff --check: passed. Net production growth: 146 lines; no test-only production seam.Measured single-worker test command cost (seconds, including setup):
src/infra/worker-task-pool.test.tssrc/infra/worker-cpu.test.tssrc/logging/diagnostic-memory.test.tssrc/agents/code-mode-node.lifecycle.test.tsextensions/diagnostics-prometheus/src/service.event-loop.test.tsextensions/telegram/src/telegram-ingress-worker.test.tsThe two added behavior regressions use a fake idle clock; the real-worker pool case took 45ms and the Code Mode lifecycle case 35ms. CI's build-artifacts job passed in 265s. Per-file CI wall times were unavailable from this run's artifacts; the file costs above are measured Testbox command walls. The initial logging failure log records 93ms summed test-body time for the 40 diagnostic-memory cases, excluding loading/hooks, within a 293s multi-group CI job. Crabbox reported an external runner-portal sync timeout after successful changed-check, final-test, and build commands; their underlying commands and reported run status succeeded.
CI fixture follow-up
The first CI head exposed an order-dependent test assumption in
diagnostic-memory.test.ts: standalone tests expected empty Worker history, while earlier files in the combined shard had already retired disk-budget and archive Workers. The original CI group manifest reproduced the same three assertions on freshblacksmith-testboxleasetbx_01m36sdpmhhkq8732caehpbvyy(run). Cumulative production counters are correct to retain that history. The pressure tests now supply a deterministic nonempty Worker-memory fixture and preserve exact event assertions; the real Worker lifecycle tests continue to cover accounting. Independent review of this test-only correction is clean.On the fresh lease,
node --import tsx scripts/ci-run-node-test-shard.mtswith the original compressed group manifest passed three complete replays (404.56s, 367.25s, 406.87s).pnpm test src/logging/diagnostic-memory.test.ts --maxWorkers=1passed 20 standalone runs, followed by Worker-accounting/Prometheus siblings, the state/logging test typecheck, and targeted lint. The complete correction-validation command passed in 25m36s; production code is unchanged. The repository bot separately reran the old CI head; that retry is not counted as repair evidence. These two task-owned Testbox leases were stopped after validation.The next CI head exposed two separate failures. The full-tree Knip scan used a merge ref predating the already-landed owner fix
54a9d03dcf0, which registers the real workflow/shell entrypoints for two scripts; no scan exception is added here. A fresh push refreshes that merge ref. Four permission-root Gateway tests also failed with revoked reads/closing database resources. Their original 22-file logical shard and standalone file both passed onblacksmith-testboxleasetbx_01m36wg944q2c3sy0nzwt5c1pt(run), so this timing-sensitive failure was not reproduced. Source inspection found a competing unscoped database-close hook that ran before the shared session harness drained work. Removing that redundant hook leaves the canonical scoped cleanup and all four behavior assertions intact. Independent review accepts the deletion; passing replays alone are not claimed as causal proof of the intermittent failure.The cleanup deletion passed three original 22-file Gateway-shard replays (233.78s, 231.71s, 284.13s), 20 standalone
pnpm test src/gateway/server.sessions.permission-root.test.ts --maxWorkers=1runs, the Gateway-server test typecheck, and targeted lint. Standalone wall time: median 15.345s, range 13.82–19.99s; the existing suite shares one real Gateway to verify persisted permission modes and admitted-work interruption. No new per-test boot or test case is added. The complete remote validation passed in 21m43s. The third lease was stopped after validation; production code remains unchanged by both CI fixture follow-ups.A later merge-ref CI run (
35851898578,checks-node-changed-extensions-bundle-12) exposed a newly landed Telegram sticker fixture using grammY's default 10-second webhook deadline around intentionally deferred model work. A webhook timeout rejects without cancelling or joining the handler, allowing it to outlive fixture teardown. The original ordered shard passed on leasetbx_01m3705656yvqb9ewg62ks5nsc(run); the case took 8.782s, so the CI timeout itself was not reproduced. The fixture now awaits the registeredbot.handleUpdatedirectly and joins its deferred handler before restoring runtime. All sticker cache, admission-order, supplemental-media, and delivery assertions remain; another case retains webhook serialization coverage. No timeout increase or production Telegram change.After integrating main at
af7420cc367, the complete candidate received a fresh scoped-clean independent review. On replacementblacksmith-testboxleasetbx_01m3719nzgamcn9pb3q34edejn(run),node --import tsx scripts/ci-run-node-test-shard.mtspassed three original eight-file shard replays in 275.97s, 247.15s, and 257.65s.pnpm test extensions/telegram/src/bot.create-telegram-bot.native-pipeline.test.ts --maxWorkers=1passed all 58 tests in 20 standalone runs (median wall 73.697s; range 65.447–101.017s). The extension-testrun-tsgo.mjsgraph, targetedrun-oxlint.mjs, and the six Worker/Code Mode/logging/Prometheus/Telegram-ingress files throughrun-vitest.mjsalso passed; the 106 focused tests took 43.50s. The complete remote validation returned exit 0 in 46m46s. The original three Worker runtime owners were unchanged by this main integration, so prior before/after benchmark evidence is retained.Two reused-lease sync attempts failed before tests at Blacksmith's two-minute sync deadline (its changed-file count unexpectedly grew from 984 to 16,477). Stopping that lease and warming the replacement restored normal synchronization; HEAD and the edited fixture's SHA-256 were checked before execution. The successful run reported only the known external runner-portal sync warning after command completion. Both Telegram leases have been stopped. All validation stayed remote.
Setup failures were diagnosed rather than counted as product failures: the transport checkout initially lacked
tsx(fixed with remote frozen install), has no cgroup-v2cpu.max, and lacksorigin/main(changed checks use the actual originalHEADbase plus exact changed paths). The initial benchmark fixture awaited an unrelated/unreferenced Worker exit; the corrected fixture uses the pool's resource-release boundary. The first changed gate identified line-cap growth; moving idle timing into its owner and extracting memory projection resolved it without an exception.Final published head
6ad602756aapassed CI run 35861313960. The repaired Telegram bundle passed in 509 CI seconds (whole multi-file job, including setup); the build, dependency scan, type, lint, and all test jobs passed. Squash auto-merge is enabled.