Register PTY output processors in memory profile census (#12795)
Add a new census module that tracks pending and retained OSC sequences across all active PTY output processors. Each processor registers a gauge at creation and unregisters it on dispose, detach, or destroy — this prevents retained gauges from inflating later heap high-water profiles and allows the memory profiler to detect stalled processors as a sign of leaks.
This commit is contained in:
@@ -542,6 +542,19 @@ describe('startParkedTerminalByteWatcher', () => {
|
||||
dispose()
|
||||
})
|
||||
|
||||
// Why: retained gauges would inflate every later high-water profile.
|
||||
it('dispose drops the processor from the pty side-effect census', async () => {
|
||||
await import('./pty-side-effect-pending-census')
|
||||
const { collectRendererMemoryProfileCounts } = await import('@/lib/renderer-memory-profile')
|
||||
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0)
|
||||
|
||||
const { dispose } = await startWatcher()
|
||||
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(1)
|
||||
|
||||
dispose()
|
||||
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0)
|
||||
})
|
||||
|
||||
it('disposes the previous watcher when a new one starts for the same PTY', async () => {
|
||||
await startWatcher({ paneId: 1 })
|
||||
const second = await startWatcher({ paneId: 2 })
|
||||
|
||||
@@ -303,6 +303,9 @@ export function startParkedTerminalByteWatcher(
|
||||
return
|
||||
}
|
||||
disposed = true
|
||||
// Why first: each park/reveal cycle owns a distinct processor gauge, and the store/IPC
|
||||
// teardown below must not be able to throw its way past the census drop.
|
||||
processor?.disposePendingSideEffectGauge()
|
||||
// Why: unhide BEFORE the reveal remount registers pane handlers, so main resumes delivery and emits the restore marker the pane consumes.
|
||||
releaseHiddenDeliveryClaim?.()
|
||||
stopMode2031Responder?.()
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { collectRendererMemoryProfileCounts } from '@/lib/renderer-memory-profile'
|
||||
import { registerPtySideEffectPendingGauge } from './pty-side-effect-pending-census'
|
||||
|
||||
function ptySideEffectCounts(): { pending: number; retained: number; processors: number } {
|
||||
const counts = collectRendererMemoryProfileCounts()
|
||||
return {
|
||||
pending: counts['ptySideEffects.pending'],
|
||||
retained: counts['ptySideEffects.retained'],
|
||||
processors: counts['ptySideEffects.processors']
|
||||
}
|
||||
}
|
||||
|
||||
function fixedGauge(pending: number, retained = pending): { dispose: () => void } {
|
||||
// Why the local: the census holds gauges weakly, so a test gauge needs a strong owner too.
|
||||
const gauge = { pending: () => pending, retained: () => retained }
|
||||
return { dispose: registerPtySideEffectPendingGauge(gauge) }
|
||||
}
|
||||
|
||||
describe('pty side-effect pending census', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('sums registered gauges and drops disposed ones', () => {
|
||||
const before = ptySideEffectCounts()
|
||||
const a = fixedGauge(3, 5)
|
||||
const b = fixedGauge(4, 4)
|
||||
|
||||
let counts = ptySideEffectCounts()
|
||||
expect(counts.pending).toBe(before.pending + 7)
|
||||
expect(counts.retained).toBe(before.retained + 9)
|
||||
expect(counts.processors).toBe(before.processors + 2)
|
||||
|
||||
a.dispose()
|
||||
counts = ptySideEffectCounts()
|
||||
expect(counts.pending).toBe(before.pending + 4)
|
||||
expect(counts.retained).toBe(before.retained + 4)
|
||||
expect(counts.processors).toBe(before.processors + 1)
|
||||
|
||||
b.dispose()
|
||||
expect(ptySideEffectCounts()).toEqual(before)
|
||||
})
|
||||
|
||||
it('ignores a repeated dispose instead of dropping another gauge', () => {
|
||||
const before = ptySideEffectCounts()
|
||||
const a = fixedGauge(3)
|
||||
const b = fixedGauge(4)
|
||||
|
||||
a.dispose()
|
||||
a.dispose()
|
||||
|
||||
expect(ptySideEffectCounts().processors).toBe(before.processors + 1)
|
||||
b.dispose()
|
||||
expect(ptySideEffectCounts()).toEqual(before)
|
||||
})
|
||||
|
||||
it('stops tracking new gauges past the cap so a missed dispose cannot grow it', () => {
|
||||
const before = ptySideEffectCounts()
|
||||
const owners = Array.from({ length: 600 }, () => fixedGauge(1))
|
||||
try {
|
||||
expect(ptySideEffectCounts().processors).toBe(512)
|
||||
} finally {
|
||||
for (const owner of owners) {
|
||||
owner.dispose()
|
||||
}
|
||||
}
|
||||
expect(ptySideEffectCounts()).toEqual(before)
|
||||
})
|
||||
|
||||
it('tracks a live output processor queue through enqueue, drain, and dispose', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { createPtyOutputProcessor } = await import('./pty-transport')
|
||||
const before = ptySideEffectCounts()
|
||||
const processor = createPtyOutputProcessor({ onTitleChange: vi.fn() })
|
||||
|
||||
expect(ptySideEffectCounts()).toEqual({
|
||||
pending: before.pending,
|
||||
retained: before.retained,
|
||||
processors: before.processors + 1
|
||||
})
|
||||
|
||||
processor.processData('\x1b]0;census-title\x07', { onData: vi.fn() })
|
||||
expect(ptySideEffectCounts().pending).toBe(before.pending + 1)
|
||||
|
||||
await vi.runOnlyPendingTimersAsync()
|
||||
expect(ptySideEffectCounts().pending).toBe(before.pending)
|
||||
|
||||
processor.processData('\x1b]0;census-title-2\x07', { onData: vi.fn() })
|
||||
expect(ptySideEffectCounts().pending).toBe(before.pending + 1)
|
||||
processor.clearAccumulatedState()
|
||||
expect(ptySideEffectCounts().pending).toBe(before.pending)
|
||||
|
||||
processor.disposePendingSideEffectGauge()
|
||||
expect(ptySideEffectCounts()).toEqual(before)
|
||||
})
|
||||
|
||||
// Why: a partly drained queue still holds every entry until compaction, so depth alone
|
||||
// would understate the retained bytes this census exists to attribute.
|
||||
it('reports drained-but-uncompacted entries as retained after a bounded drain', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { createPtyOutputProcessor } = await import('./pty-transport')
|
||||
const before = ptySideEffectCounts()
|
||||
const processor = createPtyOutputProcessor({ onTitleChange: vi.fn() })
|
||||
|
||||
for (let i = 0; i < 100; i += 1) {
|
||||
processor.processData(`\x1b]0;census-title-${i}\x07`, { onData: vi.fn() })
|
||||
}
|
||||
expect(ptySideEffectCounts()).toEqual({
|
||||
pending: before.pending + 100,
|
||||
retained: before.retained + 100,
|
||||
processors: before.processors + 1
|
||||
})
|
||||
|
||||
// One drain applies MAX_PTY_SIDE_EFFECTS_PER_DRAIN entries but stays under the compaction threshold.
|
||||
await vi.runOnlyPendingTimersAsync()
|
||||
expect(ptySideEffectCounts().pending).toBe(before.pending + 36)
|
||||
expect(ptySideEffectCounts().retained).toBe(before.retained + 100)
|
||||
|
||||
processor.flushPendingSideEffects()
|
||||
expect(ptySideEffectCounts()).toEqual({
|
||||
pending: before.pending,
|
||||
retained: before.retained,
|
||||
processors: before.processors + 1
|
||||
})
|
||||
|
||||
processor.disposePendingSideEffectGauge()
|
||||
expect(ptySideEffectCounts()).toEqual(before)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
import { registerRendererMemoryProfileContributor } from '@/lib/renderer-memory-profile'
|
||||
|
||||
/** Queue counts for one PTY output processor, read at heap-highwater time. */
|
||||
export type PtySideEffectGauge = {
|
||||
/** Entries still awaiting apply; saturates at MAX_PENDING_PTY_SIDE_EFFECTS. */
|
||||
pending: () => number
|
||||
/** Entries the queue array still holds — drained-but-uncompacted ones included, so this is the count that tracks retained bytes. */
|
||||
retained: () => number
|
||||
}
|
||||
|
||||
// Why weak: a diagnostic for leaks must not be able to cause one. The owning processor holds
|
||||
// the only strong reference, so a teardown path that forgets to dispose strands an empty
|
||||
// WeakRef here instead of pinning the processor's whole closure (callbacks, tracker, terminal).
|
||||
const gaugeRefs = new Set<WeakRef<PtySideEffectGauge>>()
|
||||
|
||||
// Why: bounds this module even if registrations outrun both disposal and collection.
|
||||
const MAX_TRACKED_GAUGES = 512
|
||||
|
||||
function pruneCollectedGauges(): void {
|
||||
for (const ref of gaugeRefs) {
|
||||
if (ref.deref() === undefined) {
|
||||
gaugeRefs.delete(ref)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function registerPtySideEffectPendingGauge(gauge: PtySideEffectGauge): () => void {
|
||||
if (gaugeRefs.size >= MAX_TRACKED_GAUGES) {
|
||||
pruneCollectedGauges()
|
||||
}
|
||||
if (gaugeRefs.size >= MAX_TRACKED_GAUGES) {
|
||||
return () => undefined
|
||||
}
|
||||
gaugeRefs.add(new WeakRef(gauge))
|
||||
// Why delete by identity: this closure is handed to the processor, so closing over `gauge`
|
||||
// is what makes the processor — never this module — the gauge's strong owner.
|
||||
return () => {
|
||||
for (const ref of gaugeRefs) {
|
||||
if (ref.deref() === gauge) {
|
||||
gaugeRefs.delete(ref)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Why processor count is the signal: each queue is capped at MAX_PENDING_PTY_SIDE_EFFECTS and
|
||||
// evicts oldest-first, so one processor can never grow without bound. Aggregate growth means
|
||||
// processors outliving their panes; queues parked at the cap mean a drain starved by throttling.
|
||||
registerRendererMemoryProfileContributor('ptySideEffects', () => {
|
||||
let pending = 0
|
||||
let retained = 0
|
||||
let processors = 0
|
||||
for (const ref of gaugeRefs) {
|
||||
const gauge = ref.deref()
|
||||
if (!gauge) {
|
||||
gaugeRefs.delete(ref)
|
||||
continue
|
||||
}
|
||||
pending += gauge.pending()
|
||||
retained += gauge.retained()
|
||||
processors += 1
|
||||
}
|
||||
return { pending, retained, processors }
|
||||
})
|
||||
@@ -183,6 +183,9 @@ export type PtyTransport = {
|
||||
scrollbackRows?: number
|
||||
}) => Promise<RemoteRuntimeSnapshotOutcome>
|
||||
preserve?: () => void
|
||||
/** Hand the live PTY to a successor without process teardown. Terminal for this instance:
|
||||
* it also drops the transport's output processor from the pty side-effect memory census,
|
||||
* so a reattached one would run untracked. Create a new transport instead. */
|
||||
detach?: (options?: { preserveExitObserver?: boolean }) => void
|
||||
destroy?: () => void | Promise<void>
|
||||
}
|
||||
|
||||
@@ -118,6 +118,43 @@ describe('createIpcPtyTransport', () => {
|
||||
expect(kill).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// Why: retained gauges would inflate every later high-water profile.
|
||||
it.each(['detach', 'destroy'] as const)(
|
||||
'drops its side-effect gauge from the census on %s',
|
||||
async (teardown) => {
|
||||
await import('./pty-side-effect-pending-census')
|
||||
const { collectRendererMemoryProfileCounts } = await import('@/lib/renderer-memory-profile')
|
||||
const { createIpcPtyTransport } = await import('./pty-transport')
|
||||
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0)
|
||||
|
||||
const transport = createIpcPtyTransport({})
|
||||
await transport.connect({ url: '', callbacks: {} })
|
||||
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(1)
|
||||
|
||||
transport[teardown]?.()
|
||||
|
||||
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0)
|
||||
}
|
||||
)
|
||||
|
||||
// Why: teardown that already failed is exactly when a stranded gauge would pin the processor.
|
||||
it('drops its side-effect gauge even when destroy throws mid-disconnect', async () => {
|
||||
await import('./pty-side-effect-pending-census')
|
||||
const { collectRendererMemoryProfileCounts } = await import('@/lib/renderer-memory-profile')
|
||||
const { createIpcPtyTransport } = await import('./pty-transport')
|
||||
const kill = window.api.pty.kill as unknown as ReturnType<typeof vi.fn>
|
||||
const transport = createIpcPtyTransport({})
|
||||
await transport.connect({ url: '', callbacks: {} })
|
||||
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(1)
|
||||
|
||||
kill.mockImplementationOnce(() => {
|
||||
throw new Error('ipc channel closed')
|
||||
})
|
||||
|
||||
expect(() => transport.destroy?.()).toThrow('ipc channel closed')
|
||||
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0)
|
||||
})
|
||||
|
||||
it('retires an adopted PTY when recovery disconnects before a replacement spawn', async () => {
|
||||
const { createIpcPtyTransport } = await import('./pty-transport')
|
||||
const spawn = window.api.pty.spawn as unknown as ReturnType<typeof vi.fn>
|
||||
|
||||
@@ -43,6 +43,10 @@ import {
|
||||
type ProcessedAgentStatusChunk
|
||||
} from '../../../../shared/agent-status-osc'
|
||||
import { extractIpcErrorMessage } from '@/lib/ipc-error'
|
||||
import {
|
||||
registerPtySideEffectPendingGauge,
|
||||
type PtySideEffectGauge
|
||||
} from './pty-side-effect-pending-census'
|
||||
import { isTuiAgent } from '../../../../shared/tui-agent-config'
|
||||
|
||||
// Re-export public API so existing consumers keep working.
|
||||
@@ -153,6 +157,7 @@ export function createPtyOutputProcessor({
|
||||
flushPendingSideEffects: () => void
|
||||
resetBellDetector: () => void
|
||||
resetAgentStatusCarry: () => void
|
||||
disposePendingSideEffectGauge: () => void
|
||||
} {
|
||||
const bellDetector = createBellDetector()
|
||||
// Why let: a model-restore marker drops bytes; recreating the parser stops a partial OSC-9999 carry from swallowing the next chunk's head.
|
||||
@@ -165,6 +170,12 @@ export function createPtyOutputProcessor({
|
||||
let pendingSideEffects: PendingPtySideEffect[] = []
|
||||
let pendingSideEffectIndex = 0
|
||||
let pendingWorkingTitleSideEffects = 0
|
||||
// Why both counts: drained entries survive until compaction, so depth alone understates what the array retains.
|
||||
const pendingSideEffectGauge: PtySideEffectGauge = {
|
||||
pending: () => pendingSideEffects.length - pendingSideEffectIndex,
|
||||
retained: () => pendingSideEffects.length
|
||||
}
|
||||
const disposePendingSideEffectGauge = registerPtySideEffectPendingGauge(pendingSideEffectGauge)
|
||||
const agentTracker =
|
||||
onAgentBecameIdle || onAgentBecameWorking || onAgentExited
|
||||
? createAgentStatusTracker(
|
||||
@@ -507,7 +518,8 @@ export function createPtyOutputProcessor({
|
||||
resetBellDetector: () => bellDetector.reset(),
|
||||
resetAgentStatusCarry: () => {
|
||||
processAgentStatusChunk = createAgentStatusOscProcessor()
|
||||
}
|
||||
},
|
||||
disposePendingSideEffectGauge
|
||||
}
|
||||
}
|
||||
|
||||
@@ -989,6 +1001,9 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
|
||||
},
|
||||
|
||||
detach(options) {
|
||||
// Why first: the successor transport owns the PTY after detach, and nothing below may
|
||||
// throw its way past the census drop — a stranded gauge outlives the transport.
|
||||
outputProcessor.disposePendingSideEffectGauge()
|
||||
clearAccumulatedState()
|
||||
inputWriteQueue.clear()
|
||||
if (ptyId) {
|
||||
@@ -1086,7 +1101,13 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
|
||||
|
||||
destroy() {
|
||||
destroyed = true
|
||||
this.disconnect()
|
||||
// Why finally: disconnect runs pty.kill IPC and consumer onDisconnect callbacks; a throw
|
||||
// there must not strand the gauge in the very path where teardown already went wrong.
|
||||
try {
|
||||
this.disconnect()
|
||||
} finally {
|
||||
outputProcessor.disposePendingSideEffectGauge()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -388,6 +388,27 @@ describe('createRemoteRuntimePtyTransport', () => {
|
||||
transport.destroy?.()
|
||||
})
|
||||
|
||||
// Why: retained gauges would inflate every later high-water profile.
|
||||
it.each(['detach', 'destroy'] as const)(
|
||||
'drops its side-effect gauge from the census on %s',
|
||||
async (teardown) => {
|
||||
await import('./pty-side-effect-pending-census')
|
||||
const { collectRendererMemoryProfileCounts } = await import('@/lib/renderer-memory-profile')
|
||||
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
|
||||
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0)
|
||||
|
||||
const transport = createRemoteRuntimePtyTransport('env-1', { worktreeId: 'wt-1' })
|
||||
transport.attach({ existingPtyId: 'remote:terminal-1', callbacks: {} })
|
||||
await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled())
|
||||
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(1)
|
||||
|
||||
transport[teardown]?.()
|
||||
|
||||
expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0)
|
||||
transport.destroy?.()
|
||||
}
|
||||
)
|
||||
|
||||
it('recovers when the first restored-terminal subscription attempt is offline', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
|
||||
@@ -2291,6 +2291,9 @@ export function createRemoteRuntimePtyTransport(
|
||||
},
|
||||
|
||||
detach() {
|
||||
// Why first: the successor transport owns the PTY after detach, and the batcher flushes
|
||||
// below can throw past the census drop — a stranded gauge outlives the transport.
|
||||
outputProcessor.disposePendingSideEffectGauge()
|
||||
lifecycleEpoch += 1
|
||||
attachGeneration += 1
|
||||
cancelTerminalCreateRetryWait()
|
||||
@@ -2516,7 +2519,13 @@ export function createRemoteRuntimePtyTransport(
|
||||
destroy() {
|
||||
destroyed = true
|
||||
setAttachmentUnavailable()
|
||||
this.disconnect()
|
||||
// Why finally: disconnect runs consumer onDisconnect/onPtyExit callbacks; a throw there
|
||||
// must not strand the gauge in the very path where teardown already went wrong.
|
||||
try {
|
||||
this.disconnect()
|
||||
} finally {
|
||||
outputProcessor.disposePendingSideEffectGauge()
|
||||
}
|
||||
recovery.dispose()
|
||||
inputBatcher.clear()
|
||||
viewportBatcher.clear()
|
||||
|
||||
Reference in New Issue
Block a user