Skip to content

perf(infra): keep hot Workers warm and expose churn - #156387

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-worker-churn-keep-warm-20260919
Sep 23, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-worker-churn-keep-warm-20260919

Conversation

@steipete

@steipete steipete commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

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} and openclaw_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:

Script Starts before → after Starts/min before → after Task-run wall before → after
cron-stream-matcher.worker.js 10 → 2 0.952 → 0.190 485 → 111 ms
git-operation.worker.js 10 → 2 0.952 → 0.190 3,076 → 824 ms
code-mode-node.worker.js 10 → 1 0.952 → 0.095 858 → 187 ms

The 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:

Fresh process Worker starts Wall RSS minus aggregate heapTotal increase after all Workers exit
Create/terminate each task 1,000 8.11 s +639.59 MiB
Same churn, MALLOC_ARENA_MAX=2 1,000 7.54 s +423.86 MiB
Reuse 32 Workers 32 3.08 s +512.05 MiB

The 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=1 for every changed test file, then node scripts/run-vitest.mjs for 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.
  • The production-owner before/after benchmark command passed, including synthetic output assertions and native-exit cleanup for all three scripts. The allocator benchmark completed all three fresh-process cases with identical checksums.
  • pnpm build followed by OPENCLAW_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).
  • Independent Codex review: scoped-clean, no actionable P0–P2 findings. git diff --check: passed. Net production growth: 146 lines; no test-only production seam.

Measured single-worker test command cost (seconds, including setup):

Changed file Wall
src/infra/worker-task-pool.test.ts 20.33
src/infra/worker-cpu.test.ts 7.48
src/logging/diagnostic-memory.test.ts 6.58
src/agents/code-mode-node.lifecycle.test.ts 5.21
extensions/diagnostics-prometheus/src/service.event-loop.test.ts 1.81
extensions/telegram/src/telegram-ingress-worker.test.ts 5.18

The 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 fresh blacksmith-testbox lease tbx_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.mts with the original compressed group manifest passed three complete replays (404.56s, 367.25s, 406.87s). pnpm test src/logging/diagnostic-memory.test.ts --maxWorkers=1 passed 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 on blacksmith-testbox lease tbx_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=1 runs, 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 lease tbx_01m3705656yvqb9ewg62ks5nsc (run); the case took 8.782s, so the CI timeout itself was not reproduced. The fixture now awaits the registered bot.handleUpdate directly 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 replacement blacksmith-testbox lease tbx_01m3719nzgamcn9pb3q34edejn (run), node --import tsx scripts/ci-run-node-test-shard.mts passed 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=1 passed all 58 tests in 20 standalone runs (median wall 73.697s; range 65.447–101.017s). The extension-test run-tsgo.mjs graph, targeted run-oxlint.mjs, and the six Worker/Code Mode/logging/Prometheus/Telegram-ingress files through run-vitest.mjs also 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-v2 cpu.max, and lacks origin/main (changed checks use the actual original HEAD base 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 6ad602756aa passed 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.

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.
@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete enabled auto-merge (squash) September 23, 2026 09:10
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: discord Channel integration: discord channel: telegram Channel integration: telegram gateway Gateway runtime cli CLI command changes agents Agent runtime and tooling extensions: openai extensions: diagnostics-prometheus size: M labels Sep 23, 2026
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.
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 23, 2026
@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 23, 2026, 8:41 AM ET / 12:41 UTC (Revision 3).

ClawSweeper review

What this changes

The 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
Reviewed head: 6ad602756aae3540e84252bc0b2a5e211b4ee28e

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with relevant real-Worker evidence, documented validation, and no actionable blocking findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The verified complete body reports real Node Worker runs through the cron, Git, and Code Mode production owners, with simulated idle intervals, checked task results, fewer starts, and native teardown. These owners are unchanged since the preceding review. Allocator results remain explicitly exploratory; no stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The verified complete body reports real Node Worker runs through the cron, Git, and Code Mode production owners, with simulated idle intervals, checked task results, fewer starts, and native teardown. These owners are unchanged since the preceding review. Allocator results remain explicitly exploratory; no stored-data contract changes.
Evidence reviewed 9 items Pinned change ownership: Reviewed the merge-base-to-head delta, including the original behavior surrounding the introduced hunks. The recorded test merge was not used to infer removal of current-main behavior.
Bounded retention preserves cleanup ownership: The retirement owner retains at most one warm slot, preserves disabled idle retirement, and keeps native-settlement, pressure, rotation, cancellation, and shutdown paths. Code Mode retains its existing single-entry cache and runtime-entry/heap-limit checks.
Complete proof body inspected: Fetched the omitted body tail and verified that the complete body matches captured SHA-256 44dfb04522cd6ac8feb2c51fe4de842c430f043885b8e18c8c203e58fde294ce. Reported production-owner runs used real Node Workers with simulated idle intervals: cron and Git starts fell from 10 to 2, and Code Mode starts from 10 to 1, with output assertions and native teardown. The body explicitly limits allocator conclusions and records fixture failures and subsequent validation.
Findings None None.
Security None None.

How this fits together

OpenClaw 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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +146, Tests +101, Docs +21. Total +268 across 27 files.

View PR surface stats
Area Files Added Removed Net
Source 16 243 97 +146
Tests 8 125 24 +101
Docs 3 24 3 +21
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 27 392 124 +268

Review metrics

Metric Value Why it matters
Production versus test growth production +146 net lines; tests +101 net lines Production growth implements bounded retention and lifecycle accounting within existing owners.
Reported Worker startup reduction 80% for cron/Git; 90% for Code Mode Real production-owner runs demonstrate reduced startup churn over ten intermittent tasks per owner.

Technical review

Best 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.

Labels

Label changes:

  • remove merge-risk: 🚨 compatibility: Current PR review selected no merge-risk labels.

Label justifications:

  • P2: This is a bounded runtime efficiency and operator-observability improvement without an established urgent user-facing outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The verified complete body reports real Node Worker runs through the cron, Git, and Code Mode production owners, with simulated idle intervals, checked task results, fewer starts, and native teardown. These owners are unchanged since the preceding review. Allocator results remain explicitly exploratory; no stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The verified complete body reports real Node Worker runs through the cron, Git, and Code Mode production owners, with simulated idle intervals, checked task results, fewer starts, and native teardown. These owners are unchanged since the preceding review. Allocator results remain explicitly exploratory; no stored-data contract changes.

Evidence

What I checked:

  • Pinned change ownership: Reviewed the merge-base-to-head delta, including the original behavior surrounding the introduced hunks. The recorded test merge was not used to infer removal of current-main behavior. (6ad602756aae)
  • Bounded retention preserves cleanup ownership: The retirement owner retains at most one warm slot, preserves disabled idle retirement, and keeps native-settlement, pressure, rotation, cancellation, and shutdown paths. Code Mode retains its existing single-entry cache and runtime-entry/heap-limit checks. (src/infra/worker-task-pool-retirement.ts:134, 6ad602756aae)
  • Complete proof body inspected: Fetched the omitted body tail and verified that the complete body matches captured SHA-256 44dfb04522cd6ac8feb2c51fe4de842c430f043885b8e18c8c203e58fde294ce. Reported production-owner runs used real Node Workers with simulated idle intervals: cron and Git starts fell from 10 to 2, and Code Mode starts from 10 to 1, with output assertions and native teardown. The body explicitly limits allocator conclusions and records fixture failures and subsequent validation. (6ad602756aae)
  • Re-review continuity: The pool core, retirement owner, resource registry, and Node Code Mode owner are unchanged from the preceding reviewed head. Prior findings were empty; the new Telegram fixture change joins deferred handler work before restoring runtime. (extensions/telegram/src/bot.create-telegram-bot.native-pipeline.test.ts:965, 6ad602756aae)
  • Current-main necessity: Fetched main retains the previous retirement implementation and 60-second Code Mode cache. The merged memory-accounting work addresses a different churn source and does not supersede this change. (src/infra/worker-task-pool-retirement.ts:19, 904f9c03a317)
  • SDK and release compatibility boundary: The added helper uses the existing private-local process-runtime facade and removes no export. The latest release lacks this helper. Official-plugin release preparation synchronizes plugin API and peer-version floors, and plugin update selection checks that API range; the PR reports successful plugin builds and the Telegram import profile. This supports normal coordinated release handling rather than a new public API decision. (scripts/sync-plugin-versions.ts:165, 6ad602756aae)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-09-23T10:17:51.087Z sha 2fe9d9e :: needs maintainer review before merge. :: none
  • reviewed 2026-09-23T11:07:37.569Z sha 3688540 :: needs maintainer review before merge. :: none

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.
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 23, 2026
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.
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 23, 2026
@steipete
steipete merged commit d61bf61 into main Sep 23, 2026
214 of 215 checks passed
@steipete
steipete deleted the steipete/perf-micro-worker-churn-keep-warm-20260919 branch September 23, 2026 12:53
@roboclaw-bot roboclaw-bot mentioned this pull request Sep 24, 2026
2 of 8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling channel: discord Channel integration: discord channel: telegram Channel integration: telegram cli CLI command changes docs Improvements or additions to documentation extensions: diagnostics-prometheus extensions: openai gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant