fix(crash-reporting): disambiguate renderer recovery from app relaunches (#9223)

* fix(crash-reporting): disambiguate main process relaunches

* fix(crash-reporting): trace all app relaunch causes
This commit is contained in:
Brennan Benson
2026-07-17 15:27:39 -07:00
committed by GitHub
parent ef03a50b1d
commit 3fd73ee848
15 changed files with 227 additions and 20 deletions
+35
View File
@@ -0,0 +1,35 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { appRelaunchMock, recordDurableCrashBreadcrumbMock } = vi.hoisted(() => ({
appRelaunchMock: vi.fn(),
recordDurableCrashBreadcrumbMock: vi.fn()
}))
vi.mock('electron', () => ({ app: { relaunch: appRelaunchMock } }))
vi.mock('./crash-reporting/durable-crash-breadcrumb', () => ({
recordDurableCrashBreadcrumb: recordDurableCrashBreadcrumbMock
}))
import { relaunchApp } from './app-relaunch'
beforeEach(() => {
appRelaunchMock.mockReset()
recordDurableCrashBreadcrumbMock.mockReset()
})
describe('relaunchApp', () => {
it('durably records the reason before scheduling the replacement process', () => {
relaunchApp('gpu-fallback', { processReason: 'crashed', exitCode: 5 })
expect(recordDurableCrashBreadcrumbMock).toHaveBeenCalledOnce()
expect(recordDurableCrashBreadcrumbMock).toHaveBeenCalledWith('app_relaunch_requested', {
processReason: 'crashed',
exitCode: 5,
reason: 'gpu-fallback'
})
expect(appRelaunchMock).toHaveBeenCalledOnce()
expect(recordDurableCrashBreadcrumbMock.mock.invocationCallOrder[0]).toBeLessThan(
appRelaunchMock.mock.invocationCallOrder[0]
)
})
})
+17
View File
@@ -0,0 +1,17 @@
import { app } from 'electron'
import type { CrashReportBreadcrumbData } from '../shared/crash-reporting'
import { recordDurableCrashBreadcrumb } from './crash-reporting/durable-crash-breadcrumb'
export type AppRelaunchReason =
| 'admin-restart'
| 'gpu-fallback'
| 'profile-switch'
| 'profile-transfer'
| 'renderer-request'
export function relaunchApp(reason: AppRelaunchReason, data?: CrashReportBreadcrumbData): void {
// Why: the current process can exit immediately after app.relaunch(), so
// persist the cause before Electron schedules the replacement process.
recordDurableCrashBreadcrumb('app_relaunch_requested', { ...data, reason })
app.relaunch()
}
@@ -31,6 +31,22 @@ afterEach(() => {
})
describe('recordDurableCrashBreadcrumb', () => {
it('attaches main-process identity when the event has no other data', () => {
recordDurableCrashBreadcrumb('renderer_recovery_reload')
expect(getCrashBreadcrumbSnapshot()).toEqual([
expect.objectContaining({
name: 'renderer_recovery_reload',
data: {
mainProcessPid: process.pid,
mainProcessLaunchId: expect.any(String),
mainProcessStartedAt: expect.any(String)
}
})
])
expect(sink.flushMock).toHaveBeenCalledOnce()
})
it('records, traces, and flushes a sanitized crash breadcrumb', () => {
recordDurableCrashBreadcrumb('process_gone_suppressed', {
source: 'renderer',
@@ -40,7 +56,13 @@ describe('recordDurableCrashBreadcrumb', () => {
expect(getCrashBreadcrumbSnapshot()).toEqual([
expect.objectContaining({
name: 'process_gone_suppressed',
data: { source: 'renderer', path: '[redacted-path]' }
data: expect.objectContaining({
source: 'renderer',
path: '[redacted-path]',
mainProcessPid: process.pid,
mainProcessLaunchId: expect.any(String),
mainProcessStartedAt: expect.any(String)
})
})
])
expect(sink.records).toEqual([
@@ -48,7 +70,8 @@ describe('recordDurableCrashBreadcrumb', () => {
name: 'crash.breadcrumb',
attributes: expect.objectContaining({
kind: 'crash-breadcrumb',
'breadcrumb.name': 'process_gone_suppressed'
'breadcrumb.name': 'process_gone_suppressed',
'breadcrumb.data': expect.objectContaining({ mainProcessPid: process.pid })
}),
exit: { _tag: 'Success' }
})
@@ -5,6 +5,7 @@ import {
} from '../../shared/crash-reporting'
import { flushActiveSink, startSpan } from '../observability/tracer'
import { recordCrashBreadcrumb } from './crash-breadcrumb-store'
import { getMainProcessLifecycleIdentity } from './main-process-lifecycle-identity'
export function recordDurableCrashBreadcrumb(
name: string,
@@ -12,14 +13,20 @@ export function recordDurableCrashBreadcrumb(
failureCause?: string
): void {
const sanitizedName = sanitizeCrashReportString(name)
const sanitizedData = data ? sanitizeCrashReportDetails(data) : undefined
recordCrashBreadcrumb(sanitizedName, sanitizedData)
const sanitizedData = data ? sanitizeCrashReportDetails(data) : {}
// Why: durable events survive renderer replacement, so carrying the main
// identity here distinguishes renderer recovery from a true app relaunch.
const lifecycleData = {
...sanitizedData,
...getMainProcessLifecycleIdentity()
}
recordCrashBreadcrumb(sanitizedName, lifecycleData)
const span = startSpan('crash.breadcrumb', {
attributes: {
kind: 'crash-breadcrumb',
'breadcrumb.name': sanitizedName,
...(sanitizedData ? { 'breadcrumb.data': sanitizedData } : {})
'breadcrumb.data': lifecycleData
}
})
if (failureCause) {
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest'
import { getMainProcessLifecycleIdentity } from './main-process-lifecycle-identity'
describe('main process lifecycle identity', () => {
it('stays stable for the lifetime of the main process', () => {
const first = getMainProcessLifecycleIdentity()
const second = getMainProcessLifecycleIdentity()
expect(second).toBe(first)
expect(first).toEqual({
mainProcessPid: process.pid,
mainProcessLaunchId: expect.stringMatching(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
),
mainProcessStartedAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/)
})
})
})
@@ -0,0 +1,19 @@
import { randomUUID } from 'node:crypto'
export type MainProcessLifecycleIdentity = Readonly<{
mainProcessPid: number
mainProcessLaunchId: string
mainProcessStartedAt: string
}>
// Why: renderer reloads reuse the Electron main process, while true app
// relaunches must receive a new ID even when the OS later recycles its PID.
const mainProcessLifecycleIdentity: MainProcessLifecycleIdentity = Object.freeze({
mainProcessPid: process.pid,
mainProcessLaunchId: randomUUID(),
mainProcessStartedAt: new Date(Date.now() - process.uptime() * 1_000).toISOString()
})
export function getMainProcessLifecycleIdentity(): MainProcessLifecycleIdentity {
return mainProcessLifecycleIdentity
}
@@ -108,11 +108,25 @@ describe('recordProcessGoneCrash', () => {
await vi.waitFor(() => expect(record).toHaveBeenCalledOnce())
expect(record).toHaveBeenCalledWith(
expect.objectContaining({ source: 'renderer', reason: 'crashed', exitCode: 5 })
expect.objectContaining({
source: 'renderer',
reason: 'crashed',
exitCode: 5,
details: expect.objectContaining({
mainProcessPid: process.pid,
mainProcessLaunchId: expect.any(String),
mainProcessStartedAt: expect.any(String)
})
})
)
expect(sink.records).toEqual([
expect.objectContaining({
name: 'electron.process_gone',
attributes: expect.objectContaining({
'app.main_process.pid': process.pid,
'app.main_process.launch_id': expect.any(String),
'app.main_process.started_at': expect.any(String)
}),
exit: expect.objectContaining({ _tag: 'Failure' })
})
])
@@ -18,6 +18,7 @@ import {
processGoneDedupe,
type ProcessGoneDedupe
} from './process-gone-dedupe'
import { getMainProcessLifecycleIdentity } from './main-process-lifecycle-identity'
import { flushActiveSink, startSpan } from '../observability/tracer'
export type ProcessGoneCrashEvent = {
@@ -84,7 +85,11 @@ export function recordProcessGoneCrash(
if (!claim) {
return
}
const crashDetails = buildProcessGoneCrashDetails(event.details)
const mainProcessLifecycle = getMainProcessLifecycleIdentity()
const crashDetails = buildProcessGoneCrashDetails({
...event.details,
...mainProcessLifecycle
})
const breadcrumbs = getCrashBreadcrumbSnapshot()
const span = startSpan('electron.process_gone', {
attributes: {
@@ -98,6 +103,9 @@ export function recordProcessGoneCrash(
arch: process.arch,
electronVersion: process.versions.electron,
chromeVersion: process.versions.chrome,
'app.main_process.pid': mainProcessLifecycle.mainProcessPid,
'app.main_process.launch_id': mainProcessLifecycle.mainProcessLaunchId,
'app.main_process.started_at': mainProcessLifecycle.mainProcessStartedAt,
details: crashDetails,
breadcrumbs
}
+17 -5
View File
@@ -18,6 +18,7 @@ import { ensureActiveOrcaProfile, initOrcaProfilePaths } from './orca-profiles/p
import { getOrcaCloudAuthConfig } from './orca-profiles/profile-cloud-auth-config'
import { getProfileUserDataPath } from './orca-profiles/profile-storage-paths'
import { applyAppIcon } from './app-icon'
import { relaunchApp } from './app-relaunch'
import { StatsCollector, initStatsPath } from './stats/collector'
import { ClaudeUsageStore, initClaudeUsagePath } from './claude-usage/store'
import { CodexUsageStore, initCodexUsagePath } from './codex-usage/store'
@@ -176,6 +177,8 @@ import {
recordCoalescedCrashBreadcrumb,
recordCrashBreadcrumb
} from './crash-reporting/crash-breadcrumb-store'
import { recordDurableCrashBreadcrumb } from './crash-reporting/durable-crash-breadcrumb'
import { getMainProcessLifecycleIdentity } from './crash-reporting/main-process-lifecycle-identity'
import { CrashReportStore } from './crash-reporting/crash-report-store'
import {
shouldRecoverRendererAfterProcessGone,
@@ -656,7 +659,8 @@ if (hasSingleInstanceLock) {
crashReports = CrashReportStore.fromUserData()
recordCrashBreadcrumb('app_started', {
packaged: app.isPackaged,
platform: process.platform
platform: process.platform,
...getMainProcessLifecycleIdentity()
})
configureElectronNetworkCompatibility()
enableRendererHeapHeadroom()
@@ -953,7 +957,7 @@ function openMainWindow(): BrowserWindow {
expectedTeardown: getExpectedTeardownScope(webContentsId)
}),
onRendererRecoveryExhausted: ({ details, recentRecoveryCount }) => {
recordCrashBreadcrumb('renderer_recovery_circuit_breaker_open', {
recordDurableCrashBreadcrumb('renderer_recovery_circuit_breaker_open', {
reason: details.reason,
exitCode: details.exitCode ?? null,
recentRecoveryCount
@@ -973,7 +977,7 @@ function openMainWindow(): BrowserWindow {
// local-PTY orphan sweep is skipped for that one reload (#5787).
onBeforeRecoveryReload: (webContentsId) => {
markRecoveryReloadInFlight(webContentsId)
recordCrashBreadcrumb('renderer_recovery_reload')
recordDurableCrashBreadcrumb('renderer_recovery_reload')
}
})
recordCrashBreadcrumb('main_window_created')
@@ -1237,7 +1241,7 @@ async function presentRendererRecoveryPrompt(recentRecoveryCount: number): Promi
? await dialog.showMessageBox(window, options)
: await dialog.showMessageBox(options)
if (response === 0 && mainWindow && !mainWindow.isDestroyed()) {
recordCrashBreadcrumb('renderer_recovery_manual_retry')
recordDurableCrashBreadcrumb('renderer_recovery_manual_retry')
loadMainWindow(mainWindow)
} else if (response === 1) {
isQuitting = true
@@ -1316,7 +1320,11 @@ function handleGpuChildCrash(reason: string, exitCode: number | null): void {
return
}
isQuitting = true
app.relaunch()
relaunchApp('gpu-fallback', {
processReason: reason,
exitCode,
crashesInWindow: result.crashesInWindow
})
app.exit(0)
}
@@ -1824,6 +1832,10 @@ app.whenReady().then(async () => {
// Honors DO_NOT_TRACK / ORCA_TELEMETRY_DISABLED / ORCA_DIAGNOSTICS_DISABLED
// / CI internally; those gates do not need to be re-checked here.
initObservability()
recordDurableCrashBreadcrumb('main_process_lifecycle_started', {
packaged: app.isPackaged,
platform: process.platform
})
// Why: cohort-classifier reads the repo count synchronously at every emit
// for cohort-extended events. The Store has been sync-loaded above, and
// this init runs before any IPC handler is registered and before any
+10
View File
@@ -8,6 +8,7 @@ const {
appRelaunchMock,
spawnMock,
destroySystemTrayMock,
relaunchAppMock,
showOpenDialogMock,
grantFloatingWorkspaceDirectoryMock
} = vi.hoisted(() => ({
@@ -17,6 +18,7 @@ const {
appRelaunchMock: vi.fn(),
spawnMock: vi.fn(),
destroySystemTrayMock: vi.fn(),
relaunchAppMock: vi.fn(),
showOpenDialogMock: vi.fn(),
grantFloatingWorkspaceDirectoryMock: vi.fn()
}))
@@ -91,6 +93,10 @@ vi.mock('../tray/system-tray', () => ({
destroySystemTray: destroySystemTrayMock
}))
vi.mock('../app-relaunch', () => ({
relaunchApp: relaunchAppMock
}))
vi.mock('./floating-workspace-directory', () => ({
ensureDefaultFloatingWorkspacePath: vi.fn(),
grantFloatingWorkspaceDirectory: grantFloatingWorkspaceDirectoryMock,
@@ -113,6 +119,8 @@ describe('registerAppHandlers', () => {
appRelaunchMock.mockReset()
spawnMock.mockReset()
destroySystemTrayMock.mockReset()
relaunchAppMock.mockReset()
relaunchAppMock.mockImplementation(() => appRelaunchMock())
showOpenDialogMock.mockReset()
grantFloatingWorkspaceDirectoryMock.mockReset()
processKillSpy = vi.spyOn(process, 'kill').mockReturnValue(true)
@@ -139,6 +147,7 @@ describe('registerAppHandlers', () => {
await vi.advanceTimersByTimeAsync(150)
expect(destroySystemTrayMock).toHaveBeenCalledTimes(1)
expect(relaunchAppMock).toHaveBeenCalledWith('renderer-request')
expect(appRelaunchMock).toHaveBeenCalledTimes(1)
expect(appExitMock).toHaveBeenCalledWith(0)
expect(destroySystemTrayMock.mock.invocationCallOrder[0]).toBeLessThan(
@@ -187,6 +196,7 @@ describe('registerAppHandlers', () => {
await vi.advanceTimersByTimeAsync(150)
expect(appRelaunchMock).toHaveBeenCalledTimes(1)
expect(relaunchAppMock).toHaveBeenCalledWith('admin-restart')
expect(appQuitMock).toHaveBeenCalledTimes(1)
expect(appExitMock).not.toHaveBeenCalled()
})
+3 -2
View File
@@ -6,6 +6,7 @@ import { app, BrowserWindow, dialog, ipcMain, type IpcMainInvokeEvent } from 'el
import { is } from '@electron-toolkit/utils'
import type { AppIdentity } from '../../shared/app-identity'
import type { FloatingTerminalCwdRequest, MarkdownDocument } from '../../shared/types'
import { relaunchApp } from '../app-relaunch'
import type { Store } from '../persistence'
import { getDevInstanceIdentity } from '../startup/dev-instance-identity'
import { isPwshAvailable } from '../pwsh'
@@ -314,7 +315,7 @@ export function registerAppHandlers(store: Store, options: RegisterAppHandlersOp
// Why: app.exit(0) skips before-quit/will-quit, so clean the Windows tray
// explicitly before relaunching to avoid a stale notification-area icon.
destroySystemTray()
app.relaunch()
relaunchApp('renderer-request')
app.exit(0)
}, 150)
})
@@ -325,7 +326,7 @@ export function registerAppHandlers(store: Store, options: RegisterAppHandlersOp
// checkpoints, runtime metadata, and telemetry flush before exit.
await runBeforeRelaunchCleanup(options.onBeforeRelaunch)
setTimeout(() => {
app.relaunch()
relaunchApp('admin-restart')
app.quit()
}, 150)
})
+10
View File
@@ -5,6 +5,7 @@ const {
appExitMock,
appQuitMock,
appRelaunchMock,
relaunchAppMock,
destroySystemTrayMock,
createLocalOrcaProfileMock,
getOrcaProfileListStateMock,
@@ -16,6 +17,7 @@ const {
appExitMock: vi.fn(),
appQuitMock: vi.fn(),
appRelaunchMock: vi.fn(),
relaunchAppMock: vi.fn(),
destroySystemTrayMock: vi.fn(),
createLocalOrcaProfileMock: vi.fn(),
getOrcaProfileListStateMock: vi.fn(),
@@ -42,6 +44,10 @@ vi.mock('../tray/system-tray', () => ({
destroySystemTray: destroySystemTrayMock
}))
vi.mock('../app-relaunch', () => ({
relaunchApp: relaunchAppMock
}))
vi.mock('../orca-profiles/profile-index-store', () => ({
createLocalOrcaProfile: createLocalOrcaProfileMock,
getOrcaProfileListState: getOrcaProfileListStateMock,
@@ -70,6 +76,8 @@ describe('registerOrcaProfileHandlers', () => {
appExitMock.mockReset()
appQuitMock.mockReset()
appRelaunchMock.mockReset()
relaunchAppMock.mockReset()
relaunchAppMock.mockImplementation(() => appRelaunchMock())
destroySystemTrayMock.mockReset()
createLocalOrcaProfileMock.mockReset()
getOrcaProfileListStateMock.mockReset()
@@ -159,6 +167,7 @@ describe('registerOrcaProfileHandlers', () => {
await vi.advanceTimersByTimeAsync(150)
expect(appRelaunchMock).toHaveBeenCalledOnce()
expect(relaunchAppMock).toHaveBeenCalledWith('profile-switch')
// Why quit, not exit: before-quit/will-quit teardown (scrollback capture,
// PTY kill, daemon checkpoints) must run on a profile switch.
expect(appQuitMock).toHaveBeenCalledOnce()
@@ -294,6 +303,7 @@ describe('registerOrcaProfileHandlers', () => {
await vi.advanceTimersByTimeAsync(150)
expect(appRelaunchMock).toHaveBeenCalledOnce()
expect(relaunchAppMock).toHaveBeenCalledWith('profile-transfer')
expect(appQuitMock).toHaveBeenCalledOnce()
expect(appExitMock).not.toHaveBeenCalled()
})
+5 -4
View File
@@ -1,5 +1,6 @@
import { app, ipcMain } from 'electron'
import type { Store } from '../persistence'
import { relaunchApp, type AppRelaunchReason } from '../app-relaunch'
import type {
CreateLocalOrcaProfileArgs,
CreateLocalOrcaProfileResult,
@@ -153,9 +154,9 @@ async function runBeforeProfileRelaunch(
}
}
function scheduleProfileRelaunch(): void {
function scheduleProfileRelaunch(reason: Extract<AppRelaunchReason, `profile-${string}`>): void {
setTimeout(() => {
app.relaunch()
relaunchApp(reason)
// Why: app.quit() (not app.exit) so before-quit/will-quit still run —
// renderer scrollback capture, PTY kill, stats flush, and daemon final
// checkpoints must not be skipped on a profile switch.
@@ -215,7 +216,7 @@ export function registerOrcaProfileHandlers(
store.flush()
setActiveOrcaProfile(profileId)
scheduleProfileRelaunch()
scheduleProfileRelaunch('profile-switch')
return { status: 'relaunching' }
}
@@ -244,7 +245,7 @@ export function registerOrcaProfileHandlers(
store.freezeWrites()
await runBeforeProfileRelaunch(options.onBeforeRelaunch)
setActiveOrcaProfile(args.targetProfileId)
scheduleProfileRelaunch()
scheduleProfileRelaunch('profile-transfer')
return { ...result, willRelaunch: true }
}
return result
@@ -0,0 +1,30 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { recordDurableCrashBreadcrumbMock } = vi.hoisted(() => ({
recordDurableCrashBreadcrumbMock: vi.fn()
}))
vi.mock('./crash-reporting/durable-crash-breadcrumb', () => ({
recordDurableCrashBreadcrumb: recordDurableCrashBreadcrumbMock
}))
import { recordUpdaterLifecycle } from './updater-lifecycle-diagnostics'
beforeEach(() => {
recordDurableCrashBreadcrumbMock.mockClear()
vi.spyOn(console, 'info').mockImplementation(() => {})
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('recordUpdaterLifecycle', () => {
it('records updater events in the durable lifecycle trace', () => {
recordUpdaterLifecycle('quit_and_install', { version: '1.2.3' })
expect(recordDurableCrashBreadcrumbMock).toHaveBeenCalledWith('updater_quit_and_install', {
version: '1.2.3'
})
})
})
+4 -2
View File
@@ -1,12 +1,14 @@
import type { CrashReportBreadcrumbData } from '../shared/crash-reporting'
import { recordCrashBreadcrumb } from './crash-reporting/crash-breadcrumb-store'
import { recordDurableCrashBreadcrumb } from './crash-reporting/durable-crash-breadcrumb'
export function recordUpdaterLifecycle(
event: string,
data?: CrashReportBreadcrumbData,
options?: { level?: 'info' | 'warn' | 'error'; message?: string }
): void {
recordCrashBreadcrumb(`updater_${event}`, data)
// Why: update-driven relaunches must remain visible in the same durable lane
// as renderer recovery so support traces can distinguish their lifecycles.
recordDurableCrashBreadcrumb(`updater_${event}`, data)
const suffix = data && Object.keys(data).length > 0 ? ` ${JSON.stringify(data)}` : ''
console[options?.level ?? 'info'](`[updater] ${options?.message ?? event}${suffix}`)
}