Repository navigation
feat(utility-worker-host): report the chat reader host's heaps for crash diagnosis #43897
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
a33a169
feat(utility-worker-host): report host and reader heaps to main for c…
brennanb2025 e14c83c
fix(utility-worker-host): keep heap events out of a worker's receive …
brennanb2025 8274208
Merge remote-tracking branch 'origin/main' into brennanb2025/utility-…
brennanb2025 8992b29
Merge remote-tracking branch 'origin/main' into brennanb2025/utility-…
brennanb2025 af23feb
fix(utility-worker-host): drop readers that left mid-sample, report a…
brennanb2025 5d32c8a
fix(utility-worker-host): count unknown reader heaps in the exit brea…
brennanb2025 4c1619a
fix(utility-worker-host): re-read the host heap on every transition t…
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
64 changes: 64 additions & 0 deletions
64
src/main/utility-worker-host/utility-worker-heap-report.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,64 @@ | ||
| import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting/crash-reporting' | ||
| import { recordCoalescedDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' | ||
| import { | ||
| WORKER_HEAP_BREADCRUMB_BYTES, | ||
| WORKER_HEAP_BREADCRUMB_MIN_INTERVAL_MS | ||
| } from '../worker-threads/worker-heap-sample' | ||
| import type { HostedWorker } from './hosted-worker' | ||
| import { | ||
| type UtilityWorkerHeapReport, | ||
| utilityWorkerHeapTotal | ||
| } from './utility-worker-host-protocol' | ||
|
|
||
| const MB = 2 ** 20 | ||
|
|
||
| /** Each worker's heap beside its replies; matched by spawn id, since every reader has one role. */ | ||
| export function utilityWorkerHeapData( | ||
| report: UtilityWorkerHeapReport | undefined, | ||
| workers: readonly HostedWorker[] | ||
| ): CrashReportBreadcrumbData { | ||
| if (!report) { | ||
| return { heapReportAgeS: null } | ||
| } | ||
| const heaps = new Map(report.workers.map((worker) => [worker.id, worker])) | ||
| const data: CrashReportBreadcrumbData = { | ||
| // Reports post only on change: later samples stayed within 64 MB of these figures. | ||
| heapReportAgeS: Math.round((Date.now() - report.sampledAt) / 1000), | ||
| hostHeapMB: Math.round(report.hostBytes / MB), | ||
| totalHeapMB: Math.round(utilityWorkerHeapTotal(report) / MB), | ||
| // The total covers the readers sampled then; some may have exited before this breadcrumb. | ||
| heapReportWorkers: report.workers.length, | ||
| // Unknown readings are left out of the total, so a nonzero count marks it as incomplete. | ||
| heapReportUnknown: report.workers.filter((worker) => worker.bytes === null).length | ||
| } | ||
| workers.forEach((worker, index) => { | ||
| const heap = heaps.get(worker.id) | ||
| const bytes = heap?.bytes | ||
| data[`w${index}_heapMB`] = typeof bytes === 'number' ? Math.round(bytes / MB) : null | ||
| if (heap?.estimated) { | ||
| data[`w${index}_heapEstimated`] = true | ||
| } | ||
| }) | ||
| return data | ||
| } | ||
|
|
||
| /** Its own coalescing key, so host and main pressure never suppress each other. */ | ||
| export function recordUtilityWorkerHeapPressure( | ||
| serviceName: string, | ||
| report: UtilityWorkerHeapReport, | ||
| workers: readonly HostedWorker[] | ||
| ): void { | ||
| if (utilityWorkerHeapTotal(report) < WORKER_HEAP_BREADCRUMB_BYTES) { | ||
| return | ||
| } | ||
| const data = utilityWorkerHeapData(report, workers) | ||
| workers.forEach((worker, index) => { | ||
| data[`w${index}_lastReply`] = worker.lastReplyType | ||
| }) | ||
| recordCoalescedDurableCrashBreadcrumb({ | ||
| name: 'worker_heap_pressure', | ||
| data: { serviceName, workers: workers.length, ...data }, | ||
| coalesceKey: `worker_heap_pressure:${serviceName}`, | ||
| minIntervalMs: WORKER_HEAP_BREADCRUMB_MIN_INTERVAL_MS | ||
| }) | ||
| } |
29 changes: 29 additions & 0 deletions
29
src/main/utility-worker-host/utility-worker-heap-sampler.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,29 @@ | ||
| import { expect, it } from 'vitest' | ||
| import { utilityWorkerHeapReportChanged } from './utility-worker-heap-sampler' | ||
|
|
||
| const MB = 2 ** 20 | ||
| function report(hostMB: number, ...workers: [number, number | null][]) { | ||
| return { | ||
| sampledAt: 0, | ||
| hostBytes: hostMB * MB, | ||
| workers: workers.map(([id, mb]) => ({ | ||
| id, | ||
| bytes: mb === null ? null : mb * MB, | ||
| estimated: false | ||
| })) | ||
| } | ||
| } | ||
|
|
||
| it('posts the first report and real moves, and stays quiet while the heaps hold steady', () => { | ||
| const steady = report(64, [1, 1200], [2, 400]) | ||
| expect(utilityWorkerHeapReportChanged(undefined, steady)).toBe(true) | ||
| expect(utilityWorkerHeapReportChanged(steady, report(70, [1, 1210], [2, 410]))).toBe(false) | ||
| // Same total, but the reader holding the memory changed. | ||
| expect(utilityWorkerHeapReportChanged(steady, report(64, [1, 400], [2, 1200]))).toBe(true) | ||
| // A replaced reader is a different isolate even at the same size. | ||
| expect(utilityWorkerHeapReportChanged(steady, report(64, [1, 1200], [3, 400]))).toBe(true) | ||
| expect(utilityWorkerHeapReportChanged(steady, report(64, [1, 1200], [2, null]))).toBe(true) | ||
| // Crossing the breadcrumb mark is reported even when nothing moved 64 MB. | ||
| const below = report(64, [1, 1000], [2, 450]) | ||
| expect(utilityWorkerHeapReportChanged(below, report(64, [1, 1000], [2, 480]))).toBe(true) | ||
| }) |
118 changes: 118 additions & 0 deletions
118
src/main/utility-worker-host/utility-worker-heap-sampler.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,118 @@ | ||
| import { getHeapStatistics } from 'node:v8' | ||
| import type { Worker } from 'node:worker_threads' | ||
| import { readWorkerSendLedger } from '../worker-threads/worker-send-ledger' | ||
| import { | ||
| readWorkerHeap, | ||
| WORKER_HEAP_BREADCRUMB_BYTES, | ||
| WORKER_HEAP_PRESSURED_BYTES, | ||
| WORKER_HEAP_PRESSURED_SAMPLE_INTERVAL_MS, | ||
| WORKER_HEAP_SAMPLE_INTERVAL_MS | ||
| } from '../worker-threads/worker-heap-sample' | ||
| import { | ||
| type UtilityWorkerHeapReport, | ||
| utilityWorkerHeapTotal | ||
| } from './utility-worker-host-protocol' | ||
|
|
||
| /** Smaller moves are noise for an OOM report and would only add IPC. */ | ||
| const REPORT_CHANGE_BYTES = 64 * 2 ** 20 | ||
| const MARKS = [WORKER_HEAP_PRESSURED_BYTES, WORKER_HEAP_BREADCRUMB_BYTES] | ||
|
|
||
| /** Any isolate counts on its own, so one reader growing while another shrinks is still reported. */ | ||
| export function utilityWorkerHeapReportChanged( | ||
| last: UtilityWorkerHeapReport | undefined, | ||
| next: UtilityWorkerHeapReport | ||
| ): boolean { | ||
| if (!last || last.workers.length !== next.workers.length) { | ||
| return true | ||
| } | ||
| const moved = (a: number | null | undefined, b: number | null): boolean => | ||
| a === undefined || | ||
| (a === null) !== (b === null) || | ||
| Math.abs((a ?? 0) - (b ?? 0)) >= REPORT_CHANGE_BYTES | ||
| const before = new Map(last.workers.map((worker) => [worker.id, worker.bytes])) | ||
| const lastTotal = utilityWorkerHeapTotal(last) | ||
| const nextTotal = utilityWorkerHeapTotal(next) | ||
| return ( | ||
| moved(last.hostBytes, next.hostBytes) || | ||
| moved(lastTotal, nextTotal) || | ||
| MARKS.some((mark) => lastTotal >= mark !== nextTotal >= mark) || | ||
| next.workers.some((worker) => moved(before.get(worker.id), worker.bytes)) | ||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * Samples the host's heaps on the main process's cadence and posts only real changes, so a steady | ||
| * host sends main nothing. The utility process can't annotate its own crash, so main keeps the last | ||
| * report for the exit breadcrumb. | ||
| */ | ||
| export function sampleUtilityWorkerHeaps( | ||
| workers: ReadonlyMap<number, Worker>, | ||
| post: (report: UtilityWorkerHeapReport) => void | ||
| ): { workersChanged(): void } { | ||
| let timer: ReturnType<typeof setTimeout> | undefined | ||
| let sampling = false | ||
| let last: UtilityWorkerHeapReport | undefined | ||
| const schedule = (delayMs: number): void => { | ||
| // Diagnostics must never take the reader host down with an unhandled rejection. | ||
| timer = setTimeout(() => void sample().catch(() => undefined), delayMs) | ||
| timer.unref?.() | ||
| } | ||
| const sample = async (): Promise<void> => { | ||
| timer = undefined | ||
| sampling = true | ||
| let delayMs = WORKER_HEAP_SAMPLE_INTERVAL_MS | ||
| try { | ||
| const ledger = new Map(readWorkerSendLedger().map((slot) => [slot.threadId, slot])) | ||
| const readings = await Promise.all( | ||
| [...workers].map(async ([id, worker]) => ({ | ||
| id, | ||
| ...(await readWorkerHeap(worker, ledger.get(worker.threadId))) | ||
| })) | ||
| ) | ||
| // Readers that exited during the reads no longer count; ones that arrived get sampled soon. | ||
| const live = readings.filter((reading) => workers.has(reading.id)) | ||
| // After the worker reads, which can take seconds, so the host's figure is current. | ||
| const report = { | ||
| sampledAt: Date.now(), | ||
| hostBytes: getHeapStatistics().total_heap_size, | ||
| workers: live | ||
| } | ||
| if ( | ||
| live.length < workers.size || | ||
| utilityWorkerHeapTotal(report) >= WORKER_HEAP_PRESSURED_BYTES | ||
| ) { | ||
| delayMs = WORKER_HEAP_PRESSURED_SAMPLE_INTERVAL_MS | ||
| } | ||
| if (utilityWorkerHeapReportChanged(last, report)) { | ||
| last = report | ||
| post(report) | ||
| } | ||
| } finally { | ||
| sampling = false | ||
| if (workers.size > 0 && !timer) { | ||
| schedule(delayMs) | ||
| } | ||
| } | ||
| } | ||
| return { | ||
| workersChanged: () => { | ||
| if (workers.size === 0) { | ||
| clearTimeout(timer) | ||
| timer = undefined | ||
| // An idle host can live 30 s more; its exit must not report readers that already left. | ||
| const idle = { | ||
| sampledAt: Date.now(), | ||
| hostBytes: getHeapStatistics().total_heap_size, | ||
| workers: [] | ||
| } | ||
| if (utilityWorkerHeapReportChanged(last, idle)) { | ||
| last = idle | ||
| post(idle) | ||
| } | ||
| } else if (!timer && !sampling) { | ||
| // The first report comes soon, so a host that dies young still says what it held. | ||
| schedule(WORKER_HEAP_PRESSURED_SAMPLE_INTERVAL_MS) | ||
| } | ||
| } | ||
| } | ||
| } | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import type { Worker } from 'node:worker_threads' | ||
| import type { WorkerSendLedgerEntry } from './worker-send-ledger' | ||
|
|
||
| /** | ||
| * Heap sampling shared by every process that runs worker threads. Node only: a utility process | ||
| * has no crash reporter, so callers own annotations and breadcrumbs. | ||
| */ | ||
| export const WORKER_HEAP_SAMPLE_INTERVAL_MS = 60_000 | ||
| export const WORKER_HEAP_PRESSURED_SAMPLE_INTERVAL_MS = 10_000 | ||
| export const WORKER_HEAP_PRESSURED_BYTES = 2 ** 30 | ||
| export const WORKER_HEAP_BREADCRUMB_BYTES = 1.5 * 2 ** 30 | ||
| export const WORKER_HEAP_BREADCRUMB_MIN_INTERVAL_MS = 10 * 60_000 | ||
| /** A worker blocked in native code (SQLite) answers only when it returns to JS. */ | ||
| const WORKER_HEAP_READ_TIMEOUT_MS = 2_000 | ||
| const MB = 2 ** 20 | ||
|
|
||
| /** Committed heap; when the worker can't answer, the used heap its last send recorded, if any. */ | ||
| export type WorkerHeapReading = { bytes: number | null; estimated: boolean } | ||
|
|
||
| export async function readWorkerHeap( | ||
| worker: Worker, | ||
| ledger: WorkerSendLedgerEntry | undefined | ||
| ): Promise<WorkerHeapReading> { | ||
| let timer: ReturnType<typeof setTimeout> | undefined | ||
| const timeout = new Promise<never>((_, reject) => { | ||
| timer = setTimeout( | ||
| () => reject(new Error('worker heap read timed out')), | ||
| WORKER_HEAP_READ_TIMEOUT_MS | ||
| ) | ||
| }) | ||
| try { | ||
| const stats = await Promise.race([ | ||
| Promise.resolve().then(() => worker.getHeapStatistics()), | ||
| timeout | ||
| ]) | ||
| return { bytes: stats.total_heap_size, estimated: false } | ||
| } catch { | ||
| // The ledger's heap field stays 0 until the worker's first send writes it. | ||
| const recorded = ledger && ledger.heapUsedMB > 0 ? ledger.heapUsedMB * MB : null | ||
| return { bytes: recorded, estimated: true } | ||
| } finally { | ||
| clearTimeout(timer) | ||
| } | ||
| } |
Oops, something went wrong.
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.