t3code icon indicating copy to clipboard operation
t3code copied to clipboard

Unbounded WebSocket fanout queues and un-cleared bufferedEvents closure in TerminalManager.subscribeMetadata leak memory

Open mateodelcon1 opened this issue 4 days ago • 1 comments

What happened

Two server-side subscription paths retain unbounded memory for the lifetime of connected clients:

  1. TerminalManager.subscribeMetadata buffers raw TerminalEvent objects (including large PTY output chunks) during initial snapshot handoff and never clears bufferedEvents afterward, pinning those chunks in the closure for the entire WebSocket connection lifetime.
  2. Per-subscriber WebSocket fanout queues in ws.ts use Queue.unbounded, allowing slow or stalled remote clients to grow server memory without bound.

Diagnosis

  1. In apps/server/src/terminal/Manager.ts (lines 3924–3967):
    • bufferedEvents: TerminalEvent[] captures every event (not just metadata events) emitted while readAllTerminalMetadata() and the initial snapshot send are in flight.
    • After draining bufferedEvents, deliverLive flips to true, but bufferedEvents is still referenced by the subscribe callback closure and is never emptied (bufferedEvents.length = 0). Any raw output chunks captured during subscribe stay retained until the subscriber disconnects.
  2. In apps/server/src/ws.ts (lines 3711–3752):
    • WS_METHODS.subscribeServerLifecycle (line 3714) and WS_METHODS.subscribeAuthAccess (line 3734) back per-subscriber live buffers with Queue.unbounded, giving no backpressure or sliding/drop cap when a client connection falls behind.

Steps to reproduce

  1. Run a noisy terminal producing continuous PTY output.
  2. Connect and disconnect/hold WebSocket clients subscribing to terminal metadata (subscribeMetadata) and server fanout streams (especially over a throttled connection).
  3. Inspect heap retention: the bufferedEvents array inside subscribeMetadata's closure retains raw terminal output chunks for the socket's entire lifetime, and slow WS subscribers grow unbounded queues.

Version

0.1.13 (also confirmed on main @ 9a66ff1e and c203d933)

Environment

Windows 10/11 (NT 10.0.26300), Node v26.13.1 (platform-independent server logic in apps/server)

Evidence

// apps/server/src/terminal/Manager.ts (lines 3928-3954)
const bufferedEvents: TerminalEvent[] = [];
let deliverLive = false;

unsubscribe = yield* subscribe((event) => {
  if (!deliverLive) {
    bufferedEvents.push(event);
    return Effect.void;
  }

  return offerMetadataEvent(listener, event);
});

const terminals = yield* readAllTerminalMetadata();
yield* listener({ type: "snapshot", terminals, managerId });

for (const event of bufferedEvents) {
  yield* offerMetadataEvent(listener, event);
}

deliverLive = true;
// bufferedEvents is never cleared while still captured by the subscribe closure above

Related issues

No matching open issue found for subscribeMetadata closure retention or ws.ts unbounded fanout queues.

Fix applied or workaround

None applied to live install. Filtering to metadata events before buffering and setting bufferedEvents.length = 0 immediately after draining fixes the TerminalManager leak, and replacing Queue.unbounded with bounded/sliding queues in ws.ts caps per-subscriber memory.

Filed by

Antigravity (gemini-4-neon) via t3 triage playbook

mateodelcon1 avatar Nov 27 '26 23:11 mateodelcon1

I tried to reproduce this on the current build and could not.

Commit 93955ac9bd (origin/main). Started the dev server with T3CODE_DEV_SEED=0 and NODE_OPTIONS=--inspect so I could read the server process's heap. Paired the web app in the preview browser and opened a terminal in a thread. In it I ran while true; do echo LEAKMARK_$RANDOM$RANDOM; done, which kept bash at about 75% CPU with continuous PTY output. While that ran, I reconnected the web client several times by reloading the page; each reload makes a new subscribeTerminalMetadata subscription on the server. After each reconnect, a driver script forced a GC over CDP, took a heap snapshot and listed every closure context that holds a bufferedEvents variable next to deliverLive (the subscribeMetadata closure), with the number of events and output characters it holds. I first checked the parser against a control process holding 5 buffered events, and it found all 5. Results on the server: before the terminal started there were 3 live metadata closures, each with 0 events. After the reconnects, the one live metadata closure (subscribed while the PTY was busy) held 0 events. Its array had never been written to (no elements backing store), across 3 separate snapshots. The terminal output strings the heap did retain were held elsewhere (normal scrollback), not by bufferedEvents. The reason: subscribe(), readAllTerminalMetadata() (a SynchronizedRef.get) and the snapshot Queue.offer all run synchronously in one fiber step. PTY data arrives on separate macrotasks, so it cannot land in that window in practice. Even if a few events did land, the array is filled only before deliverLive flips and is released on disconnect, so it cannot grow. For ws.ts: the subscribeServerLifecycle queue is fed only by welcome, ready and legacyThreadMigration events (a handful per server lifetime, apps/server/src/serverLifecycleEvents.ts). The subscribeAuthAccess queue is fed by pairing and session credential changes, which happen at the pace a person acts. Neither has a producer that could make it grow without bound behind a slow client. I did not throttle a socket, because neither queue has a high-rate producer to measure.

Closing as not planned. If it still happens for you, reply with the exact steps and the version you are on and it will be looked at again.

juliusmarminge avatar Nov 28 '26 00:11 juliusmarminge