Skip to content

perf(plugins): bound retained heap across runtime reloads - #166751

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-main-heap-retained-growth-20260919
Oct 7, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-main-heap-retained-growth-20260919

Conversation

@steipete

@steipete steipete commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Repeated plugin runtime reloads retained retired registries and cache inventories through long-lived native async resources.

User Impact

Retired inventories can be collected after admitted work and cleanup settle. Pending calls and streams keep their selected generation across adoption, while completed nested calls release their own hold even when an outer monitor remains active. Expired callbacks continue to fail instead of falling back to a newer registry.

Why This Change Was Made

Host-created scopes borrow their registry; invocation and stream owners retain it through settlement. Preparation scopes and closed service schedulers release their references. Cancellation paths reuse the shared error-stack materializer, and provider-policy caches use their existing publication revision instead of retaining a registry solely for identity.

Service startup drops caller generation ancestry before entering its own context. Lifecycle-lease capabilities are constructed outside the cache-owning function, preventing escaped guard closures from retaining an operation's inventory. Lease validation, refusal, and cleanup behavior remain unchanged. HTTP registration resolves a handler's adopted owner before reading an expired ambient scope.

Direct registry-scope callbacks retain their selection until their returned operation settles. Runtime namespace facades remain stable for their source surface while each call resolves the current registry and enforces revocation. This preserves cold command-router startup and Discord STT interception without extending detached-resource lifetimes.

Production delta: +401 lines. The growth preserves mutable/enumerable scope behavior, explicit prepared selections (including empty views), pending invocation/iterator lifetimes, and typed runtime APIs after adoption. The superseded strong-reference paths and cache-specific error helper are removed; each logical invocation uses one finite registry holder.

Evidence

The reproduction uses a built Gateway, real plugins.reload calls, and a process-owned filesystem watcher pool held open across reloads. Every cycle verifies startup, stop, and disposal; heap samples run after full GC.

Measurement Original Final candidate
Reloads 12 24
Retained fixture payloads 1 → 13 1 → 3; unchanged from reload 2 onward
Post-GC heap change +229.96 MiB +44.39 MiB including warmup
Heap slope, matched reloads 3–12 +18.85 MiB/reload +0.25 MiB/reload

The final six reloads stayed within 230.57–230.76 MiB. Closing the watcher pool released 0.95 MiB, versus 147.76 MiB immediately before the lease fix. Two extra fixture roots remain, with no count growth after reload 2. The original baseline was de38a045; an intermediate candidate at 7a8e5a19 still grew 230.30 MiB over 12 reloads. Final proof was rebuilt from c410e1a2 with the reviewed follow-up repair; its source hashes were verified before execution.

Initial validation used authorized AWS Crabbox fallback cbx_bb265f4188f7, Node 26.8.2, after Blacksmith admission stalled. Earlier controls used cbx_d323bc860f88.

  • Negative controls reproduce retired service, scope, cache, and nested-call retention. Managed service retention changes 12 → 0, service-start caller facts 2 → 0, and lifecycle-lease cache facts 4 → 0. All three nested sync/Promise/thenable cases fail before the final owner correction and pass afterward.
  • 343 tests across 16 affected files passed in the integration runs. The 15-file integration run took 107.51s; the separate 45-test decision file took 28.85s wall time.
  • pnpm test src/plugins/plugin-instance.retention.test.ts --maxWorkers=1: 13 passed, 25.74s wall. Other measured file costs: value views 23.20s, HTTP registry 25.90s, service context 25.45s, lifecycle lease 47.89s.
  • pnpm build: passed in 5m 11s, including CLI bootstrap and SDK export checks. Export-name collision guard and both eager-import/PR-wrapper source-closure files: passed, 20 closure tests.
  • node scripts/check-changed.mjs --staged: passed, including all 27 test typecheck groups, lint, dead exports, import cycles, and storage/security guards. The last lint-first run also passed all 181 targeted tests across 10 files after the final local-state and fixture cleanup. Independent review completed two passes with no accepted P0–P2 findings.

The initial staged gate checked exactly the 33 patch files. Initial validation run: run_d3fbfbfb247407dd582c38e67a101710, 16m 18s command time. File-length advisories remain in the registry runtime, instance, and HTTP-test owners; no file-length suppression or baseline exception was added. The initial hosted run exposed two task-caused regressions, both reproduced and repaired at their owners: premature collection during cold /compact routing and unstable runtime-facade identity in Discord STT capture. No CI reruns were used.

Follow-up validation on AWS cbx_af517903d88b, run run_72ad335650ad6838a0fa2b36cf003b7f: 308 tests across 22 files passed, including the exact command-router test under the pinned Bun runtime and the real Discord capture E2E. The new scope regression fails before the fix in all three completion modes; the STT regression fails before the facade fix. pnpm test <file> --maxWorkers=1 measured 23.21s for Gateway request scopes and 28.86s for runtime config. The 18-file sibling run took 125.43s. Independent follow-up review found no actionable P0–P2 defects. The fresh 24-reload measurement above is from this repaired candidate.

The final node scripts/check-changed.mjs --staged run passed on the same AWS lease: run_6bfa2d64bc5851ae4d2a84439ad0f8f4, 11m 20s command time. All 27 test typecheck groups, core types, lint, dead exports, import cycles, and storage/security guards passed. The final test-only type narrowing was rechecked with all 15 scope tests, and a fresh independent review was clean. The lease was released after validation.

This reproduction isolates plugin-generation retention. It does not establish that these paths explain all long-running Gateway heap growth. No patched production deployment or long-duration patched production measurement is included.

Hosted CI run 37700574898 passed for 7b8c1c1293aa: 678 seconds wall time, with 19,021 summed job-seconds across 79 executed jobs. The PR merged as 40d735e451b1; its 33-file scope and presence on main were verified. No CI rerun or inherited-failure admin exception was used.

Release retired registry and cache graphs held by inherited async scopes,
closed schedulers, cancellation stacks, and lifecycle lease closures.
Keep selected generations only through each admitted call or stream's
lifetime, including nested calls under long-running consumers.

Preserve adopted-owner runtime access, prepared selections, expired-lease
refusals, and resolved plugin values while reducing reload heap retention.
@clawsweeper

clawsweeper Bot commented Oct 7, 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 plugin: file-transfer size: XL labels Oct 7, 2026
@steipete
steipete marked this pull request as ready for review October 7, 2026 21:29
@steipete
steipete enabled auto-merge (squash) October 7, 2026 21:32
@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 7, 2026, 7:15 PM ET / 23:15 UTC (Revision 2).

ClawSweeper review

What this changes

The PR releases retired plugin registries and cache inventories after runtime work settles while preserving pending calls, streams, and adopted runtime access.

Merge readiness

✅ Ready for maintainer review

This remains a useful, distinct retention repair that current main does not provide. No actionable introduced correctness or security defect was found.

Priority: P2
Reviewed head: 7b8c1c1293aa7fd099f8d663db793577c253b4db

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful lifecycle repair with relevant runtime measurements and focused regression coverage; no blocking defect was identified.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured after-fix measurements exercise plugin generation retention through a built Gateway’s real reload entrypoint with native filesystem watchers held open, showing stable fixture counts and a bounded post-warmup heap. Pending-call, stream, facade identity, and expired-lease regressions supplement that proof; 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 captured after-fix measurements exercise plugin generation retention through a built Gateway’s real reload entrypoint with native filesystem watchers held open, showing stable fixture counts and a bounded post-warmup heap. Pending-call, stream, facade identity, and expired-lease regressions supplement that proof; no stored-data contract changes.
Evidence reviewed 9 items Introduced scope and lifetime changes: The pinned introduced delta replaces strong ambient registry references with borrowed views and adds finite custody through returned completion. Current main still contains the original strong-reference implementation.
Current-main necessity check: Comparison against fetched main confirms that borrowed request scopes and the runtime facade changes remain branch work rather than an already implemented replacement.
Pending invocation and stream custody: Invocation holders release their selected registry on fulfillment, rejection, or synchronous completion; stream holders release on terminal cleanup. Added regressions cover adoption during pending work, concurrent consumers, nested calls, and idle iteration.
Findings None None.
Security None None.

How this fits together

OpenClaw’s plugin runtime selects registered capabilities for Gateway requests and background services. Reloads replace registry generations while admitted operations finish against their selected generation.

flowchart TD
  A[Gateway requests and services] --> B[Live plugin admission]
  B --> C[Selected registry generation]
  C --> D[Calls and streams]
  E[Plugin reload] --> F[Replacement registry]
  F --> B
  D --> G[Settlement and cleanup]
  G --> H[Release retired references]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +401, Tests +1388, Docs +8. Total +1797 across 33 files.

View PR surface stats
Area Files Added Removed Net
Source 17 565 164 +401
Tests 15 1411 23 +1388
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 33 1984 187 +1797

Review metrics

Metric Value Why it matters
Production versus regression growth production +401 lines; tests +1388 lines Production growth supports finite custody and stable runtime facades, with regression coverage for their distinct lifecycle boundaries.

Technical review

Best possible solution:

Keep registry custody with finite invocation, stream, and cleanup owners while detached resources retain only borrowed views and live plugin identity.

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

Yes: current-main strong ambient references provide a clear retention path, and the captured body reports a real Gateway reload reproduction. This reviewer did not execute that reproduction.

Is this the best way to solve the issue?

Yes: releasing references at existing settlement boundaries repairs the retaining edges without adding another lifecycle owner or changing stored configuration.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: Repeated plugin reloads retain heap, but the supplied evidence does not establish an urgent production outage.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The captured after-fix measurements exercise plugin generation retention through a built Gateway’s real reload entrypoint with native filesystem watchers held open, showing stable fixture counts and a bounded post-warmup heap. Pending-call, stream, facade identity, and expired-lease regressions supplement that proof; no stored-data contract changes.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured after-fix measurements exercise plugin generation retention through a built Gateway’s real reload entrypoint with native filesystem watchers held open, showing stable fixture counts and a bounded post-warmup heap. Pending-call, stream, facade identity, and expired-lease regressions supplement that proof; no stored-data contract changes.

Label justifications:

  • P2: Repeated plugin reloads retain heap, but the supplied evidence does not establish an urgent production 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 captured after-fix measurements exercise plugin generation retention through a built Gateway’s real reload entrypoint with native filesystem watchers held open, showing stable fixture counts and a bounded post-warmup heap. Pending-call, stream, facade identity, and expired-lease regressions supplement that proof; no stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured after-fix measurements exercise plugin generation retention through a built Gateway’s real reload entrypoint with native filesystem watchers held open, showing stable fixture counts and a bounded post-warmup heap. Pending-call, stream, facade identity, and expired-lease regressions supplement that proof; no stored-data contract changes.

Evidence

What I checked:

  • Introduced scope and lifetime changes: The pinned introduced delta replaces strong ambient registry references with borrowed views and adds finite custody through returned completion. Current main still contains the original strong-reference implementation. (src/plugins/runtime/gateway-request-scope.ts:63, 7b8c1c1293aa)
  • Current-main necessity check: Comparison against fetched main confirms that borrowed request scopes and the runtime facade changes remain branch work rather than an already implemented replacement. (src/plugins/registry-runtime.ts:191, b300e0edea5e)
  • Pending invocation and stream custody: Invocation holders release their selected registry on fulfillment, rejection, or synchronous completion; stream holders release on terminal cleanup. Added regressions cover adoption during pending work, concurrent consumers, nested calls, and idle iteration. (src/plugins/plugin-instance.ts:374, 7b8c1c1293aa)
  • Live ownership and expired-lease refusal: Runtime facade invocation checks current plugin lifecycle authority. HTTP registration retains expired-lease, revoked-owner, and retired-registry checks before registration; lease-context extraction preserves the existing authority callbacks. The lease regression checks rejected persisted-index writes after expiry. (src/plugins/http-registry.ts:303, 7b8c1c1293aa)
  • Real Gateway reload evidence: The captured PR body reports a built Gateway on an authorized Crabbox using real plugins.reload calls with a filesystem watcher pool kept open. Across 24 candidate reloads, fixture payload counts plateaued at three after reload two; matched reloads 3–12 reduced post-GC heap slope from 18.85 to 0.43 MiB/reload. Final six samples stayed within 231.12–231.33 MiB. This supports bounded generation retention, not a claim about all production heap growth. (7b8c1c1293aa)
  • Validation and compatibility scope: The captured body reports passing affected tests, build, and changed-file gates. Inspection found no introduced schema, serialized-state, configuration-default, dependency, or publishing change. Tests were not executed during this read-only review; the introduced diff passed git diff --check. (src/plugins/plugin-lifecycle-lease.ts:34, 7b8c1c1293aa)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • obviyus: 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 (1 earlier review cycle)
  • reviewed 2026-10-07T21:35:12.408Z sha c410e1a :: needs maintainer review before merge. :: none

Keep direct registry-scope callbacks alive through their returned completion,
then release custody so detached native resources cannot retain the registry.
Reuse runtime namespace facades per source while selecting the current registry
at invocation time. This preserves cold native-command authorization and Discord
STT interception across runtime adoption and source replacement.
@steipete
steipete disabled auto-merge October 7, 2026 23:05
@steipete
steipete enabled auto-merge (squash) October 7, 2026 23:07
@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 Oct 7, 2026
@steipete
steipete merged commit 40d735e into main Oct 7, 2026
169 checks passed
@steipete
steipete deleted the steipete/perf-micro-main-heap-retained-growth-20260919 branch October 7, 2026 23:21
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 8, 2026
…66751)

* perf(plugins): bound retained heap across runtime reloads

Release retired registry and cache graphs held by inherited async scopes,
closed schedulers, cancellation stacks, and lifecycle lease closures.
Keep selected generations only through each admitted call or stream's
lifetime, including nested calls under long-running consumers.

Preserve adopted-owner runtime access, prepared selections, expired-lease
refusals, and resolved plugin values while reducing reload heap retention.

* fix(plugins): preserve pending scopes and runtime facade identity

Keep direct registry-scope callbacks alive through their returned completion,
then release custody so detached native resources cannot retain the registry.
Reuse runtime namespace facades per source while selecting the current registry
at invocation time. This preserves cold native-command authorization and Discord
STT interception across runtime adoption and source replacement.
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 P2 Normal backlog priority with limited blast radius. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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