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: prevent memory leaks from SSE streams, LSP, Bus, and process cleanup by brendandebeasi · Pull Request #15646 · anomalyco/opencode

Conversation

@brendandebeasi

@brendandebeasi brendandebeasi commented Mar 2, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown

Issue for this PR

Fixes #15645
Relates to #10913, #9140, #11696, #9156, #14091, #15592

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

Fixes multiple memory leaks that cause OpenCode's memory usage to grow unbounded over time, particularly during long-running sessions.

Memory leak fixes (always active)

Fix Issues File Change
SSE cleanup #15645 server.ts, global.ts, routes.ts done flag + writeSSE error handling + unsub on abort
LSP shutdown #10913, #9140 client.ts diagnostics.clear() + reset files Map in shutdown
Bus dispose #10913 bus/index.ts subscriptions.clear() after dispose callback
ACP stdin #11696 acp.ts .on() → .once() for end/error listeners
GitHub unsub #9156 github.ts Capture + call Bus.subscribe return in finally block
Process exit #10913, #14091 index.ts Instance.disposeAll() with 5s timeout before process.exit()

Debug tooling (always available, zero overhead)

  • Bus.debug() — subscription count introspection per event type
  • Instance.debug() — cache state inspection
  • State.debug() — state entry counts
  • GET /debug/memory — on-demand runtime memory diagnostics endpoint
  • SIGUSR1 signal — captures heap snapshot + diagnostic report to ~/.local/share/opencode/diagnostics/

Memory monitoring (opt-in via OPENCODE_DIAGNOSTICS=1)

The polling monitor and auto-kill are disabled by default. To enable:

OPENCODE_DIAGNOSTICS=1 opencode

When enabled:

  • 30s polling interval checks RSS usage
  • 2GB warning — logs heap stats + writes periodic diagnostic reports (60s cooldown)
  • 4GB kill (configurable via OPENCODE_MEMORY_LIMIT=N in GB) — writes heap snapshot + diagnostic report, then exits
  • Kill threshold formula: max(2GB, min(25% total RAM, 4GB))

How did you verify your code works?

  • All modified files pass LSP diagnostics
  • Type errors are pre-existing (3 TUI errors: Property 'tui' does not exist on type 'Config' — unrelated to this PR)
  • Diagnostics opt-in verified: without OPENCODE_DIAGNOSTICS=1, only SIGUSR1 handler is registered (no polling, no kill)
  • With OPENCODE_DIAGNOSTICS=1, full monitoring loop activates

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
@github-actions

github-actions Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor

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

Potential duplicate/related PRs found:

  1. fix: consolidate memory leak fixes from #14650 and #8953 #15435 - "fix: consolidate memory leak fixes from fix: resolve memory leak issues across multiple subsystems #14650 and feat(bash): stream large output to tmpfile with filtering and GC #8953"

    • Related to memory leak fixes with potential overlap in SSE/Bus listener cleanup scope
  2. fix: resolve memory leak issues across multiple subsystems #14650 - "fix: resolve memory leak issues across multiple subsystems"

    • Addresses broader memory leak issues that may include SSE stream handling
  3. fix(core): add dispose functions to prevent subscription memory leaks #7032 - "fix(core): add dispose functions to prevent subscription memory leaks"

    • Earlier work on subscription memory leak prevention that may be relevant to Bus listener cleanup

These PRs all address memory leak issues in similar areas. Review #15435 and #14650 particularly to ensure the SSE stream cleanup in PR #15646 doesn't duplicate existing fixes or conflict with prior memory leak consolidation efforts.

All reactions

Sorry, something went wrong.

Uh oh!

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

@brendandebeasi

brendandebeasi commented Mar 2, 2026

Copy link
Copy Markdown
Author

Reviewed the related PRs flagged above — this PR is complementary, not duplicative:

  • fix: consolidate memory leak fixes from #14650 and #8953 #15435 and fix: resolve memory leak issues across multiple subsystems #14650 address memory leaks in session management, LSP, MCP, event-reducer, and SDK SSE client-side handling. Neither touches the server-side SSE stream handlers in server.ts or routes/global.ts.
  • fix(core): add dispose functions to prevent subscription memory leaks #7032 adds dispose() functions and Bus subscription test helpers. It adds _getSubscriptionCount() / _getTotalSubscriptionCount() to bus/index.ts — our Bus.debug() is in the same area but serves a different purpose (runtime diagnostics vs test helpers). Minor merge conflict at worst, easy to resolve.

The core fix in this PR — awaiting writeSSE() calls, catching write errors to detect dead connections, and cleaning up Bus listeners + heartbeat intervals on failure — is not addressed by any of the other open PRs. Those PRs fix leaks in other subsystems; this one fixes the SSE stream handler leak path specifically.

herbievine reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

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

@brendandebeasi
brendandebeasi force-pushed the fix/sse-memory-leaks branch from 1f990f0 to 11eef33 Compare March 3, 2026 18:52
@brendandebeasi brendandebeasi changed the title fix: prevent SSE stream memory leaks on client disconnect fix: prevent memory leaks from SSE streams, LSP, Bus, and process cleanup Mar 3, 2026
@brendandebeasi
brendandebeasi force-pushed the fix/sse-memory-leaks branch 2 times, most recently from 66587a7 to 5788c8b Compare March 3, 2026 19:21
@github-actions github-actions Bot mentioned this pull request Mar 6, 2026
fix(opencode): unbounded memory growth during active usage #16346
Closed
3 of 6 tasks
@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), #14650 (subagent deallocation, event-reducer caps). Lots of file overlap across all of these. 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
brendandebeasi force-pushed the fix/sse-memory-leaks branch from 5788c8b to a275bde Compare March 10, 2026 04:54
Brendan DeBeasi and others added 7 commits March 10, 2026 16:24
Brendan DeBeasi
fix: prevent SSE stream memory leaks on client disconnect
f7a1974
- Add cleanup() guard with done flag to prevent double-cleanup
- await stream.writeSSE() calls and catch errors to trigger cleanup
- Unsubscribe Bus and GlobalBus listeners on abort or write failure
- Clear heartbeat interval in all exit paths
- Add Bus.debug() subscription count introspection
- Add GET /debug/memory endpoint for runtime memory diagnostics
@binarydoubling @claude Brendan DeBeasi
fix: resolve multiple memory leaks causing unbounded growth
58ae016
- Cap SDK event queue to prevent unbounded growth during high event throughput
- Clean up message parts when trimming excess messages in sync store
- Evict previous session data from memory when switching sessions
- Bound LSP diagnostics map with LRU eviction and clear on shutdown
- Reject pending callbacks on session cancel to prevent promise/closure leaks

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@binarydoubling @claude Brendan DeBeasi
fix: additional memory leak fixes across TUI, bus, PTY, and core
abe853d
- Add onCleanup for all sdk.event.on() listeners in app.tsx, session route,
  and prompt component to prevent listener accumulation on re-render
- Add onCleanup for process SIGUSR2 handler in theme provider
- Add onCleanup for leader timeout in keybind provider
- Clear event queue on SDK context cleanup
- Remove empty subscription arrays in Bus and RPC listener maps
- Clear warning timeout in state disposal after completion
- Clear models refresh interval on process exit
- Add dispose() to ShareNext to clear pending sync timeouts
- Clear PTY session buffer on removal to free memory immediately

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@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 @NachoFLizaur Brendan DeBeasi
fix: add robust process exit detection for child processes
1702fb1
Port robust process exit detection from PR anomalyco#15757 to fix zombie/stuck
child processes in containers where Bun fails to deliver exit events.

- Add polling watchdog to bash tool and Process.spawn that detects
  process exit via kill(pid, 0) when event-loop events are missed
- Add process registry (active map) with stale/reap exports for
  server-level watchdog to detect and clean up stuck bash processes
- Improve Shell.killTree with alive() helper and proper SIGKILL
  escalation after SIGTERM timeout
- Add session-level watchdog interval in prompt loop to periodically
  reap stale bash processes

Based on the work in anomalyco#15757.

Co-Authored-By: Nacho F. Lizaur <[email protected]>
@binarydoubling @NachoFLizaur Brendan DeBeasi
fix: add stdio end event fallback, diagnostic logging, and tests
293b2de
Complete the port of PR anomalyco#15757 with remaining pieces:

- Add stdio end event redundancy as third fallback for exit detection
  (fires when pipe file descriptors close, independent of exit events)
- Add diagnostic log.info calls at spawn, abort, timeout, and each
  exit detection path for debugging container issues
- Add comprehensive tests: defensive patterns, polling watchdog
  isolation, Shell.killTree, server-level watchdog (stale/reap),
  stdio end events, and Process.spawn defensive patterns
- Skip truncation tests on Windows (matching upstream)

Co-Authored-By: Nacho F. Lizaur <[email protected]>
@binarydoubling @NachoFLizaur Brendan DeBeasi
fix: handle null exitCode when stdio end events resolve first
491b449
On Windows, stdio pipe end events can fire before the exit event
populates proc.exitCode, causing it to be null in the result metadata.
Fall back to 0 (or 1 if signalCode is set) when exitCode is null,
matching the same pattern used in Process.spawn.

Co-Authored-By: Nacho F. Lizaur <[email protected]>
@brendandebeasi
brendandebeasi force-pushed the fix/sse-memory-leaks branch from a275bde to 491b449 Compare March 10, 2026 23:28
@github-actions github-actions Bot mentioned this pull request Mar 11, 2026
📊 Bản tin hàng ngày công cụ AI CLI 2026-03-11 compasify/agents-radar#25
Open
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]>
Brendan DeBeasi added 2 commits March 13, 2026 13:59
Brendan DeBeasi
merge dev into fix/sse-memory-leaks
33c669b
Brendan DeBeasi
fix: iterate pending maps with map APIs
3328fd5
@github-actions github-actions Bot mentioned this pull request Mar 14, 2026
📊 Bản tin hàng ngày công cụ AI CLI 2026-03-14 compasify/agents-radar#40
Open
@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.

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]>
@brendandebeasi

brendandebeasi commented Mar 20, 2026

Copy link
Copy Markdown
Author

Closing — the memory leak issues addressed here have been resolved upstream via the Effect service migration wave (effectified services with proper cleanup, scoped layers, etc.). Thanks for the reviews!

All reactions

Sorry, something went wrong.

Uh oh!

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

@brendandebeasi brendandebeasi closed this Mar 20, 2026
@zhumengzhu zhumengzhu mentioned this pull request Apr 15, 2026
fix(sse): prevent memory leak from zombie SSE connections #22550
Closed
This was referenced Apr 15, 2026
fix(sse): prevent memory leak from zombie SSE connections #22551
Closed
fix(sse): prevent memory leak from zombie SSE connections #22552
Closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

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.

SSE event streams leak memory on client disconnect

Uh oh!

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

3 participants

@brendandebeasi @binarydoubling @herbievine
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.