From 92abd8cfa7a25daf88798f166fb807be432d56f0 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Thu, 2 Jul 2026 17:17:04 -0400 Subject: [PATCH] Cap unbounded terminal output buffers in main and the foreground queue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Field evidence (Discord #performance / #2836): renderer memory climbs to ~1.5 GB and terminals freeze; a force reload does not help until memory recovers. Two unbounded buffers matched that shape: - Main-process pendingData grew by string concatenation without bound while the renderer could not receive (frozen, starved, mid-reload) — main-heap bloat a renderer reload cannot clear. Now capped at 2 MB per PTY: past the cap the buffered bytes are dropped and the entry stays O(1) until the renderer ACKs again, then a droppedOutput sentinel is delivered and the pane repaints from the authoritative main-owned buffer snapshot (existing hidden-output restore path) instead of continuing a stream with a silent gap. - The renderer output scheduler capped only hidden-pane backlogs; the foreground path could queue a visible pane's flood without bound when the drain could not keep up. The 2 MB cap now applies to every foreground enqueue branch too, with a foreground-specific skip notice. Verified: new main-side cap test (starve → flood → sentinel → normal flow resumes), renderer sentinel-to-snapshot-restore test, two foreground scheduler cap tests; full pty/terminal-pane/pane-manager suites (1981 tests) and typecheck pass. Co-authored-by: Orca --- src/main/ipc/pty.test.ts | 64 +++++++++++++++++++ src/main/ipc/pty.ts | 55 ++++++++++++++-- src/preload/api-types.ts | 1 + src/preload/index.ts | 2 + .../terminal-pane/pty-connection.test.ts | 52 ++++++++++++++- .../terminal-pane/pty-connection.ts | 7 ++ .../terminal-pane/pty-dispatcher.ts | 7 ++ .../pane-terminal-output-scheduler.test.ts | 41 ++++++++++++ .../pane-terminal-output-scheduler.ts | 39 +++++++++-- 9 files changed, 255 insertions(+), 13 deletions(-) diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index 1b3301e4e..e564eaed3 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -6742,6 +6742,70 @@ describe('registerPtyHandlers', () => { } }) + it('caps per-PTY pending output while the renderer is starved and heals via a droppedOutput sentinel', async () => { + vi.useFakeTimers() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const mockProc = createMockProc() + spawnMock.mockReturnValue(mockProc.proc) + + try { + registerPtyHandlers(mainWindow as never) + const spawn = (await handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24, + cwd: '/tmp' + })) as { id: string } + const ackData = getPtyAckDataListener() + mainWindow.webContents.send.mockClear() + + // Saturate the renderer in-flight window (512 KB) with no ACKs — the + // frozen/starved-renderer shape from the field reports. + mockProc.emitData('x'.repeat(600 * 1024)) + vi.advanceTimersByTime(8) + for (let index = 0; index < 32; index++) { + vi.advanceTimersByTime(1) + } + + // Keep flooding well past the 2 MB per-PTY pending cap. Main must not + // buffer this unboundedly (previously: unbounded string concat). + mockProc.emitData('y'.repeat(3 * 1024 * 1024)) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + pendingPtyCount: 1, + pendingChars: 0 + }) + + // Later output while dropped must stay O(1), not start re-accumulating. + mockProc.emitData('z'.repeat(64 * 1024)) + expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ + pendingPtyCount: 1, + pendingChars: 0 + }) + + // Renderer recovers and ACKs: the flush must deliver the droppedOutput + // sentinel so the pane repaints from the main-owned snapshot. + mainWindow.webContents.send.mockClear() + ackData(null, { id: spawn.id, charCount: 512 * 1024 }) + vi.advanceTimersByTime(8) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawn.id, + data: '', + droppedOutput: true + }) + + // Fresh output after the sentinel flows normally again. + mainWindow.webContents.send.mockClear() + mockProc.emitData('back to normal') + vi.advanceTimersByTime(8) + expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { + id: spawn.id, + data: 'back to normal' + }) + } finally { + errorSpy.mockRestore() + vi.useRealTimers() + } + }) + it('forwards only actually in-flight bytes to provider ACK backpressure', async () => { vi.useFakeTimers() const acknowledgeDataEvent = vi.fn() diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index 9f654ea1e..0b08c4ace 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -1352,6 +1352,7 @@ export function registerPtyHandlers( data: string startSeq?: number containsBackgroundOutput?: boolean + droppedOutput?: true } type PtyDataPayload = { @@ -1360,6 +1361,7 @@ export function registerPtyHandlers( seq?: number rawLength?: number background?: boolean + droppedOutput?: boolean } const pendingData = new Map() @@ -1373,6 +1375,12 @@ export function registerPtyHandlers( const PTY_BATCH_FLUSH_MAX_WRITES = 2 const PTY_RENDERER_IN_FLIGHT_HIGH_WATER_CHARS = 512 * 1024 const PTY_RENDERER_TOTAL_IN_FLIGHT_HIGH_WATER_CHARS = 8 * 1024 * 1024 + // Why: while the renderer cannot receive (frozen, starved, mid-reload), a + // chatty PTY used to grow its pendingData string without bound — main-process + // heap ballooning that a renderer reload cannot clear. Beyond this cap the + // buffered bytes are dropped and the pane heals from the main-owned buffer + // snapshot via the droppedOutput sentinel (renderer hidden-output restore). + const PTY_PENDING_DATA_MAX_CHARS_PER_PTY = 2 * 1024 * 1024 const PTY_RENDERER_INTERACTIVE_RESERVE_CHARS = 256 * 1024 // Why: active panes need a bounded lane through old hidden bulk output so a // keystroke redraw can reach the renderer before every background ACK lands. @@ -1561,27 +1569,55 @@ export function registerPtyHandlers( return [...active, ...background] } + const pendingDataDropWarnedPtys = new Set() + + function dropOversizedPendingPtyData(id: string, pending: PendingPtyData): PendingPtyData { + if ( + pending.droppedOutput === true || + pending.data.length <= PTY_PENDING_DATA_MAX_CHARS_PER_PTY + ) { + return pending + } + if (!pendingDataDropWarnedPtys.has(id)) { + pendingDataDropWarnedPtys.add(id) + console.error( + `[pty] dropped ${pending.data.length} buffered chars for ${id}: renderer not receiving and per-PTY pending cap exceeded; pane will restore from the main-owned snapshot` + ) + } + // Why empty data, not a trimmed tail: a mid-stream gap would silently + // corrupt the pane. The droppedOutput sentinel routes the pane through + // hidden-output restore, which repaints from the authoritative main-owned + // buffer and realigns with the live stream by sequence. + return { data: '', droppedOutput: true } + } + function appendPendingPtyData( + id: string, existing: PendingPtyData | undefined, data: string, startSeq: number | undefined, preservesSeq: boolean, containsBackgroundOutput: boolean ): PendingPtyData { + // Why: once over the cap, stay dropped at O(1) memory until the renderer + // can receive again — the restore sentinel supersedes any interim bytes. + if (existing?.droppedOutput === true) { + return existing + } const nextContainsBackgroundOutput = existing?.containsBackgroundOutput === true || containsBackgroundOutput if (!preservesSeq) { - return { + return dropOversizedPendingPtyData(id, { data: (existing?.data ?? '') + data, ...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {}) - } + }) } if (!existing) { - return { + return dropOversizedPendingPtyData(id, { data, ...(typeof startSeq === 'number' ? { startSeq } : {}), ...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {}) - } + }) } const next: PendingPtyData = { data: existing.data + data, @@ -1590,7 +1626,7 @@ export function registerPtyHandlers( if (typeof existing.startSeq === 'number') { next.startSeq = existing.startSeq } - return next + return dropOversizedPendingPtyData(id, next) } function schedulePendingDataFlush(delayMs: number): void { @@ -1618,6 +1654,14 @@ export function registerPtyHandlers( continue } pendingData.delete(id) + if (pending.droppedOutput === true) { + // Why: the buffered bytes were dropped at the pending cap; tell the + // renderer so the pane repaints from the main-owned buffer snapshot + // instead of continuing a stream with a silent gap. + sendPtyDataToRenderer(id, { id, data: '', droppedOutput: true }) + writes++ + continue + } const { data } = pending const chunk = data.slice(0, PTY_BATCH_FLUSH_CHUNK_CHARS) const remaining = data.slice(PTY_BATCH_FLUSH_CHUNK_CHARS) @@ -1703,6 +1747,7 @@ export function registerPtyHandlers( } const existing = pendingData.get(payload.id) const pending = appendPendingPtyData( + payload.id, existing, rendererData, startSeq, diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 3f31cc560..c268ac8bd 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1196,6 +1196,7 @@ export type PreloadApi = { seq?: number rawLength?: number background?: boolean + droppedOutput?: boolean }) => void ) => () => void onReplay: (callback: (data: { id: string; data: string }) => void) => () => void diff --git a/src/preload/index.ts b/src/preload/index.ts index 9a162aa54..578ff1b7b 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -890,6 +890,7 @@ const api = { seq?: number rawLength?: number background?: boolean + droppedOutput?: boolean }) => void ): (() => void) => { const listener = ( @@ -900,6 +901,7 @@ const api = { seq?: number rawLength?: number background?: boolean + droppedOutput?: boolean } ) => callback(data) ipcRenderer.on('pty:data', listener) diff --git a/src/renderer/src/components/terminal-pane/pty-connection.test.ts b/src/renderer/src/components/terminal-pane/pty-connection.test.ts index 211e6c1c8..c13f3b800 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.test.ts @@ -141,7 +141,10 @@ type StoreState = { } type ConnectCallbacks = { - onData?: (data: string, meta?: { seq?: number; rawLength?: number; background?: boolean }) => void + onData?: ( + data: string, + meta?: { seq?: number; rawLength?: number; background?: boolean; droppedOutput?: boolean } + ) => void onReplayData?: (data: string, meta?: { clearBeforeReplay?: boolean }) => void onError?: (msg: string) => void } @@ -6716,6 +6719,53 @@ describe('connectPanePty', () => { } }) + it('repaints from the main-owned snapshot when main drops pending output at the cap', async () => { + const { connectPanePty } = await import('./pty-connection') + const transport = createMockTransport('pty-id') + const capturedDataCallback: { + current: ((data: string, meta?: { droppedOutput?: boolean }) => void) | null + } = { current: null } + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + capturedDataCallback.current = callbacks.onData ?? null + return 'pty-id' + }) + transportFactoryQueue.push(transport) + const getMainBufferSnapshot = window.api.pty.getMainBufferSnapshot as unknown as ReturnType< + typeof vi.fn + > + getMainBufferSnapshot.mockResolvedValue({ + data: 'healed from snapshot\r\n', + cols: 100, + rows: 30 + }) + + const pane = createPane(1) + const manager = createManager(1) + const binding = connectPanePty( + pane as never, + manager as never, + createDeps({ isVisibleRef: { current: true } }) as never + ) + try { + await flushAsyncTicks(6) + getMainBufferSnapshot.mockClear() + + // Main hit the per-PTY pending cap while the renderer was starved and + // sent the droppedOutput sentinel: the stream has a gap, so the pane + // must repaint from the authoritative main-owned buffer. + capturedDataCallback.current?.('', { droppedOutput: true }) + await flushAsyncTicks(20) + + expect(getMainBufferSnapshot).toHaveBeenCalled() + expect(pane.terminal.write).toHaveBeenCalledWith( + expect.stringContaining('healed from snapshot'), + expect.any(Function) + ) + } finally { + binding.dispose() + } + }) + it('keeps split stateful Codex queries live after becoming visible', async () => { const { connectPanePty } = await import('./pty-connection') const transport = createMockTransport('pty-id') diff --git a/src/renderer/src/components/terminal-pane/pty-connection.ts b/src/renderer/src/components/terminal-pane/pty-connection.ts index 01f0132c3..9b81928d4 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.ts @@ -4607,6 +4607,13 @@ export function connectPanePty( } observeStartupDraftPasteReadiness(data) resetHiddenOutputRestoreIfPtyChanged() + if (meta?.droppedOutput === true) { + // Why: main dropped this PTY's buffered output at the pending cap + // (renderer was not receiving). The stream has a gap, so repaint the + // pane from the main-owned buffer snapshot instead of writing on. + markHiddenOutputRestoreNeeded() + return + } respondToTerminalPixelSizeQueries(data) observeTerminalBracketedPasteModeOutput(pane.terminal, data) for (const link of observeTerminalGitHubPRLink(data)) { diff --git a/src/renderer/src/components/terminal-pane/pty-dispatcher.ts b/src/renderer/src/components/terminal-pane/pty-dispatcher.ts index c7f31344c..859ac32cd 100644 --- a/src/renderer/src/components/terminal-pane/pty-dispatcher.ts +++ b/src/renderer/src/components/terminal-pane/pty-dispatcher.ts @@ -25,6 +25,9 @@ export type PtyDataMeta = { seq?: number rawLength?: number background?: boolean + /** Main dropped this PTY's buffered output at the pending cap; the pane + * must repaint from the main-owned snapshot instead of the live stream. */ + droppedOutput?: boolean } export const ptyDataHandlers = new Map void>() @@ -120,6 +123,10 @@ export function ensurePtyDispatcher(): void { meta ??= {} meta.background = true } + if (payload.droppedOutput === true) { + meta ??= {} + meta.droppedOutput = true + } const handler = ptyDataHandlers.get(payload.id) if (handler) { handler(payload.data, meta) diff --git a/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.test.ts b/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.test.ts index 2e107d9b2..4e5fc213e 100644 --- a/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.test.ts +++ b/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.test.ts @@ -923,6 +923,47 @@ describe('pane terminal output scheduler', () => { expect(output).not.toContain('x'.repeat(1024)) }) + it('caps a visible pane backlog the drain cannot keep up with and writes a warning', async () => { + // Why: the foreground path was previously uncapped — a flooding visible + // TUI on a starved renderer grew queuedChars without bound (field + // reports of ~1.5 GB renderer RSS before terminals froze). + vi.useFakeTimers() + const { writeTerminalOutput } = await loadScheduler() + const terminal = createTerminal() + const chunk = 'x'.repeat(512 * 1024) + + for (let i = 0; i < 5; i++) { + writeTerminalOutput(terminal, chunk, { foreground: true, latencySensitive: false }) + } + writeTerminalOutput(terminal, 'after-cap\r\n', { foreground: true, latencySensitive: false }) + + vi.advanceTimersByTime(0) + + const output = terminal.write.mock.calls.map(([data]) => data).join('') + expect(output).toContain('Orca skipped a burst of terminal output') + expect(output).toContain('after-cap') + expect(output).not.toContain('x'.repeat(1024)) + }) + + it('caps a held/coalesced foreground backlog as well', async () => { + vi.useFakeTimers() + const { writeTerminalOutput } = await loadScheduler() + const terminal = createForegroundTerminal() + const chunk = 'y'.repeat(512 * 1024) + + // holdForeground engages the synchronized-output hold — the branch a + // flooding TUI in sync mode exercises. + for (let i = 0; i < 5; i++) { + writeTerminalOutput(terminal, chunk, { foreground: true, holdForeground: true }) + } + + vi.advanceTimersByTime(1_000) + + const output = terminal.write.mock.calls.map(([data]) => data).join('') + expect(output).toContain('Orca skipped a burst of terminal output') + expect(output).not.toContain('y'.repeat(1024)) + }) + it('caps hidden backlog chunk count even when each chunk is tiny', async () => { vi.useFakeTimers() const { writeTerminalOutput } = await loadScheduler() diff --git a/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.ts b/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.ts index dfd67350f..c10ac12e3 100644 --- a/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.ts +++ b/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.ts @@ -91,6 +91,11 @@ const SYNCHRONIZED_OUTPUT_END_SEQUENCE = '\x1b[?2026l' // the lossy-backlog warning. const BACKGROUND_BACKLOG_WARNING = '\x18\x1b[0m\r\n[Orca skipped hidden terminal output because the backlog exceeded 2 MB.]\r\n' +// Why a separate foreground message: a visible pane hitting the cap means the +// drain could not keep up with a flood (starved renderer) — the output was +// skipped, not merely produced while hidden. +const FOREGROUND_BACKLOG_WARNING = + '\x18\x1b[0m\r\n[Orca skipped a burst of terminal output because the backlog exceeded 2 MB.]\r\n' const queuedByTerminal = new Map() const backlogRecoveryByTerminal = new WeakMap< @@ -580,12 +585,22 @@ function enqueueChunk( recordQueueDebugPressure() } -function replaceBacklogWithWarning(entry: QueueEntry): void { +function queueCapExceeded(entry: QueueEntry): boolean { + return ( + entry.queuedChars > MAX_BACKGROUND_QUEUE_CHARS || + entry.chunks.length - entry.chunkIndex > MAX_BACKGROUND_QUEUE_CHUNKS + ) +} + +function replaceBacklogWithWarning( + entry: QueueEntry, + warning: string = BACKGROUND_BACKLOG_WARNING +): void { const shouldNotify = !entry.backgroundBacklogDropped clearForegroundHoldSafety(entry) entry.chunks = [ { - data: BACKGROUND_BACKLOG_WARNING, + data: warning, foreground: false, forceForegroundRefresh: false, followupForegroundRefresh: false, @@ -593,7 +608,7 @@ function replaceBacklogWithWarning(entry: QueueEntry): void { } ] entry.chunkIndex = 0 - entry.queuedChars = BACKGROUND_BACKLOG_WARNING.length + entry.queuedChars = warning.length entry.backgroundBacklogDropped = true entry.highPriority = true entry.foregroundHold = false @@ -811,6 +826,13 @@ export function writeTerminalOutput( debugState.foregroundWriteCount++ debugState.deferredForegroundEnqueueCount++ } + // Why: a visible pane's queue was previously uncapped — a flood the + // drain can't keep up with ballooned renderer memory without bound. + if (queueCapExceeded(queued)) { + replaceBacklogWithWarning(queued, FOREGROUND_BACKLOG_WARNING) + scheduleDrain(0) + return + } if (options.holdForeground) { // Why: synchronized-output start/body chunks contain transient cursor // moves. Holding them prevents Chromium from rasterizing those states. @@ -878,6 +900,9 @@ export function writeTerminalOutput( debugState.foregroundWriteCount++ debugState.deferredForegroundEnqueueCount++ } + if (queueCapExceeded(entry)) { + replaceBacklogWithWarning(entry, FOREGROUND_BACKLOG_WARNING) + } // Why: returning from a hidden window can have megabytes queued. Keep // byte order, but drain it asynchronously so the first foreground frame // is not pinned behind the entire backlog. @@ -905,6 +930,9 @@ export function writeTerminalOutput( debugState.foregroundWriteCount++ debugState.deferredForegroundEnqueueCount++ } + if (queueCapExceeded(queued)) { + replaceBacklogWithWarning(queued, FOREGROUND_BACKLOG_WARNING) + } // Why: visible command floods are throughput work, not keystroke echo. // Queue them behind a zero-delay drain so one IPC callback cannot pin // the renderer in xterm.write while input and paint are waiting. @@ -940,10 +968,7 @@ export function writeTerminalOutput( enqueueChunk(entry, data, { onParsed: options.onParsed }) - if ( - entry.queuedChars > MAX_BACKGROUND_QUEUE_CHARS || - entry.chunks.length - entry.chunkIndex > MAX_BACKGROUND_QUEUE_CHUNKS - ) { + if (queueCapExceeded(entry)) { replaceBacklogWithWarning(entry) } if (debugEnabled) {