Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Stop non-crash minidumps prompting a bug report (PRD-7776) (#3379)
Andrew Mikofalvy2e9659f6f650
diff --git a/.changeset/non-crash-minidump-prompt.md b/.changeset/non-crash-minidump-prompt.mdnew file mode 100644index 000000000..e1488fb9b--- /dev/null+++ b/.changeset/non-crash-minidump-prompt.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++OpenKnowledge no longer asks you to report crashes that never happened. Chromium writes a minidump whenever its GPU watchdog thinks a thread has stalled, even when the process recovers and keeps running, and the app had no way to tell that snapshot apart from a real crash. The result was a prompt at the next launch saying the previous session ended uncleanly, for a session that quit normally, recurring at every launch until you filed a report to make it stop. The app now reads the dump's own exception record and recognizes a captured-but-never-faulted snapshot for what it is.++The same fix closes a sharper problem. When a report dialog offers to attach a crash dump, it was resolving the newest dump on disk without checking which crash was being reported, so a watchdog snapshot written after a genuine crash could be attached to a report about that earlier crash, shipping the wrong process's memory under a notice describing a different failure. Dump resolution now steps over snapshots and reaches the dump that actually belongs to the crash being reported.++Real crashes are unaffected, deliberately so. The check keys on a value a real crash cannot carry and compares it exactly, never as a range, because the neighbouring code for an Objective-C exception differs by a single digit and marks a genuine fatal crash. Anything the app cannot read with confidence, including a dump truncated by the very fault that produced it, still prompts and still offers its dump. The behavior currently ships on macOS; Windows and Linux keep exactly today's behavior until their equivalent marker is measured against a real dump on those platforms.diff --git a/packages/desktop/src/main/crash-detection.test.ts b/packages/desktop/src/main/crash-detection.test.tsindex 94d2dbe7c..d186ffbda 100644--- a/packages/desktop/src/main/crash-detection.test.ts+++ b/packages/desktop/src/main/crash-detection.test.ts@@ -60,6 +60,12 @@ interface Rig {ownDump: Buffer;/** The same dump, plus the Crashpad annotations a real one carries. */ownDumpStamped(version: string): Buffer;+ /**+ * Ours, but captured by `CRASHPAD_SIMULATE_CRASH()` rather than by a fault —+ * what Chromium's GPU watchdog leaves behind for a process it then lets keep+ * running.+ */+ ownDumpSimulated: Buffer;/** Flip to false to simulate "no live renderer window can take the event". */setRendererAvailable(available: boolean): void;/** Swap the kernel boot-session identity, simulating a reboot between sessions. */@@ -101,6 +107,9 @@ function makeRig(): Rig {emitted,warnings,ownDump: buildMinidump(ownModules),+ // 'CPsx' — kMachExceptionSimulated. Written as a literal rather than+ // imported from the production module so a change there fails here.+ ownDumpSimulated: buildMinidump(ownModules, { exceptionCode: 0x4350_7378 }),ownDumpStamped: (version: string) =>buildMinidump(ownModules, {annotations: { _productName: 'OpenKnowledge', _version: version, prod: 'Electron' },@@ -127,6 +136,10 @@ function makeRig(): Rig {crashDumpsDir: join(dir, 'crash-dumps'),appBundleRoot,appVersion: CRASHED_VERSION,+ // Pinned so the rig behaves identically on a macOS dev box and on Linux+ // CI. Left to `process.platform`, every crash-kind assertion below would+ // pass vacuously on CI, where the predicate is deliberately inert.+ platform: 'darwin',emit(event) {if (!rendererAvailable) return false;emitted.push(event);@@ -1420,3 +1433,118 @@ describe('the version a boot invitation attributes the crash to', () => {expect(armed.crashedAppVersion).toBe(CRASHED_VERSION);});});++/**+ * Dumps that were captured without a fault.+ *+ * Chromium's GPU watchdog calls `DumpWithoutCrashing()` on a process that+ * merely looks stalled and may then let it keep running. The dump it leaves is+ * genuinely ours, so ownership says `'ours'` and every pre-existing signal+ * treats it as a crash. These tests pin the two consequences that fixes: the+ * app must stop asking about failures that never happened, and — the sharper+ * one — such a dump must never be handed to a report about a real crash.+ *+ * Each boot case runs the two-session shape the rest of this file uses: a+ * first session establishes the minidump baseline and quits cleanly, dumps are+ * seeded after it, and a second session does the detecting. Seeding before the+ * baseline exists would leave every dump filtered out, which reads as a pass+ * for the suppression cases while proving nothing.+ */+describe('non-crash minidumps', () => {+ /** Baseline the store, quit clean, and hand back a rig ready to seed dumps into. */+ function afterCleanQuit(rig: Rig): void {+ const sessionA = createCrashDetection(rig.deps);+ sessionA.detectBootCrash();+ sessionA.markCleanQuit();+ }++ test('a clean quit whose only fresh dump is a snapshot arms nothing', () => {+ const rig = makeRig();+ afterCleanQuit(rig);+ seedMinidump(rig, 'pending/watchdog.dmp', rig.tick(), rig.ownDumpSimulated);++ // Before this change the dump alone armed the prompt, framed as an+ // unclean shutdown for a session that quit cleanly.+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();+ });++ test('a real crash still arms even when a snapshot sits alongside it', () => {+ const rig = makeRig();+ afterCleanQuit(rig);+ const crashedAt = rig.tick();+ seedMinidump(rig, 'pending/real.dmp', crashedAt);+ seedMinidump(rig, 'pending/watchdog.dmp', rig.tick(), rig.ownDumpSimulated);++ // The exclusion is per-dump, never per-scan: one snapshot in the set must+ // not suppress the crash sitting next to it.+ expect(bootInvite(createCrashDetection(rig.deps).detectBootCrash()).eventId).toBe(+ `boot:dump:${crashedAt.getTime()}`,+ );+ });++ test('an unreadable dump still arms — indeterminate is not a non-crash', () => {+ const rig = makeRig();+ afterCleanQuit(rig);+ seedMinidump(rig, 'pending/torn.dmp', rig.tick(), UNPARSEABLE_DUMP);++ // Arming keeps failing open. A dump truncated by the very fault that wrote+ // it must stay reportable.+ expect(createCrashDetection(rig.deps).detectBootCrash()).not.toBeNull();+ });++ test.each<NodeJS.Platform>([+ 'linux',+ 'win32',+ ])('on %s the snapshot still arms, because the predicate is gated off there', (platform) => {+ const rig = makeRig();+ rig.deps.platform = platform;+ afterCleanQuit(rig);+ seedMinidump(rig, 'pending/watchdog.dmp', rig.tick(), rig.ownDumpSimulated);++ // Those platforms' sentinels are known from Crashpad source but have not+ // been measured against a real dump there, so behavior must stay exactly+ // what it is today until one is.+ expect(createCrashDetection(rig.deps).detectBootCrash()).not.toBeNull();+ });++ test('a snapshot alone offers no dump to attach', () => {+ const rig = makeRig();+ const detection = createCrashDetection(rig.deps);+ seedMinidump(rig, 'pending/watchdog.dmp', rig.tick(), rig.ownDumpSimulated);++ detection.handleRenderProcessGone({ reason: 'crashed', exitCode: 5 });++ // Otherwise the report dialog offers to ship GPU process memory for a+ // crash that never occurred, pre-checked.+ expect(rig.emitted.at(-1)?.minidumpAvailable).toBe(false);+ expect(detection.newestMinidumpForReport().path).toBeNull();+ });++ test('a newer snapshot does not shadow the real crash dump being reported', () => {+ const rig = makeRig();+ const detection = createCrashDetection(rig.deps);+ const realPath = seedMinidump(rig, 'pending/real.dmp', rig.tick());+ seedMinidump(rig, 'pending/watchdog.dmp', rig.tick(), rig.ownDumpSimulated);++ // Resolution walks newest-first, so the snapshot is encountered FIRST.+ // Stepping over it rather than stopping is what keeps a legitimate crash+ // report from carrying the wrong process's memory under a consent notice+ // describing a different failure.+ expect(detection.newestMinidumpForReport().path).toBe(realPath);+ });++ test('skipped snapshots are counted apart from foreign and unreadable ones', () => {+ const rig = makeRig();+ const detection = createCrashDetection(rig.deps);+ seedMinidump(rig, 'pending/watchdog.dmp', rig.tick(), rig.ownDumpSimulated);++ detection.handleRenderProcessGone({ reason: 'crashed', exitCode: 5 });++ // Three counters, three meanings. Folded together, "detection declined on+ // purpose" would be indistinguishable from "the parser broke".+ const logged = rig.warnings.at(-1);+ expect(logged?.nonCrashDumpsSkipped).toBe(1);+ expect(logged?.foreignDumpsIgnored).toBe(0);+ expect(logged?.unreadableDumpsSkipped).toBe(0);+ });+});diff --git a/packages/desktop/src/main/crash-detection.ts b/packages/desktop/src/main/crash-detection.tsindex 5acb7ffac..0414ea359 100644--- a/packages/desktop/src/main/crash-detection.ts+++ b/packages/desktop/src/main/crash-detection.ts@@ -60,6 +60,7 @@ import { dirname, join } from 'node:path';import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';import { asReportableAppVersion } from './crashed-app-version.ts';import {+ classifyMinidumpCrashKind,classifyMinidumpOwnership,type MinidumpOwnership,readMinidumpAppVersion,@@ -197,6 +198,14 @@ export interface CrashDetectionDeps {* detected during this boot — that crash belongs to an earlier session.*/appVersion: string;+ /**+ * Which platform's simulated-exception sentinel to recognize in a dump.+ * Injected like everything else here so the crash-kind behavior is testable+ * off the host platform — CI runs Linux, where the predicate is deliberately+ * inert, and reading `process.platform` directly would make every such+ * assertion pass vacuously there while proving nothing.+ */+ platform?: NodeJS.Platform;/*** Push one crash-detected event to a live renderer. Returns false when no* renderer could take it — the event stays armed and is re-offered on the@@ -511,6 +520,10 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {return classifyMinidumpOwnership(path, deps.appBundleRoot);}+ function crashKindOf(path: string) {+ return classifyMinidumpCrashKind(path, deps.platform ?? process.platform);+ }+/** Baseline-filtered dumps from one scan of the crash-dumps dir, newest first. */function freshMinidumpEntries(): MinidumpEntry[] {const entries: MinidumpEntry[] = [];@@ -539,16 +552,30 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {entry: MinidumpEntry | null;foreignSkipped: number;unknownSkipped: number;+ nonCrashSkipped: number;} {let foreignSkipped = 0;let unknownSkipped = 0;+ let nonCrashSkipped = 0;for (const entry of freshMinidumpEntries()) {const ownership = classifyDump(entry.path);- if (ownership === 'ours') return { entry, foreignSkipped, unknownSkipped };+ if (ownership === 'ours') {+ // Skipping rather than stopping is the whole fix. This walk is+ // newest-first and has no idea which crash is being reported, so a+ // snapshot of a process that never faulted — a GPU watchdog capture,+ // say — would otherwise be handed to a report about a genuine crash+ // that happened earlier, under a consent notice describing that other+ // failure. Stepping over it reaches the dump that actually belongs.+ if (crashKindOf(entry.path) === 'non-crash') {+ nonCrashSkipped += 1;+ continue;+ }+ return { entry, foreignSkipped, unknownSkipped, nonCrashSkipped };+ }if (ownership === 'foreign') foreignSkipped += 1;else unknownSkipped += 1;}- return { entry: null, foreignSkipped, unknownSkipped };+ return { entry: null, foreignSkipped, unknownSkipped, nonCrashSkipped };}return {@@ -614,13 +641,26 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {// inherited our exception handler, and an unrelated program aborting is// not this app crashing. Without this the app prompts "the previous// session crashed" after a perfectly clean quit.- const freshDumps = freshMinidumpEntries().map((entry) => ({- entry,- ownership: classifyDump(entry.path),- }));+ const freshDumps = freshMinidumpEntries().map((entry) => {+ const ownership = classifyDump(entry.path);+ return {+ entry,+ ownership,+ // Only asked of dumps that are ours. A foreign dump's crash kind is+ // not this app's business, and asking would cost a second parse of a+ // file already excluded.+ crashKind: ownership === 'ours' ? crashKindOf(entry.path) : null,+ };+ });const foreignDumpCount = freshDumps.filter((d) => d.ownership === 'foreign').length;const unreadableDumpCount = freshDumps.filter((d) => d.ownership === 'unknown').length;- if (foreignDumpCount > 0 || unreadableDumpCount > 0) {+ // Ours, but a snapshot of a process that never faulted: Chromium's GPU+ // watchdog captures one when a thread merely looks stalled, and may then+ // let that process keep running. Counted apart from the two above+ // because it means something different to whoever reads the line —+ // detection worked perfectly and correctly declined to ask.+ const nonCrashDumpCount = freshDumps.filter((d) => d.crashKind === 'non-crash').length;+ if (foreignDumpCount > 0 || unreadableDumpCount > 0 || nonCrashDumpCount > 0) {// Otherwise a suppressed prompt and a detection pipeline that never// ran are indistinguishable in the logs. The unreadable count is the// one to watch: a dump we cannot parse at all is either half-flushed@@ -631,6 +671,7 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {event: 'crash-detection.foreign-dumps-ignored',count: foreignDumpCount,unreadable: unreadableDumpCount,+ nonCrash: nonCrashDumpCount,},'ignored minidumps that this app could not claim',);@@ -639,10 +680,17 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {// crash that wrote it is more likely ours than not, and the cost of being// wrong is one prompt the user dismisses once. The attachment side takes// the opposite default, so an un-ownable dump can still never be sent.+ //+ // A dump we can positively prove was captured without a fault is the one+ // exception, and it is an exclusion by evidence rather than by default:+ // only a value a real crash cannot carry gets a dump dropped here.+ // Anything indeterminate still arms.const newDumps = freshDumps- .filter((d) => d.ownership !== 'foreign')+ .filter((d) => d.ownership !== 'foreign' && d.crashKind !== 'non-crash').map((d) => d.entry.mtimeMs);- const ownedDumpCount = freshDumps.filter((d) => d.ownership === 'ours').length;+ const ownedDumpCount = freshDumps.filter(+ (d) => d.ownership === 'ours' && d.crashKind !== 'non-crash',+ ).length;// A boot-session mismatch means the kernel rebooted after the previous// session was last alive; an os-shutdown marker means the OS killed the@@ -865,6 +913,7 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {// breadcrumb so the counts sit with the crash they explain.foreignDumpsIgnored: owned.foreignSkipped,unreadableDumpsSkipped: owned.unknownSkipped,+ nonCrashDumpsSkipped: owned.nonCrashSkipped,},'renderer process died abnormally',);@@ -901,6 +950,7 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {exitCode: details.exitCode,foreignDumpsIgnored: owned.foreignSkipped,unreadableDumpsSkipped: owned.unknownSkipped,+ nonCrashDumpsSkipped: owned.nonCrashSkipped,...(gpu === null ? {} : { gpuCrashesInWindow: gpu.countInWindow }),...(gpu?.suppressInvite === true ? { invitationSuppressed: 'gpu-recoverable' } : {}),},diff --git a/packages/desktop/src/main/minidump-ownership.test.ts b/packages/desktop/src/main/minidump-ownership.test.tsindex 1b8ab82ea..590d36081 100644--- a/packages/desktop/src/main/minidump-ownership.test.ts+++ b/packages/desktop/src/main/minidump-ownership.test.ts@@ -18,7 +18,11 @@ import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { afterEach, describe, expect, test, vi } from 'vitest';import { buildMinidump, type MinidumpPatch } from './minidump.test-helper.ts';-import { classifyMinidumpOwnership, readMinidumpAppVersion } from './minidump-ownership.ts';+import {+ classifyMinidumpCrashKind,+ classifyMinidumpOwnership,+ readMinidumpAppVersion,+} from './minidump-ownership.ts';const tmpDirs: string[] = [];@@ -499,3 +503,125 @@ describe('crashpad app-version annotations', () => {}});});++/**+ * Did the process actually fault?+ *+ * The failure this guards is one-directional and silent: classify a real crash+ * as "not a crash" and the user is never asked about it, the dump is never+ * offered, and nothing anywhere says so. Every case below is therefore written+ * from the direction of "can a genuine crash be swallowed", not "is the happy+ * path happy".+ *+ * `platform` is passed explicitly rather than read from the process because CI+ * runs Linux, where the predicate is deliberately inert. Left implicit, every+ * assertion here would pass vacuously on CI while proving nothing.+ */+describe('classifyMinidumpCrashKind', () => {+ /** `'CPsx'` — Crashpad's "dump captured, process did not fault" sentinel. */+ const SIMULATED = 0x4350_7378;+ /**+ * `'CPnx'` — `kMachExceptionFromNSException`. ONE hex digit from the+ * sentinel, same `CP` tag, and a genuine fatal crash.+ */+ const FROM_NS_EXCEPTION = 0x4350_6e78;++ function writeDump(patch: MinidumpPatch): string {+ const dir = makeDir();+ const dumpPath = join(dir, 'dump.dmp');+ writeFileSync(dumpPath, buildMinidump([join(dir, 'App.app', 'MacOS', 'App')], patch));+ return dumpPath;+ }++ const kindOf = (patch: MinidumpPatch, platform: NodeJS.Platform = 'darwin') =>+ classifyMinidumpCrashKind(writeDump(patch), platform);++ test('the simulated-exception sentinel reads as a non-crash', () => {+ expect(kindOf({ exceptionCode: SIMULATED })).toBe('non-crash');+ });++ test('kMachExceptionFromNSException is a CRASH despite sharing the CP tag', () => {+ // The whole reason the comparison is exact equality. A range or prefix+ // match over the `CP` family would swallow this, and it is a real fatal+ // crash a user would never then be asked to report.+ expect(kindOf({ exceptionCode: FROM_NS_EXCEPTION })).toBe('crash');+ });++ test.each([+ ['EXC_BREAKPOINT', 0x6],+ ['EXC_BAD_ACCESS', 0x1],+ ['SIGSEGV-shaped', 0xb],+ ['zero', 0x0],+ ['one below the sentinel', SIMULATED - 1],+ ['one above the sentinel', SIMULATED + 1],+ ])('%s reads as a crash', (_label, exceptionCode) => {+ expect(kindOf({ exceptionCode })).toBe('crash');+ });++ test('no exception stream alone is indeterminate, never a non-crash', () => {+ // A dump truncated by the very fault that produced it also has no+ // exception stream. Concluding "no crash" from absence would swallow it.+ expect(kindOf({})).toBe('indeterminate');+ });++ test('no exception stream plus the positive marker reads as a non-crash', () => {+ expect(kindOf({ annotations: { 'is-dump-process-without-crashing': 'true' } })).toBe(+ 'non-crash',+ );+ });++ test('the marker must actually say true', () => {+ expect(kindOf({ annotations: { 'is-dump-process-without-crashing': 'false' } })).toBe(+ 'indeterminate',+ );+ });++ test('an unrelated annotation does not stand in for the marker', () => {+ expect(kindOf({ annotations: { _version: '1.2.3' } })).toBe('indeterminate');+ });++ test('a truncated dump carrying the sentinel is indeterminate, not a non-crash', () => {+ // Truncation must not be readable as absence-of-crash even when the bytes+ // that survived would have said so.+ expect(kindOf({ exceptionCode: SIMULATED, truncateTo: 40 })).toBe('indeterminate');+ });++ test.each([+ ['a bad signature', { signature: 'XXXX', exceptionCode: SIMULATED }],+ ['an unreachable stream directory', { streamDirectoryRva: 0xffff, exceptionCode: SIMULATED }],+ ['an absurd stream count', { streamCount: 0xffff_ffff, exceptionCode: SIMULATED }],+ ])('%s is indeterminate', (_label, patch) => {+ expect(kindOf(patch as MinidumpPatch)).toBe('indeterminate');+ });++ test('a missing file is indeterminate rather than a throw', () => {+ // This runs inside the boot scan; a throw here takes out crash detection.+ expect(classifyMinidumpCrashKind(join(makeDir(), 'absent.dmp'), 'darwin')).toBe(+ 'indeterminate',+ );+ });++ test.each<NodeJS.Platform>([+ 'linux',+ 'win32',+ ])('stays inert on %s even when the dump carries the macOS sentinel', (platform) => {+ // Those platforms' sentinels are known from Crashpad source but have not+ // been measured against a real dump there, so the predicate must not+ // fire. Indeterminate preserves today's behavior exactly.+ expect(kindOf({ exceptionCode: SIMULATED }, platform)).toBe('indeterminate');+ });++ test('reading the crash kind leaves the ownership verdict untouched', () => {+ // Ownership decides whether raw process memory may leave the machine. The+ // two answers are separate exports on separate file handles, and adding an+ // exception stream must not perturb the one that gates attachment.+ const dir = makeDir();+ const bundleRoot = join(dir, 'App.app');+ const dumpPath = join(dir, 'dump.dmp');+ const modulePath = join(bundleRoot, 'Contents', 'MacOS', 'App');+ mkdirSync(join(bundleRoot, 'Contents', 'MacOS'), { recursive: true });+ writeFileSync(dumpPath, buildMinidump([modulePath], { exceptionCode: SIMULATED }));+ expect(classifyMinidumpOwnership(dumpPath, bundleRoot)).toBe('ours');+ expect(classifyMinidumpCrashKind(dumpPath, 'darwin')).toBe('non-crash');+ });+});diff --git a/packages/desktop/src/main/minidump-ownership.ts b/packages/desktop/src/main/minidump-ownership.tsindex 611fa44bf..c853fad02 100644--- a/packages/desktop/src/main/minidump-ownership.ts+++ b/packages/desktop/src/main/minidump-ownership.ts@@ -83,6 +83,48 @@ const DIRECTORY_ENTRY_RVA_OFFSET = 8;const MODULE_LIST_STREAM_TYPE = 4;const MODULE_RECORD_BYTES = 108;const MODULE_NAME_RVA_OFFSET = 20;+/** `ExceptionStream` in the minidump stream-type enum. */+const EXCEPTION_STREAM_TYPE = 6;+/**+ * `MINIDUMP_EXCEPTION_STREAM` is `ThreadId u32`, `__alignment u32`, then the+ * `MINIDUMP_EXCEPTION` record whose first field is the code.+ */+const EXCEPTION_CODE_OFFSET = 8;+const EXCEPTION_CODE_BYTES = 4;++/**+ * `kMachExceptionSimulated` — `'CPsx'`, raised by `CRASHPAD_SIMULATE_CRASH()`+ * to mean "a dump was captured and the process did NOT fault". Chromium's GPU+ * watchdog takes exactly this path when a GPU thread looks stalled, and may+ * then let the process keep running.+ *+ * Compared for EXACT equality, never as a range, prefix, or family. `'CPnx'`+ * (`0x43506e78`, `kMachExceptionFromNSException`) is one hex digit away, shares+ * the same `CP` tag, and marks a GENUINE fatal crash — so a family match would+ * silently stop reporting real crashes, which is the one failure this predicate+ * exists to avoid.+ *+ * Windows (`0x517a7ed`) and Linux (`kSimulatedSigno`) have their own values.+ * They are deliberately absent from the table below: both are known from+ * Crashpad source but unverified against a real dump on those platforms, where+ * `NumberParameters` and the dump directory's own name both differ. Until one+ * is measured there, those platforms resolve to `null` and the predicate stays+ * inert for them.+ */+const SIMULATED_EXCEPTION_CODE_BY_PLATFORM: Partial<Record<NodeJS.Platform, number>> = {+ darwin: 0x4350_7378,+};++/**+ * Crashpad's flat annotation marking the OTHER non-crash flavor:+ * `DumpProcessWithoutCrashing(task_t)` writes a dump carrying no exception+ * stream at all.+ *+ * Requiring this POSITIVE marker is what keeps that branch honest. A missing+ * exception stream is also what a dump truncated by its own crash looks like,+ * and those must stay reportable — so absence alone can never mean "no crash".+ */+const DUMP_WITHOUT_CRASHING_KEY = 'is-dump-process-without-crashing';/*** `MinidumpCrashpadInfo` — Crashpad's own stream, outside the minidump format's@@ -364,3 +406,135 @@ export function readMinidumpAppVersion(dumpPath: string): MinidumpAppVersionReadconst facts = readMinidumpFacts(dumpPath);return { version: facts.appVersion, parseFailed: facts.appVersionParseFailed };}++/**+ * Whether the process this dump describes actually faulted.+ *+ * `'indeterminate'` is not an error channel — it is the answer whenever the+ * dump cannot be read well enough to say, and callers are expected to treat it+ * exactly as they treat a crash. Arming therefore keeps failing OPEN: the cost+ * of being wrong is one prompt a user dismisses, where the cost of the opposite+ * default is a real crash nobody ever hears about.+ */+export type MinidumpCrashKind = 'crash' | 'non-crash' | 'indeterminate';++/**+ * Look up one simple annotation by key.+ *+ * Deliberately NOT folded into the app-version walk above. That walk is reached+ * from the same pass as the ownership verdict, and ownership decides whether a+ * report may carry raw process memory at all; keeping this question on its own+ * file handle means a change here cannot reach that answer by accident. The+ * duplication is the point, not an oversight.+ */+function findSimpleAnnotation(+ fd: number,+ infoRva: number,+ infoSize: number,+ key: string,+): string | null {+ if (infoSize < CRASHPAD_INFO_PREFIX_BYTES) return null;+ const info = readExactly(fd, CRASHPAD_INFO_PREFIX_BYTES, infoRva);+ if (info === null) return null;+ const dictRva = info.readUInt32LE(CRASHPAD_ANNOTATIONS_RVA_OFFSET);+ if (dictRva === 0) return null;+ const count = readExactly(fd, 4, dictRva);+ if (count === null) return null;+ const entryCount = count.readUInt32LE(0);+ if (entryCount === 0 || entryCount > MAX_ANNOTATIONS) return null;+ const declaredBytes = info.readUInt32LE(CRASHPAD_ANNOTATIONS_SIZE_OFFSET);+ if (declaredBytes < 4 + entryCount * ANNOTATION_ENTRY_BYTES) return null;++ const entries = readExactly(fd, entryCount * ANNOTATION_ENTRY_BYTES, dictRva + 4);+ if (entries === null) return null;+ for (let i = 0; i < entryCount; i += 1) {+ const at = i * ANNOTATION_ENTRY_BYTES;+ if (readAnnotationString(fd, entries.readUInt32LE(at)) !== key) continue;+ return readAnnotationString(fd, entries.readUInt32LE(at + 4));+ }+ return null;+}++/**+ * Classify `dumpPath` as a real fault, a captured-but-not-crashed snapshot, or+ * unreadable.+ *+ * Four branches, in order:+ *+ * 1. Exception stream present, code EXACTLY the platform sentinel → non-crash.+ * 2. Exception stream present, any other code → crash.+ * 3. No exception stream, directory parsed, AND the positive+ * `is-dump-process-without-crashing` annotation says `true` → non-crash.+ * 4. Anything else, including any read that fails → indeterminate.+ *+ * Branch 3's annotation requirement is load-bearing. Concluding "no crash" from+ * a MISSING stream would also swallow a dump truncated by the very fault that+ * produced it, which is a real crash nobody would ever be asked about.+ *+ * Returns `'indeterminate'` outright on any platform with no verified sentinel,+ * which leaves that platform's behavior exactly as it was.+ */+export function classifyMinidumpCrashKind(+ dumpPath: string,+ platform: NodeJS.Platform = process.platform,+): MinidumpCrashKind {+ const simulatedCode = SIMULATED_EXCEPTION_CODE_BY_PLATFORM[platform];+ if (simulatedCode === undefined) return 'indeterminate';++ let fd: number | null = null;+ try {+ fd = openSync(dumpPath, 'r');+ const header = readExactly(fd, HEADER_BYTES, 0);+ if (header === null || header.readUInt32LE(0) !== MINIDUMP_SIGNATURE) return 'indeterminate';+ const streamCount = header.readUInt32LE(NUMBER_OF_STREAMS_OFFSET);+ if (streamCount === 0 || streamCount > MAX_STREAMS) return 'indeterminate';++ const directory = readExactly(+ fd,+ streamCount * DIRECTORY_ENTRY_BYTES,+ header.readUInt32LE(STREAM_DIRECTORY_RVA_OFFSET),+ );+ // The directory itself must parse before an absent stream can mean anything.+ if (directory === null) return 'indeterminate';++ let exceptionRva: number | null = null;+ let crashpadInfoRva: number | null = null;+ let crashpadInfoSize = 0;+ for (let i = 0; i < streamCount; i += 1) {+ const at = i * DIRECTORY_ENTRY_BYTES;+ const streamType = directory.readUInt32LE(at);+ if (streamType === EXCEPTION_STREAM_TYPE && exceptionRva === null) {+ exceptionRva = directory.readUInt32LE(at + DIRECTORY_ENTRY_RVA_OFFSET);+ } else if (streamType === CRASHPAD_INFO_STREAM_TYPE && crashpadInfoRva === null) {+ crashpadInfoRva = directory.readUInt32LE(at + DIRECTORY_ENTRY_RVA_OFFSET);+ crashpadInfoSize = directory.readUInt32LE(at + DIRECTORY_ENTRY_SIZE_OFFSET);+ }+ if (exceptionRva !== null && crashpadInfoRva !== null) break;+ }++ if (exceptionRva !== null) {+ const code = readExactly(fd, EXCEPTION_CODE_BYTES, exceptionRva + EXCEPTION_CODE_OFFSET);+ if (code === null) return 'indeterminate';+ return code.readUInt32LE(0) === simulatedCode ? 'non-crash' : 'crash';+ }++ if (crashpadInfoRva === null) return 'indeterminate';+ const marker = findSimpleAnnotation(+ fd,+ crashpadInfoRva,+ crashpadInfoSize,+ DUMP_WITHOUT_CRASHING_KEY,+ );+ return marker === 'true' ? 'non-crash' : 'indeterminate';+ } catch {+ return 'indeterminate';+ } finally {+ if (fd !== null) {+ try {+ closeSync(fd);+ } catch {+ // Descriptor already reclaimed; nothing left to release.+ }+ }+ }+}diff --git a/packages/desktop/src/main/minidump.test-helper.ts b/packages/desktop/src/main/minidump.test-helper.tsindex 3c41ec0d0..70b7e71d0 100644--- a/packages/desktop/src/main/minidump.test-helper.ts+++ b/packages/desktop/src/main/minidump.test-helper.ts@@ -24,6 +24,19 @@ const CRASHPAD_INFO_BYTES = 64;const CRASHPAD_ANNOTATIONS_SIZE_OFFSET = 36;const CRASHPAD_ANNOTATIONS_RVA_OFFSET = 40;const ANNOTATION_ENTRY_BYTES = 8;+const EXCEPTION_STREAM_TYPE = 6;+/**+ * `MINIDUMP_EXCEPTION_STREAM`: `ThreadId u32`, `__alignment u32`, the 152-byte+ * `MINIDUMP_EXCEPTION` record, then a `MINIDUMP_LOCATION_DESCRIPTOR` for the+ * thread context. Only the code is read here, but the stream is emitted at its+ * true size so a fixture cannot pass by being conveniently short.+ *+ * `ExceptionInformation` is a FIXED 15-entry array, not one sized by+ * `NumberParameters` — advancing by the latter is a documented way to misparse+ * this record.+ */+const EXCEPTION_STREAM_BYTES = 168;+const EXCEPTION_CODE_OFFSET = 8;/*** Per-field overrides. Most corrupt a single value the parser reads;@@ -80,13 +93,22 @@ export interface MinidumpPatch {annotationValueRva?: number;/** First entry's value block's claimed BYTE length. */annotationValueByteLength?: number;+ /**+ * Emit an ExceptionStream carrying this code. Omitted entirely when absent,+ * which is what both a pre-exception-stream dump and the+ * `DumpProcessWithoutCrashing` flavor look like — so the crash-kind parse has+ * to distinguish those by annotation rather than by the stream's absence.+ */+ exceptionCode?: number;}export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}): Buffer {const decoyStreams = patch.streamsBefore ?? 0;const annotationEntries =patch.annotations === undefined ? null : Object.entries(patch.annotations);- const directoryEntries = decoyStreams + 1 + (annotationEntries === null ? 0 : 1);+ const hasException = patch.exceptionCode !== undefined;+ const directoryEntries =+ decoyStreams + 1 + (annotationEntries === null ? 0 : 1) + (hasException ? 1 : 0);const directoryRva = HEADER_BYTES;const moduleListRva = directoryRva + directoryEntries * DIRECTORY_ENTRY_BYTES;const moduleListBytes = 4 + modulePaths.length * MODULE_RECORD_BYTES;@@ -157,6 +179,18 @@ export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}):cursor = stringCursor;}+ // Laid out last so adding one cannot shift any offset an existing fixture+ // already depends on.+ const exceptionBlocks: Buffer[] = [];+ const exceptionRva = cursor;+ if (hasException) {+ const exception = Buffer.alloc(EXCEPTION_STREAM_BYTES);+ exception.writeUInt32LE(1, 0); // ThreadId — unread by the crash-kind parse+ exception.writeUInt32LE(patch.exceptionCode ?? 0, EXCEPTION_CODE_OFFSET);+ exceptionBlocks.push(exception);+ cursor += EXCEPTION_STREAM_BYTES;+ }+const header = Buffer.alloc(HEADER_BYTES);header.write(patch.signature ?? 'MDMP', 0, 'ascii');header.writeUInt32LE(0xa793, 4); // version — unread by the ownership parse@@ -174,11 +208,18 @@ export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}):directory.writeUInt32LE(patch.streamType ?? MODULE_LIST_STREAM_TYPE, moduleListEntry);directory.writeUInt32LE(moduleListBytes, moduleListEntry + 4);directory.writeUInt32LE(patch.moduleListRva ?? moduleListRva, moduleListEntry + 8);+ let nextEntry = moduleListEntry + DIRECTORY_ENTRY_BYTES;if (annotationEntries !== null) {- const crashpadEntry = moduleListEntry + DIRECTORY_ENTRY_BYTES;- directory.writeUInt32LE(patch.crashpadStreamType ?? CRASHPAD_INFO_STREAM_TYPE, crashpadEntry);- directory.writeUInt32LE(CRASHPAD_INFO_BYTES, crashpadEntry + 4);- directory.writeUInt32LE(crashpadInfoRva, crashpadEntry + 8);+ directory.writeUInt32LE(patch.crashpadStreamType ?? CRASHPAD_INFO_STREAM_TYPE, nextEntry);+ directory.writeUInt32LE(CRASHPAD_INFO_BYTES, nextEntry + 4);+ directory.writeUInt32LE(crashpadInfoRva, nextEntry + 8);+ nextEntry += DIRECTORY_ENTRY_BYTES;+ }+ if (hasException) {+ directory.writeUInt32LE(EXCEPTION_STREAM_TYPE, nextEntry);+ directory.writeUInt32LE(EXCEPTION_STREAM_BYTES, nextEntry + 4);+ directory.writeUInt32LE(exceptionRva, nextEntry + 8);+ nextEntry += DIRECTORY_ENTRY_BYTES;}const moduleList = Buffer.alloc(moduleListBytes);@@ -188,6 +229,13 @@ export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}):moduleList.writeUInt32LE(index === 0 ? (patch.nameRva ?? rva) : rva, at);});- const dump = Buffer.concat([header, directory, moduleList, ...nameBlocks, ...crashpadBlocks]);+ const dump = Buffer.concat([+ header,+ directory,+ moduleList,+ ...nameBlocks,+ ...crashpadBlocks,+ ...exceptionBlocks,+ ]);return patch.truncateTo === undefined ? dump : dump.subarray(0, patch.truncateTo);}