Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
startPreGoneSystemMemorySampling
} from '../memory/pre-gone-host-memory'
import { preGonePtyTreeMemoryDetails } from '../memory/pre-gone-pty-tree-memory'
import { observeMainMemorySample } from '../../memory/main-memory-spike-capture'

type ProcessMetricLike = {
pid?: unknown
Expand Down Expand Up @@ -199,10 +200,11 @@ function sampledProcessIdentities(metrics: ProcessMetricLike[]): PreGoneSampledP
export function samplePreGoneProcessMetrics(nowMs: number = Date.now()): void {
try {
const metrics = app.getAppMetrics()
preGoneSample = {
details: collectProcessGoneMetricDetails(metrics),
processes: sampledProcessIdentities(metrics),
sampledAtMs: nowMs
const details = collectProcessGoneMetricDetails(metrics)
preGoneSample = { details, processes: sampledProcessIdentities(metrics), sampledAtMs: nowMs }
const mainMB = details.processMetricsBrowserWorkingSetMB
if (typeof mainMB === 'number') {
observeMainMemorySample(mainMB, nowMs, details)
}
} catch {
// Preserve the last good sample when enumeration fails.
Expand Down
93 changes: 93 additions & 0 deletions src/main/memory/main-memory-spike-capture.performance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Main's memory spike capture (main-memory-spike-capture PR): an idle or steadily growing main writes
// no record and reads no counts; one 300 MB jump within two minutes writes exactly one record an hour.
import { afterEach, beforeEach, expect, it, vi } from 'vitest'

vi.mock('../worker-threads/worker-thread-diagnostics', () => ({
readWorkerThreadMemoryData: async () => ({ workers: 0 })
}))

import { _resetTracerForTests, setActiveSink } from '../observability/tracer'
import {
observeMainMemorySample,
resetMainMemorySpikeCaptureForTest,
setMainMemorySpikeCounts
} from './main-memory-spike-capture'

const MINUTE = 60_000
type SpanRecord = { name?: string; attributes?: Record<string, unknown> }
const records: SpanRecord[] = []
const counts = vi.fn(() => ({ openChats: 3, terminals: 2 }))

beforeEach(() => {
setActiveSink({ push: (record: SpanRecord) => records.push(record), flush() {}, close() {} })
setMainMemorySpikeCounts(counts)
})

afterEach(() => {
resetMainMemorySpikeCaptureForTest()
_resetTracerForTests()
records.length = 0
counts.mockClear()
})

async function settle(): Promise<void> {
await new Promise((resolve) => setImmediate(resolve))
await new Promise((resolve) => setImmediate(resolve))
}

it('does no capture work across a day of samples without a spike', async () => {
// 20 MB more every minute: 2.9 GB of growth, never 300 MB within two minutes.
for (let minute = 0; minute < 24 * 60; minute += 1) {
observeMainMemorySample(500 + minute * 2, minute * MINUTE, {})
}
await settle()
expect(records).toHaveLength(0)
expect(counts).not.toHaveBeenCalled()
})

it('ignores the launch ramp', async () => {
observeMainMemorySample(200, 0, {})
observeMainMemorySample(900, MINUTE, {})
await settle()
expect(records).toHaveLength(0)
})

it('compares against the sample from two late-firing ticks ago', async () => {
observeMainMemorySample(900, 0, {})
observeMainMemorySample(1000, 3 * MINUTE, {})
observeMainMemorySample(1150, 4 * MINUTE + 1, {})
observeMainMemorySample(1300, 5 * MINUTE + 3, {})
await settle()
expect(records).toHaveLength(1)
expect(records[0].attributes).toMatchObject({
baselineWorkingSetMB: 1000,
baselineAgeMs: 120_003,
riseMB: 300
})
})

it('writes one record for a spike and none for another within the hour', async () => {
observeMainMemorySample(400, 0, {})
observeMainMemorySample(850, 3 * MINUTE, {})
observeMainMemorySample(860, 4 * MINUTE, {})
observeMainMemorySample(1470, 5 * MINUTE, { processMetricsBrowserWorkingSetMB: 1470 })
observeMainMemorySample(800, 6 * MINUTE, {})
observeMainMemorySample(1500, 7 * MINUTE, {})
await settle()
expect(records).toHaveLength(1)
expect(counts).toHaveBeenCalledTimes(1)
expect(records[0].name).toBe('memory.main-spike')
expect(records[0].attributes).toMatchObject({
mainWorkingSetMB: 1470,
baselineWorkingSetMB: 850,
riseMB: 620,
count_openChats: 3,
count_terminals: 2,
workers: 0
})

observeMainMemorySample(800, 66 * MINUTE, {})
observeMainMemorySample(1200, 67 * MINUTE, {})
await settle()
expect(records).toHaveLength(2)
})
170 changes: 170 additions & 0 deletions src/main/memory/main-memory-spike-capture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { getHeapSpaceStatistics, getHeapStatistics } from 'node:v8'
import type { CrashReportDetailValue } from '../../shared/crash-reporting/crash-reporting'
import { hasActiveTraceSink, startSpan } from '../observability/tracer'
import { readWorkerThreadMemoryData } from '../worker-threads/worker-thread-diagnostics'

/**
* Main's footprint jumping by hundreds of MB names no owner after the fact, so a rise this large
* within this window writes one breakdown to the local trace log. Fed by the process-metrics
* sampler, so an idle app pays one comparison per sample and no reads of its own.
*/
export const MAIN_MEMORY_SPIKE_RISE_MB = 300
export const MAIN_MEMORY_SPIKE_WINDOW_MS = 2 * 60_000
/** Ticks fire late (more so on a busy main), so the sample from two ticks ago can be just past the window. */
const SAMPLE_LATENESS_SLACK_MS = 30_000
export const MAIN_MEMORY_SPIKE_MIN_INTERVAL_MS = 60 * 60_000
const MB = 2 ** 20

type Details = Record<string, CrashReportDetailValue>
type Sample = { atMs: number; mb: number }

/** Counts only, never names or paths. */
export type MainMemorySpikeCounts = () => Record<string, number>

const recent: Sample[] = []
let armedAtMs: number | null = null
let lastCaptureAtMs = Number.NEGATIVE_INFINITY
let readCounts: MainMemorySpikeCounts | null = null

export function setMainMemorySpikeCounts(counts: MainMemorySpikeCounts | null): void {
readCounts = counts
}

export function observeMainMemorySample(
mainMB: number,
nowMs: number,
processMetrics: Details
): void {
// Launch loads the profile in its first minutes; that ramp is expected, not a spike.
armedAtMs ??= nowMs + MAIN_MEMORY_SPIKE_WINDOW_MS
if (nowMs < armedAtMs) {
return
}
while (
recent.length > 0 &&
nowMs - recent[0].atMs > MAIN_MEMORY_SPIKE_WINDOW_MS + SAMPLE_LATENESS_SLACK_MS
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
) {
recent.shift()
}
let baseline: Sample = { atMs: nowMs, mb: mainMB }
for (const sample of recent) {
if (sample.mb < baseline.mb) {
baseline = sample
}
}
recent.push({ atMs: nowMs, mb: mainMB })
if (
mainMB - baseline.mb < MAIN_MEMORY_SPIKE_RISE_MB ||
nowMs - lastCaptureAtMs < MAIN_MEMORY_SPIKE_MIN_INTERVAL_MS ||
!hasActiveTraceSink()
) {
return
}
lastCaptureAtMs = nowMs
void captureMainMemorySpike({
mainMB,
baselineMB: baseline.mb,
baselineAgeMs: nowMs - baseline.atMs,
processMetrics
})
}

async function captureMainMemorySpike(trigger: {
mainMB: number
baselineMB: number
baselineAgeMs: number
processMetrics: Details
}): Promise<void> {
const span = startSpan('memory.main-spike', {
attributes: {
mainWorkingSetMB: trigger.mainMB,
baselineWorkingSetMB: trigger.baselineMB,
riseMB: trigger.mainMB - trigger.baselineMB,
baselineAgeMs: trigger.baselineAgeMs,
...trigger.processMetrics
}
})
const record = (attributes: Details): void => {
for (const [key, value] of Object.entries(attributes)) {
span.setAttribute(key, value)
}
}
// Synchronous reads first, so they describe the moment of the spike; a failed part names itself.
for (const [part, read] of [
['node', nodeMemory],
['v8', v8Heap],
['counts', countsData]
] as const) {
try {
record(read())
} catch {
span.setAttribute(`${part}Error`, true)
}
}
const [allocator, workers] = await Promise.allSettled([
allocatorTotals(),
readWorkerThreadMemoryData()
])
record(allocator.status === 'fulfilled' ? allocator.value : { chromiumError: true })
record(workers.status === 'fulfilled' ? workers.value : { workersError: true })
span.end()
}

function toMB(bytes: number): number {
return Math.round(bytes / MB)
}

function nodeMemory(): Details {
const usage = process.memoryUsage()
return {
rssMB: toMB(usage.rss),
heapTotalMB: toMB(usage.heapTotal),
heapUsedMB: toMB(usage.heapUsed),
externalMB: toMB(usage.external),
arrayBuffersMB: toMB(usage.arrayBuffers)
}
}

function v8Heap(): Details {
const heap = getHeapStatistics()
const details: Details = {
v8TotalHeapMB: toMB(heap.total_heap_size),
v8UsedHeapMB: toMB(heap.used_heap_size),
v8PhysicalMB: toMB(heap.total_physical_size),
v8MallocedMB: toMB(heap.malloced_memory),
v8PeakMallocedMB: toMB(heap.peak_malloced_memory),
v8ExternalMB: toMB(heap.external_memory),
v8HeapLimitMB: toMB(heap.heap_size_limit),
v8NativeContexts: heap.number_of_native_contexts,
v8DetachedContexts: heap.number_of_detached_contexts
}
for (const space of getHeapSpaceStatistics()) {
details[`v8Space_${space.space_name}_usedMB`] = toMB(space.space_used_size)
}
return details
}

/** Chromium's per-process totals; its full allocator dump needs a trace session, which stays opt-in. */
async function allocatorTotals(): Promise<Details> {
if (typeof process.getProcessMemoryInfo !== 'function') {
return {}
}
const info = await process.getProcessMemoryInfo()
return {
chromiumPrivateMB: Math.round(info.private / 1024),
chromiumSharedMB: Math.round(info.shared / 1024),
...(info.residentSet ? { chromiumResidentSetMB: Math.round(info.residentSet / 1024) } : {})
}
}

function countsData(): Details {
const counts = readCounts?.() ?? {}
return Object.fromEntries(Object.entries(counts).map(([key, value]) => [`count_${key}`, value]))
}

export function resetMainMemorySpikeCaptureForTest(): void {
recent.length = 0
armedAtMs = null
lastCaptureAtMs = Number.NEGATIVE_INFINITY
readCounts = null
}
4 changes: 4 additions & 0 deletions src/main/memory/pty-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,7 @@ export function hasRegisteredPtyWithPid(): boolean {
export function listRegisteredPtys(): PtyRegistration[] {
return [...registry.values()]
}

export function registeredPtyCount(): number {
return registry.size
}
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ export function createStructuredAgentSessionConversationReads(context: () => Rea
: child?.accountHome
},
holdsSessions: () => context().deps.store.holdsRecords(),
openConversationCount: () => context().sessions.size,
onSessionsHeld: (listener: () => void) => context().deps.store.onHeldChange(listener),
prospectiveAccountHome: (id: string) => {
const { deps, serialize } = context()
Expand Down
10 changes: 10 additions & 0 deletions src/main/startup/main-process-ready-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import { browserSessionRegistry } from '../browser/sessions/profiles/browser-ses
import { configureBrowserClientPageAutomationRuntime } from '../browser/client-pages/execution/browser-client-page-automation-runtime'
import { openOffscreenBrowserPageLink } from '../runtime/browser/commands/offscreen-browser-page-link'
import { startPreGoneCrashSampling } from '../crash-reporting/process-exits/process-gone-diagnostics'
import { setMainMemorySpikeCounts } from '../memory/main-memory-spike-capture'
import { registeredPtyCount } from '../memory/pty-registry'
import { getStructuredAgentSessionHost } from '../native-chat/agent-session-wire/host/structured-agent-session-registry'
import { refuseRealtimeSchedulingUnderZeroRtTime } from './linux-runtime/linux-realtime-scheduling-guard'
import { recordProcessGoneCrash } from './main-window/main-window-lifecycle-flags'
import { handleGpuChildCrash } from './gpu-recovery/gpu-lifecycle'
Expand All @@ -32,6 +35,13 @@ function getDesktopWindowStatus(): RuntimeDesktopWindowStatus {
}

function startProcessCrashObservers(): void {
setMainMemorySpikeCounts(() => ({
openChats: getStructuredAgentSessionHost()?.reads.openConversationCount() ?? 0,
workspaces: Object.keys(state.store?.getAllWorktreeMeta() ?? {}).length,
projects: state.store?.getRepos().length ?? 0,
bots: state.store?.getBots().length ?? 0,
terminals: registeredPtyCount()
}))
// Sample live processes: gone-time metrics omit dead children and already-released memory.
startPreGoneCrashSampling()
app.on('child-process-gone', (_event, details) => {
Expand Down
29 changes: 25 additions & 4 deletions src/main/worker-threads/worker-thread-diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ const MB = 2 ** 20
type LiveWorker = { worker: Worker; role: WorkerThreadRole; threadId: number }
type WorkerHeap = { entry: LiveWorker; heap: number }

const live = new Set<LiveWorker>()

export function installWorkerThreadDiagnostics(): void {
const live = new Set<LiveWorker>()
let largeSendLogSet = false
onJournalReaderRequest(annotateReaderRequest)
let sampling: ReturnType<typeof setTimeout> | undefined
Expand Down Expand Up @@ -96,8 +97,7 @@ export function installWorkerThreadDiagnostics(): void {
})
}

/** Returns the committed heap of main plus every live worker. */
async function sampleHeaps(live: Set<LiveWorker>): Promise<number> {
async function readLiveWorkerHeaps(live: Set<LiveWorker>): Promise<WorkerHeap[]> {
for (const entry of live) {
if (entry.worker.threadId === -1) {
live.delete(entry)
Expand All @@ -110,7 +110,28 @@ async function sampleHeaps(live: Set<LiveWorker>): Promise<number> {
heap: (await readWorkerHeap(entry.worker, ledger.get(entry.threadId))).bytes ?? 0
}))
)
heaps.sort((a, b) => b.heap - a.heap)
return heaps.sort((a, b) => b.heap - a.heap)
}

/** Worker heaps, largest first, and what main retains for chats; for the memory spike record. */
export async function readWorkerThreadMemoryData(): Promise<CrashReportBreadcrumbData> {
const heaps = await readLiveWorkerHeaps(live)
const data: CrashReportBreadcrumbData = {
workers: heaps.length,
workersHeapMB: Math.round(heaps.reduce((sum, { heap }) => sum + heap, 0) / MB),
...mainHeapSpaces(),
...retentionData(readRetention())
}
heaps.slice(0, REPORTED_WORKERS).forEach(({ entry, heap }, index) => {
data[`w${index}_role`] = entry.role
data[`w${index}_heapMB`] = Math.round(heap / MB)
})
return data
}

/** Returns the committed heap of main plus every live worker. */
async function sampleHeaps(live: Set<LiveWorker>): Promise<number> {
const heaps = await readLiveWorkerHeaps(live)
// After the worker reads, which can take seconds, so main's and the ledger's figures are current.
const sent = new Map(readWorkerSendLedger().map((slot) => [slot.threadId, slot]))
const mainHeap = getHeapStatistics().total_heap_size
Expand Down
Loading