Repository navigation
fix(gateway): release completed runs and obsolete cache state (main-thread heap retention) - #163834
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
|
Codex review: blocked before merge. Reviewed October 2, 2026, 7:46 PM ET / 23:46 UTC (Revision 2). ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherThe 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
Before merge
Agent review detailsSecurityNone. PR surfaceSource +92, Tests +315, Docs +2, Other +642. Total +1051 across 27 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest 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. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
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.
e3b3c66 to
29e6804
Compare
…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.
What Problem This Solves
Long-running Gateways retain completed chat registrations, obsolete usage reports, and prompt text owned only by diagnostics.
sessions.describeandsessions.getcan 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, profileopenclaw-check), leasetbx_01m3yxq2dm2s0adhrnh6bm0r11, run 37047126001. The comparison uses original production sources ateb50c3a61b815b322fa2cf198304f64e84e160eeand the same authored rig/regressions.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 identifiedsessionsUsageCache: 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 catalogpagescache 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 focusedscripts/run-vitest.mjsruns. Candidate probes and focused tests pass. FinalsourcePerformancebuild: 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 currentmainwithout changing the reviewed patch (git range-diffreports equality). The finalnode scripts/check-changed.mjs --stagedpassed in 1,480.40 s on leasetbx_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
pagescache (+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 forpnpm test <file> --maxWorkers=1):prompt-cache-observability.test.tsagent-turn/internal-facade.test.tsserver-chat.agent-events.test.tsserver-chat.registration-lifecycle.test.tsserver-maintenance.chat-state.test.tsserver-methods.suspension-admission.test.tsserver-methods/usage-cache.test.tssession-row-placement-projection.lifecycle.test.tssession-row-prepared-read.test.tsusage.sessions-usage-owner-attribution.integration.test.tsThese 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 head29e6804889ea2ffee26897bd671315e4ffc61560passed in run 37078610993, including the requiredopenclaw/ci-gate.