GeezerVison is showing github.com — fix(sse): prevent memory leak from zombie SSE connections by zhumengzhu · Pull Request #22552 · anomalyco/opencode
Conversation
zhumengzhu
commented
Apr 15, 2026
•
edited
Loading
Uh oh!
There was an error while loading. Please reload this page.
Issue for this PR
Closes #22198, closes #22422.
Type of change
What does this PR do?
Root cause: adapter.bun.ts sets idleTimeout: 0, disabling Bun's idle timeout
entirely. When an SSE connection enters TCP CLOSE_WAIT (Electron shell reconnecting on
minimize/restore, or a reverse proxy swallowing the client FIN), the server has no
signal that the connection is dead. Three resources leak per zombie connection: the
heartbeat setInterval, the Bus.subscribeAll subscription, and the AsyncQueue.
The queue keeps receiving every Bus event with no consumer draining it — at 66+ zombie
connections this was ~14 MB/sec, peaking at 24.5 GB before OOM.
The finally { stop() } block does not help — for await is suspended on q.next()
which returns a Promise that never resolves when the queue has no consumer.
Five changes:
-
adapter.bun.ts: idleTimeout: 0 → 120 — the root fix. Bun's idle timeout
fires after 120s of no successful writes, aborting Request.signal and triggering
cleanup. The 10s heartbeat resets the timer on every beat for active connections, so
live connections are never affected.
-
c.req.raw.signal.addEventListener("abort", stop) in event.ts and global.ts
— adds an independent cleanup path that fires before stream.onAbort on direct
connections (~2ms earlier). Hono gates this listener behind isOldBunVersion() and
skips it on Bun 1.2+; we add it unconditionally.
-
writeSSE wrapped in try/catch in the same files — kept for forward
compatibility if a future Hono version propagates write errors. Hono 4.x
StreamingApi.write() has an empty catch block so this does not fire on the current
version (noted in code comments).
-
AsyncQueue capacity limit (default 1000, drop oldest on overflow) — defensive
backstop so growth is bounded even if a cleanup signal is missed.
-
GlobalBus.setMaxListeners(100) — each SSE connection adds one listener; the
default of 10 causes MaxListenersExceededWarning under normal usage.
Reproduction attempt and detailed analysis: https://gist.github.com/zhumengzhu/091076a04491762659c3cd210d02cee7
Inspired by #18395 and #15646, both closed without merging.
How did you verify your code works?
- Full test suite: 1890 pass, 1 fail (the failure is pre-existing on
upstream/dev
before any changes — same result on unmodified upstream)
- Local reproduction attempt with nginx
proxy_ignore_client_abort on (20 SSE
connections, kill all clients, monitor VmRSS for 120s) — detailed in the gist above
- Signal timing instrumentation to verify
req.raw.signal vs stream.onAbort firing
order in both direct and proxied scenarios
Screenshots / recordings
N/A — server-side memory fix
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.
|
Thanks for updating your PR! It now meets our contributing guidelines. 👍
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Root cause: adapter.bun.ts explicitly set idleTimeout: 0, disabling
Bun's idle timeout entirely. When connections enter TCP CLOSE_WAIT
(reverse proxy or Electron shell swallowing client FIN), the server
has no signal that the connection is dead — three resource classes
leak permanently: AsyncQueue grows without bound (14 MB/s, peak
24.5 GB), setInterval heartbeats keep ticking, Bus subscriptions
are never cancelled.
Five changes:
- server/adapter.bun.ts: idleTimeout: 0 → 120. Heartbeat interval
is 10s so active connections reset the timer on every beat and are
never killed; dead connections are cleaned up within 120s
- server/instance/event.ts: register c.req.raw.signal abort listener
as a second cleanup path independent of responseReadable.cancel().
Hono skips this listener on Bun 1.2+ (isOldBunVersion gate); we
add it unconditionally. writeSSE try/catch kept for forward
compatibility — Hono 4.x write() has an empty catch so this block
does not fire on the current version
- server/instance/global.ts: same two changes applied to streamEvents()
- util/queue.ts: add capacity limit (default 1000), drop oldest entry
on overflow — defensive backstop so growth is bounded even if a
cleanup signal is missed
- bus/global.ts: setMaxListeners(100) — fixes anomalyco#22422
MaxListenersExceededWarning; each SSE connection adds one listener,
default limit of 10 is too low for normal concurrent usage
Fixes anomalyco#22198, fixes anomalyco#22422
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
|
On not adding an application-layer idle timeout check
A few comments in #22198 (AlexZander85) suggested tracking lastConsumed and calling
stop() if no heartbeat has been consumed in N seconds. We considered this but did not
implement it for two reasons:
-
idleTimeout: 120 already provides this guarantee at the right layer. Bun's
idle timeout fires when no data has been successfully written for 120s. With a 10s
heartbeat, active connections reset the timer on every beat and are never affected.
Dead connections stop resetting the timer once the downstream TCP buffer fills, and
are cleaned up within 120s. This is the same signal, handled at the transport layer
where it belongs.
-
Application-layer detection has no reliable signal. writeSSE appears to
succeed even on dead connections — Hono 4.x StreamingApi.write() has an empty
catch block, so write failures are invisible to the caller. The only application-
layer proxy for "was data consumed" is WritableStreamDefaultWriter.desiredSize,
which only turns negative after the downstream TCP buffer is full — by which point
idleTimeout would fire anyway.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Relationship with #20642
PR #20642 (by @jwcrystal) redesigns
AsyncQueue with a capacity parameter, a close() method, and a sentinel value —
a more complete queue interface that also caps memory growth.
The two PRs are complementary and do not overlap:
If #20642 is merged first, the AsyncQueue changes here would need rebasing against
its interface, but the rest of the changes in this PR are independent.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Covers: basic FIFO order, oldest-entry eviction on overflow, queue
length never exceeds limit, direct-resolver bypass, null sentinel
termination, and zombie scenario (10000 pushes, no consumer).
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
|
Hey @thdxr — would appreciate a review when you get a chance. This fixes the unbounded memory growth in #22198 by restoring Bun's idle timeout (idleTimeout: 0 → 120), which is the only path that cleans up zombie SSE connections under a reverse proxy or Electron shell reconnect.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
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.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
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.
|