Skip to content

fix(gateway): release completed runs and obsolete cache state (main-thread heap retention) - #163834

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

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

Conversation

@steipete

@steipete steipete commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Long-running Gateways retain completed chat registrations, obsolete usage reports, and prompt text owned only by diagnostics. sessions.describe and sessions.get can also keep preparing rows after their connection closes.

User Impact

The Gateway releases finished or abandoned work and obsolete cached content sooner. Active execution, accepted writes, late tool-event delivery, and reply-dispatch completion retain their existing ownership.

Why This Change Was Made

Terminal registration cleanup must follow run completion regardless of whether a visible message is delivered. Usage revisions invalidate a stable query entry instead of creating another historical copy; cache writes evict settled variants idle for 30 seconds while preserving same-query stale refreshes. Prompt fingerprints should not extend transcript text lifetime. Pure session reads now enter the existing observation lifetime before authorization; row preparation stops on disconnect after admitted work settles.

Evidence

Campaign input: approximately 230 MB/hour of main-thread heap growth, with GC accounting for 24% of main-thread busy time. These deployment measurements are context; the synthetic comparison below does not establish the production GC-time improvement.

Baseline validation completed on Blacksmith Testbox (blacksmith-testbox, profile openclaw-check), lease tbx_01m3yxq2dm2s0adhrnh6bm0r11, run 37047126001. The comparison uses original production sources at eb50c3a61b815b322fa2cf198304f64e84e160ee and the same authored rig/regressions.

Measurement Original Candidate
Rig heap at 5-minute snapshot 354,528,240 B 318,490,720 B
Rig heap at 30-minute snapshot 551,879,576 B 334,259,608 B
Rig heap growth, 5→30 minutes 197,351,336 B 15,768,888 B (92.01% lower)
Rig growth per 1,000 RPCs 30,530,838 B 2,439,494 B
Usage owner: retained results after 64 revisions 64 1 (latest)
Usage owner: forced-GC heap delta 19,525,816 B 480,568 B
Prompt owner: forced-GC heap delta after dropping 75 MiB of text 79,016,280 B 350,992 B

Both rigs completed the identical 300 mock turns, 7,754 RPCs, and 82 connections with zero failures, using 300 sessions and eight reconnecting clients. Candidate validation used lease tbx_01m3z19pkwd8tvcn071vhq7pw7, run 37054100499. Final live heap was 217,619,968 B lower; heap-node growth fell from 3,906,330 to 95,846 nodes. The original-code strong-edge snapshot diff identified sessionsUsageCache: the Map retained 36,728,352→218,221,128 B (+181,492,776 B), about 92% of observed heap growth. Retainer path: process module context → sessionsUsageCache → entry → value → sessions. The cache revision had become a new query key, so every published usage rollup retained a historical response. A smaller catalog pages cache grew about 1.20 MB; that owner belongs to a separate campaign lane.

Owner probes use real exported observation/cache entry points, release original owners, and force GC. The prompt probe collected every original message object while its full text remained retained. The usage probe retained all 64 historical results and sampled session rows. Original-source regressions produced the expected 11 failures (137 passing) across hidden terminal cleanup, abandoned registration sweep, usage revision/expiry, and canonical/placement cancellation; 53.52 seconds wall time.

Commands: scripts/build-all.mts sourcePerformance (baseline 47.76 s, pass), scripts/bench-gateway-heap-retention.ts --agent-turns 300 (31m46.619s including final capture, pass), scripts/heap-snapshot-diff.mjs (pass), and focused scripts/run-vitest.mjs runs. Candidate probes and focused tests pass. Final sourcePerformance build: 41.84 s; the complete candidate build/test/rig command: 32m55.849s, pass. Independent Codex autoreview completed scoped-clean through P2 with no accepted/actionable findings. The branch was rebased onto current main without changing the reviewed patch (git range-diff reports equality). The final node scripts/check-changed.mjs --staged passed in 1,480.40 s on lease tbx_01m3zav7jgqk0dm3gtkceqdadz, run 37071281213. It includes all 27 core test typecheck shards, production/script types, dead-export scans, lint, docs, and repository guards.

The final rig also passed a one-minute smoke after its polling loops were replaced with explicit promise gates: 10 sessions, two reconnecting clients, 10 turns, 1,090 RPCs, 26 connections, and two snapshots with zero failures. This used lease tbx_01m3z4m0fr1b1a5aebdb08y77k, run 37060358398. The matched 30-minute comparison used identical pre-cleanup rigs; production code was unchanged by this harness-only cleanup.

The candidate's retainer paths show the old usage entry collected and replaced by the current entry (~0.95 MB). Remaining growth includes V8 code metadata (9.79 MB class delta; class totals overlap), the catalog pages cache (+1.20 MB, separate lane), and current connection-owned session metadata. No additional leak was confirmed. The rig does not measure GC's share of busy time; production heap/GC needs remeasurement after deployment.

Focused test costs and negative controls

Final changed-test costs on Testbox, using node scripts/run-vitest.mjs <file> --maxWorkers=1 (the worktree-safe runner for pnpm test <file> --maxWorkers=1):

File Tests Wall / CI runner seconds
prompt-cache-observability.test.ts 44 3.15
agent-turn/internal-facade.test.ts 23 28.43
server-chat.agent-events.test.ts 82 26.21
server-chat.registration-lifecycle.test.ts 8 8.96
server-maintenance.chat-state.test.ts 8 9.25
server-methods.suspension-admission.test.ts 27 8.52
server-methods/usage-cache.test.ts 7 2.30
session-row-placement-projection.lifecycle.test.ts 6 8.42
session-row-prepared-read.test.ts 10 10.91
usage.sessions-usage-owner-attribution.integration.test.ts 9 47.68

These include transform/import time; CI scheduling can differ. Seven sibling files passed 164 tests in 57.44 seconds. After extracting the oversized event suite and moving existing rootless-request policy into its lifecycle owner, five affected files passed 162 tests in 43.52 seconds. The root-drain negative control fails with zero active roots while an accepted child is blocked; the candidate keeps its admission until settlement. The corrected hidden-run fixture, using the canonical run-context owner, independently fails on original cleanup with 300 retained registrations in both visibility variants (29.29 seconds), and passes on the candidate.

A confirmed producer of hidden registrations is subagent coordination sent to a main/global session: admission registers the run while suppressing visible session messages. Its terminal previously skipped registration retirement.

The prompt text memo was introduced after the original deployment sample; it is a current retention issue, not established as the cause of that earlier measurement. Pending session-change event retention remains unconfirmed: those committed publications own a Gateway lifetime and intentionally survive reconnect.

Protected agent-run claims remain unchanged: the exact execution owner must release them after accepted terminal writes settle. Session-row resident projection and catalog list ownership belong to separate campaign lanes.

CI follow-up: the first published-head run found two unregistered executable files in the unused-file scan and one failed shared-store usage-attribution case. The follow-up registers the benchmark CLI and its IPC preload as real Knip execution roots, and adds the handler error to the existing usage assertion without weakening it. On Blacksmith Testbox lease tbx_01m3zdmp9gwdvjw9tckw50cj29, run 37075576276, export scans passed (112.72 s), production/full-tree unused-file scans reported zero entries (66.07 s), and focused type/lint/line-cap checks passed. The exact CI group passed 141 tests (121.72 s); the focused file passed nine tests with the current cache (47.68 s) and with the two parent cache modules restored (49.68 s). The original usage failure remains unreproduced; these passing replays do not establish a fix or inherited attribution. The follow-up also passed fresh independent review through P2 with no actionable findings. CI for updated head 29e6804889ea2ffee26897bd671315e4ffc61560 passed in run 37078610993, including the required openclaw/ci-gate.

@clawsweeper

clawsweeper Bot commented Oct 2, 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 scripts Repository scripts agents Agent runtime and tooling size: XL labels Oct 2, 2026
@steipete
steipete marked this pull request as ready for review October 2, 2026 22:47
@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components. This comment is informational because the PR author has repository Maintain or Admin access.

  • Current SHA: 29e6804889ea2ffee26897bd671315e4ffc61560
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/methods/core-descriptors.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server-methods.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@steipete
steipete enabled auto-merge (squash) October 2, 2026 22:49
@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 2, 2026
@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

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

ClawSweeper review

What this changes

The Gateway releases completed chat registrations, replaces obsolete usage results, avoids retaining prompt text through diagnostics, and stops disconnected session-read preparation.

Merge readiness

⛔ Blocked before merge - 1 item remains

This PR remains useful against fetched main, and no actionable introduced defect was found. The earlier migration concern does not apply: the changed caches and request lifetimes are process-local.

Priority: P2
Reviewed head: 29e6804889ea2ffee26897bd671315e4ffc61560

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong measured runtime evidence supports a coherent owner-level repair with no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied Testbox comparison exercises the compiled Gateway's session and usage owners through real WebSocket requests and reconnects, showing 92.01% lower synthetic heap growth with zero workload failures; owner probes and failing original-source regressions supplement it. No stored-data contract changes, so migration proof is not applicable.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied Testbox comparison exercises the compiled Gateway's session and usage owners through real WebSocket requests and reconnects, showing 92.01% lower synthetic heap growth with zero workload failures; owner probes and failing original-source regressions supplement it. No stored-data contract changes, so migration proof is not applicable.
Evidence reviewed 9 items Pinned introduction boundary: Reviewed the merge-base-to-head introduction, keeping base-only session-suggestion tests outside PR ownership. The host verified the original head and the test merge's separate parent identities.
Current main still retains historical usage keys: Fetched main includes profile and usage revisions in query keys and lacks the candidate's revision replacement and idle-entry eviction. The central retention repair therefore remains necessary; no merged replacement was established.
No persisted data-model change: Both usage caches are module-local Maps. Query axes, including visibility identity, remain intact while revision becomes entry metadata. Prompt diagnostics use WeakMap/WeakRef ownership. No schema, serialized state, migration, or stored preference changes are introduced, resolving the previous review's upgrade-proof concern.
Findings None None.
Security None None.

How this fits together

The Gateway receives client requests and agent lifecycle events, prepares session information, and publishes replies and updates. Its request and cache owners determine how long completed work and derived content remain in memory.

flowchart TD
 A[Client requests] --> B[Authorization and admission]
 B --> C[Connection-bound session reads]
 C --> D[Replies and session updates]
 E[Agent lifecycle events] --> F[Run registration cleanup]
 B --> G[Usage result cache]
 G --> D
 H[Transcript messages] --> F
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +92, Tests +315, Docs +2, Other +642. Total +1051 across 27 files.

View PR surface stats
Area Files Added Removed Net
Source 11 419 327 +92
Tests 11 689 374 +315
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 4 643 1 +642
Total 27 1753 702 +1051

Review metrics

Metric Value Why it matters
Code growth by responsibility runtime +92 lines; tests/support +415; tooling/config +642 Runtime growth implements cancellation settlement; most added tooling is the isolated heap comparison rig.
Measured heap retention 92.01% lower synthetic heap growth over minutes 5–30 The matched workload provides direct evidence for the retention repair without claiming production GC improvement.

Stored data model

Persistent data-model change detected: serialized state: scripts/bench-gateway-heap-retention.ts, unknown-data-model-change: scripts/bench-gateway-heap-retention.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep derived content bounded by its existing owner and end disconnected observations while allowing accepted execution, persistence, and delivery to settle.

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

Yes: current-main source retains historical usage revisions, and the supplied matched Gateway run and original-source negative controls demonstrate retention. This reviewer did not execute a reproduction.

Is this the best way to solve the issue?

Yes: the patch repairs existing lifecycle and cache owners while preserving query isolation, authorization, and accepted-work settlement.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This repairs measured long-running Gateway heap retention without evidence of an immediate outage.
  • 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 supplied Testbox comparison exercises the compiled Gateway's session and usage owners through real WebSocket requests and reconnects, showing 92.01% lower synthetic heap growth with zero workload failures; owner probes and failing original-source regressions supplement it. No stored-data contract changes, so migration proof is not applicable.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied Testbox comparison exercises the compiled Gateway's session and usage owners through real WebSocket requests and reconnects, showing 92.01% lower synthetic heap growth with zero workload failures; owner probes and failing original-source regressions supplement it. No stored-data contract changes, so migration proof is not applicable.

Evidence

What I checked:

  • Pinned introduction boundary: Reviewed the merge-base-to-head introduction, keeping base-only session-suggestion tests outside PR ownership. The host verified the original head and the test merge's separate parent identities. (29e6804889ea)
  • Current main still retains historical usage keys: Fetched main includes profile and usage revisions in query keys and lacks the candidate's revision replacement and idle-entry eviction. The central retention repair therefore remains necessary; no merged replacement was established. (src/gateway/server-methods/usage-result-cache.ts:65, 810018486a55)
  • No persisted data-model change: Both usage caches are module-local Maps. Query axes, including visibility identity, remain intact while revision becomes entry metadata. Prompt diagnostics use WeakMap/WeakRef ownership. No schema, serialized state, migration, or stored preference changes are introduced, resolving the previous review's upgrade-proof concern. (src/gateway/server-methods/usage-result-cache.ts:24, 29e6804889ea)
  • Cancellation retains accepted settlement: The observation scope surrounds preparation and authorization, retains existing root admission at handler entry, drains tracked descendants, and releases the root afterward. Method scopes, profile checks, session authorization, and final invocation guards remain present. (src/gateway/server-request-lifecycle.ts:128, 29e6804889ea)
  • Terminal cleanup preserves delivery ownership: Registration retirement now occurs independently of visible terminal publication. Reply-dispatch-owned completion remains excluded, superseded lifecycle events return before cleanup, and maintenance preserves active execution and queued delivery owners. (src/gateway/server-chat.ts:531, 29e6804889ea)
  • Real Gateway heap comparison: The supplied PR body records matched Testbox runs through a compiled Gateway and real WebSocket clients: 300 turns, 7,754 RPCs, and 82 connections per run with zero failures. Post-GC growth fell from 197,351,336 to 15,768,888 bytes. The inspected benchmark exercises session reads, usage queries, committed updates, and reconnects with a mock provider. This supports synthetic retention improvement, not a production GC-time claim. (scripts/bench-gateway-heap-retention.ts:1, 29e6804889ea)

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 (1 earlier review cycle)
  • reviewed 2026-10-02T22:52:54.530Z sha e3b3c66 :: blocked before merge. :: none

Retire hidden terminal registrations, replace usage revisions at stable query keys, and keep prompt text memos owned by transcript messages. Bind session-row preparation to observation lifetimes while retaining accepted work through settlement.

A matched 300-session workload completed 300 turns and 7,754 RPCs per run with zero failures. Post-GC heap growth between the five- and thirty-minute snapshots fell from 197,351,336 to 15,768,888 bytes. Focused and sibling tests, the full staged check on Blacksmith Testbox, and independent review passed.
Model the manually executed benchmark and its Node IPC preload as Knip entrypoints. Include the handler error in the existing usage-attribution assertion without changing its expectation.

The full unused-file scans pass with zero entries. The original CI usage failure did not reproduce in the exact 141-test group or in the nine-test focused file using either current or parent cache modules; these replays do not establish a behavioral fix.
@steipete
steipete force-pushed the steipete/perf-micro-main-heap-retention-20260919 branch from e3b3c66 to 29e6804 Compare October 2, 2026 23:39
@steipete
steipete merged commit 5ab3ae2 into main Oct 2, 2026
150 of 151 checks passed
@steipete
steipete deleted the steipete/perf-micro-main-heap-retention-20260919 branch October 2, 2026 23:53
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 3, 2026
…hread heap retention) (openclaw#163834)

* perf(gateway): release completed runs and obsolete cache state

Retire hidden terminal registrations, replace usage revisions at stable query keys, and keep prompt text memos owned by transcript messages. Bind session-row preparation to observation lifetimes while retaining accepted work through settlement.

A matched 300-session workload completed 300 turns and 7,754 RPCs per run with zero failures. Post-GC heap growth between the five- and thirty-minute snapshots fell from 197,351,336 to 15,768,888 bytes. Focused and sibling tests, the full staged check on Blacksmith Testbox, and independent review passed.

* fix(ci): register heap rig and improve usage failure diagnostics

Model the manually executed benchmark and its Node IPC preload as Knip entrypoints. Include the handler error in the existing usage-attribution assertion without changing its expectation.

The full unused-file scans pass with zero entries. The original CI usage failure did not reproduce in the exact 141-test group or in the nine-test focused file using either current or parent cache modules; these replays do not establish a behavioral fix.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation 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. scripts Repository scripts security-sensitive-changed 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