Skip to content

perf(infra): collect and retire idle worker heaps - #154408

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

steipete merged 1 commit into
mainfrom
steipete/perf-micro-worker-idle-gc-20260919

Conversation

@steipete

@steipete steipete commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Persistent database workers can retain garbage from completed large operations during their 30-minute reuse window. This raises process memory while the workers are idle.

Related: #153601, #154295.

User Impact

Idle workers release transient heap while remaining reusable. Critical memory pressure retires idle workers through their existing cleanup owners. Busy tasks, accepted replies, resource cleanup, and database write settlement keep their existing ownership guarantees.

SQLite broker, shared-state reader, history/usage, transcript read/export/reconciliation, archive/cold-storage/reclamation, and canonical-validation workers request 512 MiB old-generation limits. An explicit process-wide --max-old-space-size overrides the effective V8 limit even though worker.resourceLimits still reports 512. Native and external allocations are outside that limit. There are no configuration, schema, stored-data retention, or update-procedure changes.

Why This Change Was Made

Completion hooks defer major collection until the operation releases its payload stack, and collect only after used heap grows by 32 MiB. A successor cancels scheduled collection. One worker-owned inspector session performs collection without changing process-global V8 flags; it remains attached until worker teardown. Generation and idle state handle operations that begin or finish while collection is pending. Buffered write-admission replies are filtered before cancellation, so they cannot cancel collection for an operation that already finished.

Critical-pressure notifications reach cleanup owners independently of diagnostic event recording and log throttling. Custom history/reclamation/database custody stays with its existing retirement owner. The generic pool retires only idle slots whose retirement it already owns.

The change adds 186 net production lines. Existing state-operation adapters moved unchanged to a sibling module to preserve line caps. The materialized PR-wrapper inventory includes both new runtime modules, and the V8-specific regression stays on Node through the existing CI runtime partition.

Evidence

Current head: ea738de9893c98dbc244c3d7ca0e0505e15fb1f8, a single commit with the original subject. The final rebase preserves byte-identical contents for all 28 files in this PR. Fresh full-candidate and focused follow-up Codex reviews found no actionable P0-P2 findings. Exact-head hosted CI passed, including the required openclaw/ci-gate.

The native regression exercises the real task-pool server and preserves the worker thread and V8 compile-cache identity:

Measurement Bytes
Warm worker heap 10,185,256
Heap after a 128 MiB payload 144,517,976
Idle heap after collection 7,732,696

On Testbox run 35565808025, the memory regression passed through the actual CI entry point with the Bun-compatible policy selecting Node. The following runtime-partition, eager-import, wrapper-source, and unchanged native compile-cache suites passed 125 tests in 33.91 s. Core typechecking and targeted core/script/test lint passed. The memory case took 497 ms, with 14.71 s cold file wall including worker compilation. The runtime-partition file's standalone regression-cost measurement was 3.82 s file / 5.12 s wrapper wall.

On Testbox run 35567975516, the admission-reply regression failed before the ordering repair, then passed with native reclamation and heap siblings: 4 tests in 19.74 s. The port-loop regression measured 4 ms test / 363 ms file / 1.17 s wrapper wall. It uses a real MessageChannel with synthetic database boundaries, no process boots, polling, or sleeps.

CI exposed a test cleanup typing error and a type-graph root budget overflow. Run 35569653790 proved both on the candidate while pure main beaf348df2306d9199bd2419e6f003c4892cd890 passed. The iterator cleanup now respects its optional return method. The earlier config/CLI typecheck excluded sessions; the correct graph was then checked. Run 35570995203 passed all 24 graph-ownership tests in 17.31 s, both affected canonical type graphs, and the docs audit (14,258 links, zero broken links). Main independently landed the same graph rebalance in f6f59497b50 (#154497); the duplicate configuration/docs changes were removed from this PR during rebase.

CI repair history and limitations

  • Planner issue CI preflight fails on multiple PRs: split timing generation repeats files for core-runtime-infra-storage-state #148443 initially blocked preflight and the required openclaw/ci-gate. Main repair f76d38a4ac5e is incorporated. Planning passed on pure main and the candidate, producing 68 compact shards.
  • The first refreshed CI run exposed a process-global --expose-gc leak, missing wrapper inventory entries, and the V8 test being routed to Bun. Pure-main comparisons and failing regressions confirmed these defects before repair. Existing exact compile-cache-directory assertions remain intact.
  • Head 2d7254b8fe57038c68483848b3f64f2fde86674c completed hosted CI green, ignoring superseded rollup entries. Subsequent heads add the admission-reply regression and its test-only type cleanup.
  • A separate Crabbox staging process-settlement timeout did not reproduce on pure main, in its original compact group or alone. The group ran 1,139 passing tests including staging, but a later suite could not resolve a package-local Markdown dependency in the temporary checkout. The isolated staging case passed in 2.694 s. This does not prove that the timeout is fixed; no unrelated staging changes are included.
  • Remote setup needed a full fetch SHA, frozen dependency restoration, and replacement leases after sync timeouts. All six landing-owned Testbox leases are stopped. No test suites, typechecks, or builds ran on the saturated Mac.

Maintainer decision: Retain the requested 512 MiB limits alongside idle GC and critical-pressure retirement. The caps affect active-operation capacity as well as idle heaps. Large live working sets and a post-deployment RSS curve remain unvalidated; the synthetic garbage proof does not establish those properties. No live Gateway or stored user data was modified.

@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 size: M maintainer Maintainer-authored PR labels Sep 21, 2026
@steipete
steipete marked this pull request as ready for review September 21, 2026 04:39
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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 changes before merge. Reviewed September 21, 2026, 3:57 AM ET / 07:57 UTC (Revision 8).

ClawSweeper review

What this changes

The PR collects unused worker heap after completed operations, retires idle workers under critical memory pressure, and requests 512 MiB database-worker heap limits.

Merge readiness

⛔ Needs changes before merge - 2 items remain

The work remains useful and is absent from current main. One previously reported P3 documentation error remains; no additional blocking runtime defect was found.

Priority: P2
Reviewed head: ea738de9893c98dbc244c3d7ca0e0505e15fb1f8

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, well-supported runtime work with one small, previously identified documentation correction remaining.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The recorded Node native-worker run exercises the production task server and idle-GC owner, showing a completed 128 MiB payload reclaimed while the same worker remains reusable. It supports focused heap reclamation, with live capacity and deployed RSS limitations explicitly accepted.
Patch quality 🐚 platinum hermit (4/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The recorded Node native-worker run exercises the production task server and idle-GC owner, showing a completed 128 MiB payload reclaimed while the same worker remains reusable. It supports focused heap reclamation, with live capacity and deployed RSS limitations explicitly accepted.
Evidence reviewed 9 items Pinned introduction and merge ownership: Reviewed the merge-base-to-head introduced diff. The recorded test merge has the pinned base followed by the exact PR head as parents; its resulting delta contains the same intended paths, rather than the unrelated endpoint drift.
Existing lifecycle owners remain responsible: Idle retirement excludes occupied slots, pending resource closures, and failed retirements. Existing retirement still joins native settlement and worker exit before releasing resources; custom history and reclamation owners retain their own cleanup paths.
Prior admission-reply finding resolved: Buffered admission replies are skipped before cancelWorkerIdleGc runs. The added MessageChannel regression checks that completed-operation collection remains scheduled and a successor request cancels it.
Findings 1 actionable finding [P3] [P3] State that pressure retirement requires enabled diagnostics
Security None None.

How this fits together

OpenClaw runs database and transcript operations in reusable workers. Completion hooks reclaim garbage, while diagnostic memory samples ask existing lifecycle owners to retire idle workers without interrupting active work.

flowchart TD
  A[Database and transcript requests] --> B[Reusable workers]
  B --> C[Operation completes]
  C --> D[Deferred idle garbage collection]
  E[Enabled diagnostics heartbeat] --> F[Critical memory pressure]
  F --> G[Existing cleanup owners]
  G --> H[Retire idle workers]
  C --> A
Loading

Before merge

  • [P3] State that pressure retirement requires enabled diagnostics (P3) - The paragraph is under Disable diagnostics, but diagnostics.enabled=false stops the heartbeat in configureDiagnostics(), and startDiagnosticHeartbeat() also returns early. That heartbeat owns the production call to the new pressure publisher, so automatic pressure retirement does not run in this configuration. Clarify that retirement bypasses sample-recording suppression and log throttling while diagnostics remain enabled; idle GC remains independent. This carries forward the previous review's finding on the same head.
  • Complete next step (P2) - Correct the diagnostics documentation to explain that automatic critical-pressure retirement requires diagnostics to remain enabled.

Findings

  • [P3] [P3] State that pressure retirement requires enabled diagnostics — docs/gateway/diagnostics.md:346-348
Agent review details

Security

None.

PR surface

Source +186, Tests +329, Docs +10, Other +4. Total +529 across 28 files.

View PR surface stats
Area Files Added Removed Net
Source 18 224 38 +186
Tests 7 331 2 +329
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 2 4 0 +4
Total 28 569 40 +529

Review metrics

Metric Value Why it matters
Worker heap budget 512 MiB requested old-generation limit This also constrains active workloads; the captured maintainer decision accepts that tradeoff and documents process-wide overrides.
Production versus test growth Production +186 net lines; tests and test support +329 Production growth is justified by shared idle collection and integration with existing cleanup owners.

Technical review

Best possible solution:

Keep reclamation within existing worker lifecycle owners and clearly distinguish independent idle GC from diagnostics-driven pressure retirement.

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

Yes for the remaining documentation defect: disabling diagnostics stops the only production heartbeat that publishes memory pressure. This is source-proven; no runtime reproduction was executed during review.

Is this the best way to solve the issue?

Yes, the runtime approach reuses existing cleanup ownership and has focused native-worker evidence; the remaining correction should change documentation rather than introduce another pressure sampler.

Full review comments:

  • [P3] [P3] State that pressure retirement requires enabled diagnostics — docs/gateway/diagnostics.md:346-348
    The paragraph is under Disable diagnostics, but diagnostics.enabled=false stops the heartbeat in configureDiagnostics(), and startDiagnosticHeartbeat() also returns early. That heartbeat owns the production call to the new pressure publisher, so automatic pressure retirement does not run in this configuration. Clarify that retirement bypasses sample-recording suppression and log throttling while diagnostics remain enabled; idle GC remains independent. This carries forward the previous review's finding on the same head.
    Confidence: 0.99

Overall correctness: patch is correct
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 11263ceb18ca.

Labels

Label justifications:

  • P2: This is a bounded worker-memory improvement without evidence of an urgent user-facing outage.
  • merge-risk: 🚨 compatibility: The requested 512 MiB worker limits change capacity for existing large workloads; this specific tradeoff is explicitly accepted.
  • merge-risk: 🚨 availability: Large active heaps can exhaust the new limits; the maintainer expressly retained them despite unvalidated live working-set capacity.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster 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 recorded Node native-worker run exercises the production task server and idle-GC owner, showing a completed 128 MiB payload reclaimed while the same worker remains reusable. It supports focused heap reclamation, with live capacity and deployed RSS limitations explicitly accepted.
  • proof: sufficient: Contributor real behavior proof is sufficient. The recorded Node native-worker run exercises the production task server and idle-GC owner, showing a completed 128 MiB payload reclaimed while the same worker remains reusable. It supports focused heap reclamation, with live capacity and deployed RSS limitations explicitly accepted.

Evidence

Acceptance criteria:

  • [P1] pnpm docs:check-links.
  • [P1] git diff --check.

What I checked:

  • Pinned introduction and merge ownership: Reviewed the merge-base-to-head introduced diff. The recorded test merge has the pinned base followed by the exact PR head as parents; its resulting delta contains the same intended paths, rather than the unrelated endpoint drift. (ea738de9893c)
  • Existing lifecycle owners remain responsible: Idle retirement excludes occupied slots, pending resource closures, and failed retirements. Existing retirement still joins native settlement and worker exit before releasing resources; custom history and reclamation owners retain their own cleanup paths. (src/infra/worker-task-pool-retirement.ts:109, ea738de9893c)
  • Prior admission-reply finding resolved: Buffered admission replies are skipped before cancelWorkerIdleGc runs. The added MessageChannel regression checks that completed-operation collection remains scheduled and a successor request cancels it. (src/config/sessions/session-accessor.sqlite-mutation-worker.runtime.ts:274, ea738de9893c)
  • Documentation finding remains: The added paragraph under Disable diagnostics promises pressure retirement when diagnostic collection is disabled. Gateway configureDiagnostics stops the heartbeat when diagnostics.enabled is false, and startDiagnosticHeartbeat independently rejects disabled diagnostics. That heartbeat is the production memory-sample caller. The previous completed review inspected this same head, so its documentation finding remains outstanding. Public docs: docs/gateway/diagnostics.md. (docs/gateway/diagnostics.md:346, ea738de9893c)
  • Accepted capacity tradeoff: The captured PR body records the maintainer decision to retain the requested 512 MiB limits, explicitly accepting their effect on active-operation capacity while large live working sets and deployed RSS remain unvalidated. This covers the current diff; those limitations do not require renewed acceptance. (src/infra/sqlite-worker-broker.ts:425, ea738de9893c)
  • Native worker behavior evidence: The captured body reports a real Node worker executing the production task server: heap rose from 10,185,256 to 144,517,976 bytes after a 128 MiB payload, then fell to 7,732,696 bytes while preserving worker identity. The inspected fixture exercises that boundary and checks unchanged V8 compile-cache identity. This establishes focused heap reclamation, not deployed Gateway sizing. (src/infra/worker-task-pool.memory.test.ts:7, ea738de9893c)

Likely related people:

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

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Correct the diagnostics paragraph to state the enabled-heartbeat prerequisite while preserving the independent idle-GC guarantee.

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 (7 earlier review cycles)
  • reviewed 2026-09-21T04:47:33.817Z sha b5b69fdef2f027daeb1e2aa560dece5a7046f0dc :: blocked before merge. :: none
  • reviewed 2026-09-21T05:03:13.228Z sha b5b69fdef2f027daeb1e2aa560dece5a7046f0dc :: blocked before merge. :: [P2] [P2] Ignore admission replies before cancelling idle GC
  • reviewed 2026-09-21T05:28:08.626Z sha 34935a69ffea25cee9ccb05c6dda98aa6251e874 :: needs changes before merge. :: [P2] [P2] Filter admission replies before cancelling idle GC
  • reviewed 2026-09-21T06:09:44.368Z sha 2d7254b8fe57038c68483848b3f64f2fde86674c :: needs changes before merge. :: [P2] [P2] Filter admission replies before cancelling idle GC
  • reviewed 2026-09-21T06:45:02.309Z sha f627ead :: needs maintainer review before merge. :: none
  • reviewed 2026-09-21T07:16:13.884Z sha 65635a767be1df91bf8a59d56eba03c47b58de9b :: needs changes before merge. :: none
  • reviewed 2026-09-21T07:32:25.379Z sha ea738de :: needs changes before merge. :: [P3] [P3] State that pressure retirement requires enabled diagnostics

@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 21, 2026
@steipete
steipete force-pushed the steipete/perf-micro-worker-idle-gc-20260919 branch from b5b69fd to 34935a6 Compare September 21, 2026 05:18
@steipete

steipete commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Catalog-worker retention coordination update: the final fix removes two independent retaining paths: the inline generation-release closure chained every predecessor, and the plugin cache retained successfully disposed instances. The cached registry loader is preserved; terminal successful physical disposal now releases each instance from its birth inventories. Active, adopted, draining, and failed instances retain custody.

The real-worker synthetic benchmark now passes 1,000 preparations across four plugin-config revisions with one retained callback after settlement, versus 1,000 before. Post-GC worker heap is 87.3 MB versus 178.4 MB. All 235 focused worker/plugin tests pass, including one shared runtime-source graph across agent publications.

Both catalog-worker host paths request 512 MiB old-generation limits. Generic idle GC, pressure retirement, and task-pool lifecycle files remain untouched. The process-wide heap-flag override and large-working-set limitations will remain documented. Final changed checks and build are running before PR publication.

Published as #154568. The exact-head CI workflow passed, as did all selected Testbox checks and the full build; all task-owned Testboxes are stopped.

@steipete
steipete force-pushed the steipete/perf-micro-worker-idle-gc-20260919 branch from 34935a6 to 2d7254b Compare September 21, 2026 05:58
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Sep 21, 2026
@steipete
steipete force-pushed the steipete/perf-micro-worker-idle-gc-20260919 branch from 2d7254b to f627ead Compare September 21, 2026 06:33
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 21, 2026
@steipete
steipete force-pushed the steipete/perf-micro-worker-idle-gc-20260919 branch from f627ead to 65635a7 Compare September 21, 2026 07:08
@steipete
steipete merged commit 031834e into main Sep 21, 2026
228 checks passed
@steipete
steipete deleted the steipete/perf-micro-worker-idle-gc-20260919 branch September 21, 2026 08:01
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit to vyctorbrzezowski/openclaw that referenced this pull request Sep 21, 2026
…question-layout-restart-recovery-20260921

* 'main' of https://github.com/openclaw/openclaw: (110 commits)
  perf(infra): collect and retire idle worker heaps (openclaw#154408)
  perf(sessions): hand shared history to the final reader (openclaw#154552)
  fix: clarify Codex onboarding migration scope (openclaw#151383)
  fix: recover conflicted PRs after accepted auto-merge
  perf(update): defer Gateway maintenance during candidate validation (openclaw#154548)
  perf(test): advance llama.cpp reload deadlines virtually (openclaw#154536)
  refactor(skills): prepare pinned library resources off-thread (openclaw#148560)
  fix(tooling): preserve Node compiler policy in script subprocesses (openclaw#154509)
  ci: select supported Node and cover packaged Node 26 (openclaw#154298)
  fix(release): preserve Telegram rerun evidence (openclaw#154561)
  docs: follow pending PR merges through completion
  fix(gateway): avoid stuck shutdowns after lifecycle errors (openclaw#145241)
  fix(ui): let focused dashboard widgets fill the task area (openclaw#154440)
  feat(release): add non-Latest extended-stable releases (openclaw#154515)
  fix(release): project 7.35 package Telegram config (openclaw#154546)
  refactor(config): derive host contracts from schemas (openclaw#153936)
  fix(ui): remove finished subagents from inline activity (openclaw#154469)
  refactor(config): derive core channel contracts from schemas (openclaw#153935)
  refactor(config): derive boundary contracts from schemas (openclaw#153937)
  fix(ui): keep thread activity current across cached updates (openclaw#154540)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 22, 2026
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 gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. scripts Repository scripts 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