GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix: resolve memory leak issues across multiple subsystems by kryptobaseddev · Pull Request #14650 · anomalyco/opencode

Conversation

@kryptobaseddev

@kryptobaseddev kryptobaseddev commented Feb 22, 2026

Copy link
Copy Markdown

Issue for this PR

Closes #9385
Relates to #7046, #9151

Type of change

  • Bug fix

What does this PR do?

Fixes 10 of the 15 memory leak sources tracked across issues #9385, #7046, #9151, and PR #14635. The two dominant drivers of unbounded RSS growth were subagent sessions never being deallocated (I-9385-A) and message delta strings accumulating without any cap (event-reducer). Together these caused observed GB-scale growth in long-running sessions.

Changes by file:

Subagent deallocation (tool/task.ts) — Call Session.remove() after extracting the subagent task output. This fires session.deleted, which triggers the existing cleanupSessionCaches() in the event-reducer, freeing all in-memory messages, parts, and status entries for completed subagent sessions. Resume via task_id degrades gracefully (creates a fresh session).

Delta string cap (event-reducer.ts) — Cap accumulated part field strings at 1 MB. On overflow the oldest bytes are dropped via slice(). This was the single largest contributor to absolute heap size.

Tool output on compact (compaction.ts) — When prune() compacts tool parts, clear state.output and state.attachments from both the DB row and in-memory store. toModelMessages already substituted placeholder text for compacted parts; this aligns stored data with that behavior.

SSE buffer guard (serverSentEvents.gen.ts, v1 + v2) — Add a 10 MB MAX_BUFFER_SIZE check before each buffer += value. Throws on overflow instead of growing unbounded during stalled or malformed streams.

MCP OAuth transport TTL (mcp/index.ts) — Replace bare Map.set/delete with helpers that attach a 5-minute auto-eviction timer per pending OAuth transport entry. Stale entries from failed or abandoned auth flows are cleaned up automatically.

Pending permissions cleanup (permission/next.ts, session/index.ts) — Add PermissionNext.clearSession() which rejects and removes all pending permission requests for a given session. Called from Session.remove() before the DB delete, so subagent sessions no longer leave dangling permission entries.

TUI event listener cleanup (app.tsx, routes/session/index.tsx, component/prompt/index.tsx) — Save the unsubscribe functions returned by all 8 sdk.event.on() calls across these three components and call them in onCleanup(). Previously onCleanup was not even imported in app.tsx. The session and prompt components mount/unmount during navigation, so each navigation was adding duplicate listeners.

LSP diagnostics cap (lsp/client.ts) — Enforce a 2,000-file cap on the diagnostics Map and a 1,000-file cap on the open-files tracking object. FIFO eviction on overflow.

AbortSignal listener (sdk/js server.ts, v1 + v2) — Pass { once: true } to the abort listener added during startup so it self-removes after firing.

How did you verify your code works?

Built a standalone binary (./packages/opencode/script/build.ts --single) and ran it against a real project for 2.5 hours with continuous subagent tasks, multi-step tool use, and session switching. Monitored RSS every 10 seconds (875 samples).

Results:

  • Active work phase (first 20 min): RSS grew from 1,889 → 2,507 MB during heavy subagent + tool activity
  • Post-activity: RSS stabilized at ~2,501-2,515 MB and held flat for over 2 hours
  • Subsequent active bursts: Brief spikes (up to 2,572 MB) returned to baseline within minutes
  • Net drift over 2.5 hours idle+active: ~8 MB (normal GC-managed creep, not a leak)
  • VSZ completely flat at 80,467 MB after initial loading — no new virtual memory allocation

The previous behavior (per issue reports) showed continuous unbounded growth toward 25+ GB RSS under similar workloads.

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

herbievine reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
kryptobaseddev and others added 2 commits February 21, 2026 20:58
@kryptobaseddev @claude
fix: resolve memory leak issues across multiple subsystems
d0f1c66
Addresses 6 of the 10 open issues from the memory-leak work plan
(L-01, L-02, L-03, L-04, I-7046-B, I-7046-D).

L-01 (CRITICAL) — event-reducer.ts: cap accumulated delta string at 1 MB
per part field; drops oldest bytes on overflow rather than growing the
V8 heap without bound. Primary driver of observed 25 GB RSS growth.

L-02 (CRITICAL) — serverSentEvents.gen.ts (v1 + v2): guard the SSE
read loop with a 10 MB MAX_BUFFER_SIZE; throws BufferOverflowError
before the string can grow unbounded during stalled or large streams.

L-03 (HIGH) — mcp/index.ts: replace bare pendingOAuthTransports.set/
delete with helper functions that attach a 5-minute TTL timer per
entry. Stale transports from abandoned or failed OAuth flows are now
automatically evicted. Timer state is cleared on state teardown.

L-04 (LOW) — sdk/js server.ts (v1 + v2): pass { once: true } to the
AbortSignal "abort" listener added during server startup. The listener
is now auto-removed after firing, eliminating long-lived accumulation
on signals that outlive the startup promise.

I-7046-B (HIGH) — lsp/client.ts: enforce a 2 000-file cap on the
diagnostics Map and a 1 000-file cap on the open-files tracking
object. Oldest entries are evicted (FIFO) on overflow; evicted files
re-open cleanly on next access.

I-7046-D (MEDIUM) — permission/next.ts + session/index.ts: add
PermissionNext.clearSession(sessionID) which rejects and removes all
pending permission requests keyed to a session. Session.remove() now
calls clearSession() before the DB delete, so short-lived subagent
sessions no longer leave dangling permission entries.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@kryptobaseddev @claude
fix: subagent deallocation, compaction output retention, TUI listener…
fe65e5a
… leaks

Addresses the 4 remaining high-priority memory leak issues from the
work plan (I-9385-A, I-7046-A, PR-14635, I-7046-C partial).

I-9385-A (CRITICAL, Priority anomalyco#1) — tool/task.ts: call Session.remove()
after extracting subagent task output. This fires the session.deleted
event, which triggers cleanupSessionCaches() in the event-reducer —
freeing all in-memory messages, parts, diffs, permissions, and status
for the subagent session. The task_id in the output becomes a dead
reference; if the LLM tries to resume, Session.get() fails gracefully
and a fresh session is created. Validated: the cleanup infrastructure
already existed but was never invoked for subagent sessions.

I-7046-A (CRITICAL, Priority anomalyco#3) — session/compaction.ts: clear
part.state.output and part.state.attachments when pruning compacted
tool parts. Previously, prune() set time.compacted but left the full
output string in both the DB row and the in-memory store.
toModelMessages already substituted "[Old tool result content cleared]"
for compacted parts — this change aligns stored data with that
behavior, freeing the large strings from memory and disk.

PR-14635 (HIGH, Priority anomalyco#4) — TUI event listener cleanup:
- app.tsx: save the unsubscribe functions returned by all 6
  sdk.event.on() calls; call them in a single onCleanup() handler.
  Previously, onCleanup was not even imported.
- routes/session/index.tsx: save and clean up the message.part.updated
  listener. This component mounts/unmounts during session navigation,
  so each navigation previously added a duplicate listener.
- component/prompt/index.tsx: save and clean up the PromptAppend
  listener. Same mount/unmount pattern as the session component.

I-7046-C (partial) — the TUI event listener fixes above cover the
most impactful instances of the missing-dispose pattern. A full audit
of all subscribe() call sites remains as follow-up work.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@kryptobaseddev
kryptobaseddev requested a review from adamdotdevin as a code owner February 22, 2026 08:39
@github-actions

github-actions Bot commented Feb 22, 2026

Copy link
Copy Markdown
Contributor

The following comment was made by an LLM, it may be inaccurate:

Based on my search, I found several related PRs that address memory leak issues. Here are the potential duplicates or related work:

Related/Potentially Duplicate PRs:

  1. PR fix: address 6 memory leaks for long-running sessions #13594 - "fix: address 6 memory leaks for long-running sessions"

    • Related to the same issue domain (long-running sessions with memory leaks)
  2. PR fix: resolve multiple memory leaks causing unbounded RAM growth ( Now passing: && Fixed failing tests for windows ) #13514 - "fix: resolve multiple memory leaks causing unbounded RAM growth"

    • Directly addresses unbounded RAM growth, same core issue as PR fix: resolve memory leak issues across multiple subsystems #14650
  3. PR fix(mcp): Fix memory leaks in OAuth transport and process cleanup #9145 - "fix(mcp): Fix memory leaks in OAuth transport and process cleanup"

    • Related to MCP OAuth transport TTL mentioned in PR fix: resolve memory leak issues across multiple subsystems #14650
  4. PR fix(memory): Fix event listener leaks in TUI and Slack bot #9147 - "fix(memory): Fix event listener leaks in TUI and Slack bot"

    • Related to TUI event listener cleanup mentioned in PR fix: resolve memory leak issues across multiple subsystems #14650
  5. PR fix(memory): Fix timeout, interval, and subscription cleanup #9148 - "fix(memory): Fix timeout, interval, and subscription cleanup"

    • Related to cleanup mechanisms similar to those in PR fix: resolve memory leak issues across multiple subsystems #14650
  6. PR fix(disposal): Complete Instance disposal chain for plugins and caches #9149 - "fix(disposal): Complete Instance disposal chain for plugins and caches"

    • Related to session cleanup and disposal patterns

Recommendation: Check PR #13514 and #13594 first, as they address very similar unbounded growth and long-running session memory leak issues. They may be earlier attempts or competing solutions for the same problems being fixed in PR #14650.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

This was referenced Feb 22, 2026
Memory leak #9385
Closed
memory leak #7046
Closed
Memory leak #9151
Closed
@github-actions github-actions Bot mentioned this pull request Feb 22, 2026
fix(core): clear tool output and attachments on compaction prune #14693
Closed
3 of 6 tasks
@kryptobaseddev kryptobaseddev mentioned this pull request Feb 23, 2026
fix: clear tool output and attachments when pruning to prevent memory leak #7049
Closed
@github-actions github-actions Bot mentioned this pull request Feb 27, 2026
fix(web): dispose idle MCP server instances to prevent process accumulation #15326
Closed
3 of 6 tasks
tda1017 pushed a commit to tda1017/opencode that referenced this pull request Feb 28, 2026
@kryptobaseddev root
fix: resolve 10 memory leak sources across multiple subsystems
6efcd20
Fixes subagent session deallocation, delta string cap, tool output on compact,
SSE buffer guard, MCP OAuth transport TTL, pending permissions cleanup,
TUI event listener cleanup, LSP diagnostics cap, and AbortSignal listener.

Original work from PR anomalyco#14650 by @kryptobaseddev
Co-authored-by: Keaton Hoskins <[email protected]>
@tda1017 tda1017 mentioned this pull request Feb 28, 2026
fix: consolidate memory leak fixes from #14650 and #8953 #15435
Closed
3 of 6 tasks
@tda1017

tda1017 commented Feb 28, 2026

Copy link
Copy Markdown

Hi @kryptobaseddev, I've been experiencing the memory leak issues and found your excellent fix here. Since this PR has been open for a while, I created a consolidated PR (#15435) that includes your work along with @cgwalters's bash streaming fix from #8953.

I've properly attributed all your work with Co-authored-by tags and explicit credit in the PR description. Hope this helps get these important fixes merged faster. Thank you for the thorough investigation and fix!

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@tda1017 tda1017 mentioned this pull request Feb 28, 2026
feat(bash): stream large output to tmpfile with filtering and GC #8953
Closed
This was referenced Mar 2, 2026
fix: prevent memory leaks from SSE streams, LSP, Bus, and process cleanup #15646
Closed
fix: clear tool output and attachments during compaction prune #16162
Closed
fix(opencode): unbounded memory growth during active usage #16346
Closed
fix: add idle-timeout Instance disposal for serve mode memory #16616
Closed
@binarydoubling

binarydoubling commented Mar 9, 2026

Copy link
Copy Markdown

FYI there are now multiple PRs tackling memory leaks from different angles — #16695 (TUI listener cleanup, Maps/Sets eviction, timer cleanup), #16730 (database bloat, SQLite config), #16346 (plugin subscriber stacking, msgs retention). Lots of overlap across all of these on files like lsp/client.ts, app.tsx, session/index.tsx. Might be worth coordinating merges to avoid conflict hell.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@binarydoubling binarydoubling mentioned this pull request Mar 9, 2026
Multiple memory leaks cause unbounded RAM growth during extended TUI usage #16697
Closed
@binarydoubling binarydoubling mentioned this pull request Mar 9, 2026
fix: resolve multiple memory leaks causing unbounded growth #16695
Closed
3 of 6 tasks
brendandebeasi pushed a commit to brendandebeasi/opencode that referenced this pull request Mar 10, 2026
@binarydoubling @claude Brendan DeBeasi
fix: consolidate memory leak fixes from 23+ community PRs
0fab91b
Addresses the remaining memory leaks identified in anomalyco#16697 by
consolidating the best fixes from 23+ open community PRs into
a single coherent changeset.

Fixes consolidated from PRs: anomalyco#16695, anomalyco#16346, anomalyco#14650, anomalyco#15646,

- Plugin subscriber stacking: unsub before re-subscribing in init()
- Subagent deallocation: Session.remove() after task completion
- SSE stream cleanup: centralized cleanup with done guard (3 endpoints)
- Compaction data trimming: clear output/attachments on prune
- Process exit cleanup: Instance.disposeAll() with 5s timeout
- Serve cmd: graceful shutdown instead of blocking forever
- Bash tool: ring buffer with 10MB cap instead of O(n²) concat
- LSP index teardown: clear clients/broken/spawning on dispose
- LSP open-files cap: evict oldest when >1000 tracked files
- Format subscription: store and cleanup unsub handle
- Permission/Question clearSession: reject pending on session delete
- Session.remove() cleanup chain: FileTime, Permission, Question
- ShareNext subscription cleanup: store unsub handles, cleanup on dispose
- OAuth transport: close existing before replacing

Co-Authored-By: Claude Opus 4.6 <[email protected]>
binarydoubling added a commit to binarydoubling/opencode that referenced this pull request Mar 13, 2026
@binarydoubling @claude
fix: consolidate memory leak fixes from 23+ community PRs
5124d2a
Addresses the remaining memory leaks identified in anomalyco#16697 by
consolidating the best fixes from 23+ open community PRs into
a single coherent changeset.

Fixes consolidated from PRs: anomalyco#16695, anomalyco#16346, anomalyco#14650, anomalyco#15646,

- Plugin subscriber stacking: unsub before re-subscribing in init()
- Subagent deallocation: Session.remove() after task completion
- SSE stream cleanup: centralized cleanup with done guard (3 endpoints)
- Compaction data trimming: clear output/attachments on prune
- Process exit cleanup: Instance.disposeAll() with 5s timeout
- Serve cmd: graceful shutdown instead of blocking forever
- Bash tool: ring buffer with 10MB cap instead of O(n²) concat
- LSP index teardown: clear clients/broken/spawning on dispose
- LSP open-files cap: evict oldest when >1000 tracked files
- Format subscription: store and cleanup unsub handle
- Permission/Question clearSession: reject pending on session delete
- Session.remove() cleanup chain: FileTime, Permission, Question
- ShareNext subscription cleanup: store unsub handles, cleanup on dispose
- OAuth transport: close existing before replacing

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions github-actions Bot mentioned this pull request Mar 15, 2026
fix: remove dead LSP clients to prevent unbounded memory growth #17635
Closed
3 of 6 tasks
@herbievine

herbievine commented Mar 16, 2026

Copy link
Copy Markdown

+1 please! running this in server mode and we reach 10GiB of memory very quickly

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions github-actions Bot mentioned this pull request Mar 16, 2026
fix(run): await loop() before instance disposal #17825
Closed
3 tasks done
rubend056 pushed a commit to rubend056/opencode that referenced this pull request Mar 18, 2026
@binarydoubling @claude @rubend056
fix: consolidate memory leak fixes from 23+ community PRs
191dd2f
Addresses the remaining memory leaks identified in anomalyco#16697 by
consolidating the best fixes from 23+ open community PRs into
a single coherent changeset.

Fixes consolidated from PRs: anomalyco#16695, anomalyco#16346, anomalyco#14650, anomalyco#15646,

- Plugin subscriber stacking: unsub before re-subscribing in init()
- Subagent deallocation: Session.remove() after task completion
- SSE stream cleanup: centralized cleanup with done guard (3 endpoints)
- Compaction data trimming: clear output/attachments on prune
- Process exit cleanup: Instance.disposeAll() with 5s timeout
- Serve cmd: graceful shutdown instead of blocking forever
- Bash tool: ring buffer with 10MB cap instead of O(n²) concat
- LSP index teardown: clear clients/broken/spawning on dispose
- LSP open-files cap: evict oldest when >1000 tracked files
- Format subscription: store and cleanup unsub handle
- Permission/Question clearSession: reject pending on session delete
- Session.remove() cleanup chain: FileTime, Permission, Question
- ShareNext subscription cleanup: store unsub handles, cleanup on dispose
- OAuth transport: close existing before replacing

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions github-actions Bot mentioned this pull request Apr 7, 2026
fix: bash tool memory leak #21321
Closed
3 tasks done
@opencode-agent
opencode-agent Bot force-pushed the dev branch from 2f2ed11 to 9f201d6 Compare April 16, 2026 21:55
@rekram1-node

rekram1-node commented May 15, 2026

Copy link
Copy Markdown
Member

Automated PR Cleanup

Thank you for contributing to opencode.

Due to the high volume of PRs from users and AI agents, we periodically close older PRs using automated criteria so maintainers can focus review time on the most active and community-supported contributions.

This PR was closed because it matched the following cleanup criteria:

  • The PR was created more than 1 month ago
  • The PR had fewer than 2 positive reactions
  • Positive reactions are counted as thumbs-up, heart, celebration, or rocket reactions on the PR

PRs created within the last month are not affected by this cleanup.

If you believe this PR was closed incorrectly, or if you are still actively working on it, please leave a comment explaining why it should be reopened. A maintainer can review and reopen it if appropriate.

Thanks again for taking the time to contribute.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@rekram1-node rekram1-node closed this May 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@adamdotdevin adamdotdevin Awaiting requested review from adamdotdevin

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Memory leak

Uh oh!

There was an error while loading. Please reload this page.

5 participants

@kryptobaseddev @tda1017 @binarydoubling @herbievine @rekram1-node
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.