Skip to content

perf(diagnostics): attribute Worker heap usage by script - #154295

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-worker-heap-growth-20260919
Sep 21, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-worker-heap-growth-20260919

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Related: #153842

What Problem This Solves

Aggregate Worker heap totals cannot identify which Worker script is growing when Gateway memory pressure rises.

User Impact

Operators get the five largest fresh Worker heaps in the memory-pressure warning and a bounded-label openclaw_worker_heap_used_bytes{script} gauge. This is attribution only; it does not claim to fix heap growth.

Example warning fragment (synthetic byte counts):

workerHeaps=[{"script":"sqlite-store.worker.js","heapUsed":700,"heapTotal":1400},{"script":"sqlite-store.worker.js","heapUsed":600,"heapTotal":1200},{"script":"sqlite-store.worker.js","heapUsed":500,"heapTotal":1000},{"script":"sqlite-store.worker.js","heapUsed":400,"heapTotal":800},{"script":"sqlite-store.worker.js","heapUsed":300,"heapTotal":600}]

Example metric (sum of two fresh Workers running the same script):

# TYPE openclaw_worker_heap_used_bytes gauge
openclaw_worker_heap_used_bytes{script="sqlite-store.worker.js"} 250

Why This Change Was Made

The existing Worker resource registry prepares a fixed allowlisted basename once at construction. Unknown, eval, and directly constructed Workers use other; installation paths and eval sources are never retained. Archive and lease-heartbeat constructors now use that same owner. The existing 30-second heartbeat, single outstanding native request, 60-second sample expiry, and native-exit cleanup remain in charge. Metrics aggregate fresh samples by script and remove series absent from the next sample. No new timer or cache lifecycle.

The existing metric store moves into a sibling module to satisfy the service file's line-cap ratchet; the new clearing operation remains part of that store. Net production growth: 81 lines. Probe scripts remain local and are excluded from this PR.

Evidence

Tiny single-process benchmark of the original and candidate sampler/exporter function bodies, using 50 cached Worker samples and 2,000 unrelated gauges. Five alternating rounds, median time per call:

Operation Before After Added cost
Cached Worker sampling 1.657 µs 2.020 µs 0.362 µs
Memory-event metric update 2.094 µs 11.773 µs 9.680 µs

This measures attribution overhead, excludes unchanged native heap interrupts and event dispatch, and ran in under one second on a loaded host. No end-to-end speedup is claimed.

Validation uses provider blacksmith-testbox, profile openclaw-check, lease tbx_01m30rwcft36t12jtfbb7wc97x, Testbox run. The first focused run stopped before executing tests because the synced checkout lacked dependencies; pnpm install --frozen-lockfile on that lease repaired hydration. The first unpinned changed-file check caught the service line-cap growth and also included changes from newer main; the extraction resolves the former, and subsequent checks pin the lane's original base 647e62369ffb4b684be2b8adadce825b21b042c2.

The pinned broad check passed core, all 24 core-test, extension, and extension-test typechecks plus boundary/dead-export guards, then found one test-only property-shorthand lint error. After fixing that line, focused check-changed runs for the changed Worker test and the exporter/docs completed successfully on replacement lease tbx_01m30v43kcda3kyp8jaxp8ke7s (run). Prior successful typecheck evidence was reused for unchanged inputs. Both leases are stopped.

Provider / lease Command Result
blacksmith-testbox / first lease node scripts/run-vitest.mjs src/infra/worker-cpu.test.ts src/logging/diagnostic-memory.test.ts extensions/diagnostics-prometheus/src/service.event-loop.test.ts --maxWorkers=1 50 passed; 18.78 s runner wall.
blacksmith-testbox / first lease node scripts/check-changed.mjs --base 647e62369ffb4b684be2b8adadce825b21b042c2 All typechecks passed; test-only shorthand lint failure fixed below.
blacksmith-testbox / replacement lease node scripts/check-changed.mjs --base 647e62369ffb4b684be2b8adadce825b21b042c2 -- src/infra/worker-cpu.test.ts Passed, including affected test graph and lint.
blacksmith-testbox / replacement lease Same pinned check-changed command with the three exporter files and docs/gateway/prometheus.md Passed; both focused check commands completed in 10 m 43 s.
blacksmith-testbox / replacement lease Original logging/exporter production files plus run-vitest filtered to the new output assertions Both failed for the intended missing workerHeaps / openclaw_worker_heap_used_bytes output. Candidate files restored immediately afterward.
blacksmith-testbox / replacement lease Final node scripts/run-vitest.mjs command below 78 passed across six files, 56.24 s runner wall; baseline comparisons plus final tests took 80.38 s.
node scripts/run-vitest.mjs \
  src/infra/worker-cpu.test.ts \
  src/logging/diagnostic-memory.test.ts \
  extensions/diagnostics-prometheus/src/service.event-loop.test.ts \
  src/state/openclaw-state-lease-heartbeat.startup.test.ts \
  src/state/openclaw-state-lease-heartbeat.source-cwd.test.ts \
  src/config/sessions/session-accessor.sqlite-archive.worker.test.ts \
  --maxWorkers=1

Changed test-file wall times on the final run: Worker lifecycle 2.71 s, diagnostic memory 4.59 s, Prometheus metrics 2.59 s (including startup/transformation; each is under 0.5 s of test execution). Tests cover native-exit cleanup, stale samples, one outstanding heap request during a stall, source/bundled/unknown labels, top-five log records including total heap, same-script summation, trust filtering, and absent-series removal. PR CI is separate and pending at publication.

Recovery notes: two post-fix native sync attempts timed out during the provider's full-checksum fallback, before tests ran; the old lease was retired and targeted sync on the replacement succeeded. A compound login-shell command initially ran outside the synced checkout and failed to resolve the pinned base; a non-login shell verified the exact candidate base and ran all subsequent compound proof commands. No failed test was rerun without identifying its cause.

Independent Codex autoreview: no actionable P0–P2 findings. git diff --check passes. No production deployment was performed. The original sustained heap growth remains unproven by synthetic workloads; nested Workers and direct plugin Workers cannot be individually attributed beyond the documented registry coverage.

@clawsweeper

clawsweeper Bot commented Sep 21, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime extensions: diagnostics-prometheus size: L maintainer Maintainer-authored PR labels Sep 21, 2026
@steipete
steipete marked this pull request as ready for review September 21, 2026 02:21
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 21, 2026
@clawsweeper

clawsweeper Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 20, 2026, 10:31 PM ET / September 21, 2026, 02:31 UTC.

ClawSweeper review

What this changes

Adds Worker script names to memory-pressure warnings and a per-script Prometheus heap gauge, using the existing sampling registry.

Merge readiness

✅ Ready for maintainer review

Keep open: this is a useful, bounded follow-up to aggregate Worker memory accounting, and current main does not provide the script attribution. No actionable correctness or security defect was found.

Priority: P2
Reviewed head: 1d132fce72b2dbc39b497f494f759284286199aa

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with meaningful regression coverage, explicit measurement limits, and no blocking findings.
Proof confidence 🌊 off-meta tidepool Not applicable: The maintainer-author exemption applies. Reported tests exercise the registry, pressure logger, and exporter with native Workers and controlled samples; synthetic examples and function-body benchmarks do not establish a live Gateway attribution run.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-author exemption applies. Reported tests exercise the registry, pressure logger, and exporter with native Workers and controlled samples; synthetic examples and function-body benchmarks do not establish a live Gateway attribution run.
Evidence reviewed 9 items Introduced change: Reviewed the pinned merge-base-to-head diff. Attribution extends the existing registry; the archive and lease-heartbeat constructors retain their options and lifecycle handling.
Sampling and privacy boundaries: Script labels come from a fixed basename allowlist; unknown names, eval sources, and direct Workers use other. Sampling retains the existing single outstanding request, 60-second expiry, and native-exit cleanup.
Exporter behavior: The existing trusted-event filter precedes aggregation. Each accepted memory sample replaces the per-script gauge series; the extracted store preserves its existing series cap, and scrape authorization remains unchanged.
Findings None None.
Security None None.

How this fits together

The Gateway samples background Worker memory through its diagnostics heartbeat. Those samples feed operator warnings and the Prometheus plugin’s authenticated metrics endpoint.

flowchart TD
  A[Background Workers] --> B[Worker resource registry]
  B --> C[Fresh heap samples with bounded script names]
  D[Diagnostics heartbeat] --> C
  C --> E[Memory diagnostic event]
  E --> F[Top five heaps in pressure warnings]
  E --> G[Per-script Prometheus gauge]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +81, Tests +94, Docs +8. Total +183 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 7 239 158 +81
Tests 3 113 19 +94
Docs 1 9 1 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 361 178 +183

Review metrics

Metric Value Why it matters
Diagnostic surface 1 new gauge family; 1 bounded script label; 5 Worker records per warning Provides attribution without adding operator settings or another sampling timer.
Production versus test growth Production net +81 lines; tests net +94 lines Production growth is explained by attribution and gauge replacement, with the existing metric store extracted to satisfy the file-size limit.

Technical review

Best possible solution:

Keep script attribution with the existing Worker resource owner and derive bounded warnings and metrics from its fresh samples.

Do we have a high-confidence way to reproduce the issue?

Not applicable: this adds diagnostic attribution rather than repairing a demonstrated heap leak; current-main source confirms the attribution gap.

Is this the best way to solve the issue?

Yes: extending the existing sampling owner and exporter avoids a competing registry or timer while preserving existing aggregate metrics.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 20db76a79212.

Labels

Label changes:

  • add P2: This is a bounded operator-diagnostics improvement, without evidence of an urgent runtime failure.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-author exemption applies. Reported tests exercise the registry, pressure logger, and exporter with native Workers and controlled samples; synthetic examples and function-body benchmarks do not establish a live Gateway attribution run.

Label justifications:

  • P2: This is a bounded operator-diagnostics improvement, without evidence of an urgent runtime failure.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-author exemption applies. Reported tests exercise the registry, pressure logger, and exporter with native Workers and controlled samples; synthetic examples and function-body benchmarks do not establish a live Gateway attribution run.

Evidence

What I checked:

  • Introduced change: Reviewed the pinned merge-base-to-head diff. Attribution extends the existing registry; the archive and lease-heartbeat constructors retain their options and lifecycle handling. (src/infra/worker-cpu.ts:51, 1d132fce72b2)
  • Sampling and privacy boundaries: Script labels come from a fixed basename allowlist; unknown names, eval sources, and direct Workers use other. Sampling retains the existing single outstanding request, 60-second expiry, and native-exit cleanup. (src/infra/worker-cpu.ts:16, 1d132fce72b2)
  • Exporter behavior: The existing trusted-event filter precedes aggregation. Each accepted memory sample replaces the per-script gauge series; the extracted store preserves its existing series cap, and scrape authorization remains unchanged. (extensions/diagnostics-prometheus/src/service.ts:752, 1d132fce72b2)
  • Still necessary on current main: The fetched main registry returns aggregate Worker counts and heap totals without script attribution; its exporter likewise lacks the new per-script gauge. (src/infra/worker-cpu.ts:85, 20db76a79212)
  • Related merged foundation: GitHub verifies perf(diagnostics): account for worker memory and reduce isolate churn #153842 as merged at acbe50a. Its reviewed body and commit patch establish aggregate memory sampling, rather than the script attribution proposed here. (src/infra/worker-cpu.ts, acbe50ab5685)
  • Feature-history routing: Current-main history shows prior Worker memory accounting and several diagnostics improvements by Peter Steinberger; GitHub commit metadata maps the accounting commit to steipete. Local parent-dependent blame inspection was unavailable, so the history pointer remains subject to host verification. (src/infra/worker-cpu.ts:112, acbe50ab5685)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; 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.

@steipete
steipete merged commit eeba8b6 into main Sep 21, 2026
284 checks passed
@steipete
steipete deleted the steipete/perf-micro-worker-heap-growth-20260919 branch September 21, 2026 03:05
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: diagnostics-prometheus gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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