Skip to content

fix: reduce retained Gateway and Activity memory - #134891

Merged
steipete merged 1 commit into
mainfrom
codex/perf-gateway-memory-pass5
Sep 1, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/perf-gateway-memory-pass5

Conversation

@steipete

@steipete steipete commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

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 184c9c303fa on main 2a920ab94d3. 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 main 38f80876377c15c3150a8c1e0b1922a87815b606, 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.

Measurement Baseline Candidate Reduction
Main heap after GC 703.82 MB 313.37 MB 55.5%
Process RSS after GC 1318.81 MB 830.36 MB 37.0%
Workload peak RSS 3504.31 MB 2460.60 MB 29.8%
Retained saved-prompt copies 5,994 (392.92 MB) 0 100%

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 /readyz response 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 ENOBUFS encountered 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 184c9c303fa and 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.ts only 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:changed passed 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.

Activity before

Activity after

Actual rebuilt Gateway Web UI reply on final head 184c9c303fa:

memory-pass5-latest-integrated-ui.webm

@clawsweeper

clawsweeper Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime extensions: memory-core Extension: memory-core agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 1, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. 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 1, 2026
@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 1, 2026, 5:02 AM ET / 09:02 UTC.

ClawSweeper review

What this changes

This 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 src/infra/sqlite-wal.ts. Prefer a design that avoids changing persisted SQLite tables. If the change is necessary, verify migration and upgrade compatibility against an existing database before merge.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep 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
Reviewed head: 184c9c303fa9ab5adcd6dfe6be89e26a295d825f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong supplied behavior evidence and owner-boundary coverage support a large but merge-sensitive session and lifecycle repair.
Proof confidence 🦞 diamond lobster (5/6) Not applicable: The PR is maintainer-authored; its supplied rebuilt-Gateway, CLI, Control UI, screenshot, and recording evidence supports the claimed behavior, while this read-only review did not execute it.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The PR is maintainer-authored; its supplied rebuilt-Gateway, CLI, Control UI, screenshot, and recording evidence supports the claimed behavior, while this read-only review did not execute it.
Evidence reviewed 7 items Current-main necessity: Current main d9031e4 still materializes broad reply-session stores, while this head reads only the current and declared related rows; the candidate head is not an ancestor of current main and no release tag contains it.
Session owner boundary: The snapshot reads the current row, declared related rows, and the current row’s stored parent in one deferred read-only transaction; the caller supplies main, parent, model-parent, command-target, and thread-parent keys.
Lifecycle sibling safety: Lifecycle projection hydrates mutation rows only, while deletion still scans survivor metadata to preserve shared session-window references without loading unrelated prompts.
Findings None None.
Security None None.

How this fits together

Gateway 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]
Loading

Before merge

  • Resolve merge risk (P1) - The patch changes persisted-session selection and lifecycle cleanup; upgrades with uncommon parent, command-target, or shared-window relationships remain compatibility- and session-state-sensitive despite focused coverage.
  • Resolve merge risk (P1) - Production code grows by 84 net lines; the growth is tied to selected-row snapshot ownership and background-lifetime isolation, but it increases the review surface.
Agent review details

Security

None.

PR surface

Source +84, Tests +611. Total +695 across 30 files.

View PR surface stats
Area Files Added Removed Net
Source 18 257 173 +84
Tests 12 686 75 +611
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 30 943 248 +695

Review metrics

Metric Value Why it matters
Production vs test LOC production +257/-173 (net +84); tests/test support +686/-75 (net +611) The production growth implements selected-row session ownership and background resource isolation; the larger test delta covers persistence, lifetime, and retention regressions.

Stored data model

Persistent data-model change detected: serialized state: src/config/sessions/session-accessor.entry-mutation.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Accept the bounded lifecycle change (recommended)
    Merge only with the selected-session and deletion regressions retained, so uncommon existing session relationships remain covered.

Technical review

Best 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.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P1: The repair targets retained memory and unnecessary work in active Gateway reply handling.
  • merge-risk: 🚨 compatibility: Existing persisted session relationships and lifecycle behavior are narrowed to selected rows.
  • merge-risk: 🚨 session-state: The patch changes session snapshot selection, concurrent metadata merging, and cleanup reference handling.
  • 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. Not applicable: The PR is maintainer-authored; its supplied rebuilt-Gateway, CLI, Control UI, screenshot, and recording evidence supports the claimed behavior, while this read-only review did not execute it.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vishal Doshi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Josh Avant: 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 (3 earlier review cycles)
  • reviewed 2026-09-01T05:55:00.524Z sha d1b4d9cccef9383c9ded24a2ed56b5cd7152a0bf :: needs maintainer review before merge. :: none
  • reviewed 2026-09-01T07:24:22.382Z sha 300b778 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-01T08:14:26.738Z sha 4f4b60f4656670b8dd228a904b2b9b310493da0f :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/perf-gateway-memory-pass5 branch from d1b4d9c to 3d4744b Compare September 1, 2026 05:56
@steipete
steipete marked this pull request as ready for review September 1, 2026 05:57
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Sep 1, 2026
@steipete

steipete commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

The two rank-up moves are complete. The rebase preserves #134814's metadata authorization and captured archive decisions. The combined runtime was rebuilt at 3d4744b6f0da30cfd3e2a761b1b255765cc9b4f1 and passed all nine live Gateway/CLI/Control UI stages again: 312.20 MB post-GC heap, 824.38 MB RSS, zero retained saved fixture prompts, zero browser errors, and successful reset/delete with an unrelated row unchanged. Updated sanitized recording and full methodology are in the PR body. The conflict-neighborhood suites passed 289 tests; final-head native background/Activity checks passed another 79, with seven Linux-only cases left to hosted Linux CI.

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 25f90162ed8ccad28292ae299fc43435c9c5887c adds only the script/test repair, selecting the same 273 metadata records from the immutable candidate with 37,120 bytes of output instead of 1,048,974. The existing test fails before the repair, all 47 producer tests pass after, and the final changed-file gate and fresh Codex P0 review pass. No release/publication policy changed. Final-head CI is running.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete
steipete force-pushed the codex/perf-gateway-memory-pass5 branch from 25f9016 to 300b778 Compare September 1, 2026 06:51
@openclaw-barnacle openclaw-barnacle Bot removed the scripts Repository scripts label Sep 1, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 1, 2026
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts commands Command implementations labels Sep 1, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 1, 2026
@steipete
steipete force-pushed the codex/perf-gateway-memory-pass5 branch from 4f4b60f to 184c9c3 Compare September 1, 2026 08:19
@openclaw-barnacle openclaw-barnacle Bot removed gateway Gateway runtime scripts Repository scripts labels Sep 1, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the commands Command implementations label Sep 1, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 1, 2026
@steipete
steipete merged commit 98ebcc4 into main Sep 1, 2026
303 checks passed
@steipete
steipete deleted the codex/perf-gateway-memory-pass5 branch September 1, 2026 09:20
@steipete

steipete commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui extensions: memory-core Extension: memory-core maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. 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