Repository navigation
Log where main's memory went when it suddenly jumps #46734
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
f6d535e
feat(memory): log a breakdown when main's memory jumps
brennanb2025 33d6a27
test(memory): type the spike capture sink without a cast
brennanb2025 9aa93b8
chore: drop unrelated lockfile change
brennanb2025 5be8659
fix(memory): keep collected stats when an optional memory read fails
brennanb2025 d36bcca
fix(memory): keep the sample from two late ticks ago in the spike window
brennanb2025 2fa7567
chore: drop unrelated lockfile change
brennanb2025 8271507
fix(memory): record the spike baseline's real age
brennanb2025 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
93 changes: 93 additions & 0 deletions
93
src/main/memory/main-memory-spike-capture.performance.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| ) { | ||
| 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 | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.