Repository navigation
fix: reduce retained Gateway and Activity memory - #134891
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed September 1, 2026, 5:02 AM ET / 09:02 UTC. ClawSweeper reviewWhat this changesThis PR limits reply initialization and lifecycle work to relevant session rows, prevents long-lived background resources from retaining request context, and copies bounded Control UI activity previews. Warning SQLite table change This PR modifies persisted SQLite tables in Merge readinessKeep open. Current main does not contain the PR’s selected-session and retained-memory fixes; the patch follows the owning lifecycle boundaries and has no actionable introduced defect in review. Priority: P1 Review scores
Verification
How this fits togetherGateway reply handling reads and commits session state before agent work; this PR narrows those reads while preserving related-session and lifecycle ownership. Background timers, watchers, and Control UI activity output can outlive a request, so they now retain only background context or bounded preview text. flowchart LR
A[Inbound Gateway reply] --> B[Selected session snapshot]
B --> C[Reply initialization]
C --> D[Lifecycle commit and cleanup]
E[Background timers and watchers] --> F[Background context]
G[Activity output] --> H[Redacted bounded preview]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +84, Tests +611. Total +695 across 30 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Retain the selected-row and metadata-only lifecycle design, with exact-head session and background-lifetime regressions passing before merge. Do we have a high-confidence way to reproduce the issue? No current-main execution was performed in this read-only review; source inspection and the PR’s before/after owner-boundary evidence provide a high-confidence reproduction path. Is this the best way to solve the issue? Yes. The patch repairs retention at the session, resource, and Activity owners rather than adding downstream cleanup or raising limits. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against d9031e4648a4. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles)
|
d1b4d9c to
3d4744b
Compare
|
The two rank-up moves are complete. The rebase preserves #134814's metadata authorization and captured archive decisions. The combined runtime was rebuilt at The SQLite-table warning does not apply: the WAL diff changes the context used to allocate its existing periodic timer, with no DDL, schema, stored row format, checkpoint mode, interval, or retention-policy change. Existing-state session ownership, concurrency, lifecycle and live reset/delete coverage passed. Main's metadata sharing implementation is retained unchanged. CI found a separate real bug in release inventory discovery: an unnecessary recursive Git tree listing exceeded Node's 1 MiB buffer. Final head @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
25f9016 to
300b778
Compare
4f4b60f to
184c9c3
Compare
|
Merged via squash.
|
Related: #91588 (long-running Gateway memory growth)
What Problem This Solves
Fixes an issue where operators with large saved-session histories would see Gateway memory grow during ordinary CLI and Web UI conversations. Activity could also retain a large tool result long after its raw event left the feed, despite displaying only a short preview.
Why This Change Was Made
Single-session lookups and reply initialization acquired every saved prompt, then request closures carried those inventories into background resource lifetimes. The repair reads the current session and declared relatives in one SQLite snapshot, projects lifecycle writes and deletion references before acquiring prompt payloads, and gives shared watchers, dispatcher cleanup, MCP idle sweeps, and SQLite maintenance timers their own startup context. Authorized diagnostics explicitly obtains the metadata inventory it needs. Activity owns a copy of its bounded preview.
The same pass fixes key-less reply preprocessing, which omitted the configured agent ID when deriving the session key. Request authorization and transport acquisition stay in the caller's context; only owner-managed background work changes context. SQLite schema, maintenance timing, retention policy, configuration, and visible Activity contents remain unchanged.
Current-head integration preserves #134814 (metadata-only authorization and unused deletion-scan removal), which landed during this pass. Its sharing-policy and cache-test changes remain identical to main; selected lifecycle reads retain its captured archive decisions. The current candidate is
184c9c303faon main2a920ab94d3. Main also independently landed #134935’s exact-row Gateway lookups and #134812’s Doctor readiness-fixture repair. Those implementations remain unchanged, and this PR drops its duplicate lookup and fixture changes. The remaining 30-file patch has the same stable patch ID as the corresponding files in the previously tested memory commit. The base also includes #134824’s release-inventory repair.User Impact
CLI and Web UI conversations retain substantially less memory when many sessions have saved prompts. Session lists, parent inheritance, diagnostics discovery, reset/delete cleanup, memory indexing, and Activity output remain functional.
Evidence
Measurements below are from original candidate
d1b4d9cccef9383c9ded24a2ed56b5cd7152a0bf, against freshly pulled main38f80876377c15c3150a8c1e0b1922a87815b606, using Node 24.19.0, an isolated built Gateway, the actual CLI and Control UI, and a deterministic local OpenAI-compatible provider. The corpus contains 1,998 sessions with 64 KiB saved prompts. This is a controlled stress workload, not a multi-day production soak.Final integrated runtime proof (
184c9c303fa): the complete build passed and all nine workload stages passed, with 310.99 MB post-GC heap, 834.42 MB RSS, 2285.55 MB workload peak RSS, zero retained saved fixture prompts, and zero browser errors. Reset retained the session ID, rotated its lifecycle, cleared saved skills, preserved the model override, and deletion changed 1,998 rows to 1,997; repeated deletion returned false and an unrelated row stayed byte-identical. The final/readyzresponse was ready with no failing checks or event-loop degradation. Source/tree/diff and built-file hashes bind this replay to the exact pushed commit.The earlier integrated build (
300b7781d554) also passed all nine stages, with 313.20 MB heap, 836.83 MB RSS, and zero retained saved fixture prompts. These integration figures include newer main changes and are not a separate attribution of their gains to this PR. Historical integration suites passed 289 tests, then another 108 tests with seven Linux-only cases skipped locally.The workload covers prepared/full/refreshed model catalogs, three CLI agent turns, 500 distinct paginated session keys, 20 reconnect/subscription cycles, 20 status/list cycles, Web UI paging/sidebar expansion/reloads, and an actual composer reply. Reset and deletion additionally verify lifecycle rotation, repeated deletion, and preservation of an unrelated session. Browser errors: zero.
Allocation and owner probes independently show reply-snapshot retention falling from 132.25 MB to 0.12 MB; commit retention from 135.95 MB to 8.94 MB; and deletion survivor payload acquisition from 131.19 MB to 0.16 MB, with transcript ownership and unrelated persisted rows preserved. The final main-isolate heap snapshot contains zero saved fixture prompts, versus 5,994 retained copies on the baseline. The Activity browser stress case retains 0.65 MB instead of 17.35 MB after 100 large results and eviction of all raw result events; the same 100 rows and 200,000 preview characters remain visible.
The catalog grew from 230 to 266 models during the test window, so no cold-catalog performance improvement is claimed. Whole-process RSS includes Workers and allocator behavior; heap figures are post-GC main-isolate measurements. The pool idle timer was bounded at 60 seconds. Watchers and repeating MCP/SQLite maintenance timers retained completed turns until their owners closed; the periodic timers now start in their owner context. This PR does not claim to resolve every multi-day/custom-plugin report in #91588.
Regression tests fail on the original sources and pass with the repairs, including actual native timers/watchers under two async contexts, related-row snapshot consistency across an await, shared-window deletion, writable/read-only lookup visibility, diagnostics inventory, key-less ingress, and both Activity payload branches. Focused and sibling lifecycle, authorization, heartbeat, transport, and UI suites pass. Full build, formatting, core/test/UI/plugin type checks, lint, dead-export and boundary guards passed. The final MCP/WAL suites passed 170 tests (seven Linux-only tests skipped on macOS). A fresh independent Codex review found no actionable P0 issues. One build attempt correctly stopped on a changing dependency-resolution namespace; the unchanged-source retry passed. A Promise-executor lint finding in the new test was corrected and the suite/lint rerun passed.
The base includes #134824's release-inventory repair: it selects package metadata from the immutable Git tree before collecting it, preventing unrelated source growth from overflowing Node's 1 MiB buffer. This resolves the
ENOBUFSencountered in CI, with a large-tree regression and root/core/plugin manifest and README symlink coverage. The memory PR preserves that implementation unchanged.ClawSweeper follow-through: its September 1, 09:02 UTC review covers exact head
184c9c303faand finds no actionable introduced defect. The maintainer accepts the bounded lifecycle change and net 84 production lines with the selected-session, related-parent/command-target, shared-window deletion, concurrency, and native-lifetime regressions retained and passing. The complete build, 180-test focused run, changed-scope checks, live reset/delete and zero-retainer replay, and exact-head CI supply the requested integration proof. Its SQLite-table and serialized-state warnings are not applicable:sqlite-wal.tsonly changes the async context used to allocate its existing maintenance timer, and the entry-mutation change removes unused revision plumbing. No DDL, schema, stored row format, checkpoint mode, maintenance interval, or persistence policy changes.Production: +257/-173 (net +84); tests and test support: +686/-75 (net +611). The added production code establishes selected-row snapshot acquisition and explicit background lifetime ownership; obsolete whole-inventory paths, the no-op initialization helper, and unused revision plumbing are removed from these flows. A preexisting test fixture now keeps its reindex lock inside temporary state. Named follow-ups: forced maintenance still hydrates full entries, and the UI full-message expansion cache has no payload-byte cap; neither is claimed fixed here.
Latest candidate validation: fresh independent Codex P0 review is clean; the exact-head full build and all nine live stages pass, and full CI run 33486488004 is green. The final focused integration run passed 180 tests across 14 files, with seven Linux-only cases skipped on macOS, including all 11 Doctor process cases.
check:changedpassed formatting, dependency and source-boundary guards, Doctor closure tests, core/test/UI/plugin typechecks, lint, unused-export scans, schema/storage guards, import-cycle checks, and webhook/pairing guards. Earlier measured results above remain tied to their stated revisions. The Doctor CI timeout is repaired by main #134812’s canonical pre-worker runtime build; its original readiness deadline and migration assertions remain intact.Before and after Activity: identical visible content, bounded retained storage.
Actual rebuilt Gateway Web UI reply on final head
184c9c303fa:memory-pass5-latest-integrated-ui.webm