Skip to content
2 changes: 1 addition & 1 deletion src/main/utility-worker-host/hosted-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export class HostedWorker extends EventEmitter {
}
}

receive(event: Exclude<UtilityWorkerHostEvent, { type: 'ready' }>): void {
receive(event: Exclude<UtilityWorkerHostEvent, { type: 'ready' | 'heap' }>): void {
this.heard = true
this.unheardPosts = []
if (event.type === 'error') {
Expand Down
64 changes: 64 additions & 0 deletions src/main/utility-worker-host/utility-worker-heap-report.ts
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 src/main/utility-worker-host/utility-worker-heap-sampler.test.ts
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 src/main/utility-worker-host/utility-worker-heap-sampler.ts
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
Comment thread
brennanb2025 marked this conversation as resolved.
Resolved
// 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)
}
}
}
}
6 changes: 6 additions & 0 deletions src/main/utility-worker-host/utility-worker-host-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Worker } from 'node:worker_threads'
import { installFatalSignalListenerGuard } from '../crash-reporting/fatal-signal-listener-guard'
import { spawnWorkerThread } from '../worker-threads/worker-thread-spawn'
import { setWorkerLargeSendLog } from '../worker-threads/worker-send-ledger'
import { sampleUtilityWorkerHeaps } from './utility-worker-heap-sampler'
import {
UTILITY_WORKER_MESSAGE_CHUNK_BYTES,
type UtilityWorkerFailure,
Expand All @@ -22,6 +23,9 @@ if (!parent) {
}
const port = parent
const workers = new Map<number, Worker>()
const heaps = sampleUtilityWorkerHeaps(workers, (report) =>
port.postMessage({ type: 'heap', report })
)

function failure(error: unknown): UtilityWorkerFailure {
const value = error instanceof Error ? error : new Error(String(error))
Expand Down Expand Up @@ -77,10 +81,12 @@ port.on('message', ({ data: request }) => {
execArgv: []
})
workers.set(id, worker)
heaps.workersChanged()
worker.on('message', (bytes: Uint8Array) => relay(id, bytes))
worker.on('error', (error) => port.postMessage({ type: 'error', id, error: failure(error) }))
worker.once('exit', (code) => {
workers.delete(id)
heaps.workersChanged()
port.postMessage({ type: 'exit', id, code })
})
} catch (error) {
Expand Down
12 changes: 12 additions & 0 deletions src/main/utility-worker-host/utility-worker-host-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,23 @@ export type UtilityWorkerHostRequest =

export type UtilityWorkerFailure = { name: string; message: string; code?: string }

/** Committed heap of the host isolate and of each worker by its spawn id; null when unknown. */
export type UtilityWorkerHeapReport = {
sampledAt: number
hostBytes: number
workers: { id: number; bytes: number | null; estimated: boolean }[]
}

export function utilityWorkerHeapTotal(report: UtilityWorkerHeapReport): number {
return report.workers.reduce((sum, worker) => sum + (worker.bytes ?? 0), report.hostBytes)
}

/** Worker messages travel as v8-serialized bytes, split so no IPC message passes the chunk size. */
export type UtilityWorkerHostEvent =
| { type: 'ready' }
| { type: 'message'; id: number; bytes: Uint8Array; more: boolean }
| { type: 'error'; id: number; error: UtilityWorkerFailure }
| { type: 'exit'; id: number; code: number }
| { type: 'heap'; report: UtilityWorkerHeapReport }

export const UTILITY_WORKER_MESSAGE_CHUNK_BYTES = 32 * 2 ** 20
14 changes: 13 additions & 1 deletion src/main/utility-worker-host/utility-worker-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@ import { app, utilityProcess, type UtilityProcess } from 'electron'
import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting/crash-reporting'
import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb'
import { HostedWorker } from './hosted-worker'
import {
recordUtilityWorkerHeapPressure,
utilityWorkerHeapData
} from './utility-worker-heap-report'
import type {
HostedWorkerThread,
UtilityWorkerHeapReport,
UtilityWorkerHostEvent,
UtilityWorkerHostRequest,
UtilityWorkerSpawn
Expand All @@ -28,6 +33,7 @@ type Host = {
readyTimer: ReturnType<typeof setTimeout>
idleTimer?: ReturnType<typeof setTimeout>
retired: boolean
heap?: UtilityWorkerHeapReport
}

/** A child still launching has no PID to kill yet; kill it once it has one. */
Expand Down Expand Up @@ -135,6 +141,11 @@ export class UtilityWorkerHost {
}
return
}
if (event.type === 'heap') {
host.heap = event.report
recordUtilityWorkerHeapPressure(this.serviceName, event.report, [...host.workers.values()])
return
}
const worker = host.workers.get(event.id)
if (!worker) {
return
Expand Down Expand Up @@ -223,7 +234,8 @@ export class UtilityWorkerHost {
const data: CrashReportBreadcrumbData = {
serviceName: this.serviceName,
code,
workers: workers.length
workers: workers.length,
...utilityWorkerHeapData(host.heap, workers)
}
workers.forEach((worker, index) => {
data[`w${index}_lastReply`] = worker.lastReplyType
Expand Down
44 changes: 44 additions & 0 deletions src/main/worker-threads/worker-heap-sample.ts
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)
}
}
Loading
Loading