From b2f127866d5bf595b04225ef0f727818cf249d6f Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 12 Nov 2026 20:18:35 +0500 Subject: [PATCH 01/11] feat(node): hang reports carry a crash.json of the blocking stack (#14) With profiling on, the hottest non-idle stack of the CPU profile's trailing stall window becomes exception.frames (domain AppHang::*), built through buildCrashJson. The profiling controller holds the segment briefly so the fair/medium/severe burst all see the stall. Without a usable profile the report is unchanged. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSd4XxSkeZk5vaw6dX --- docs/PROGRESS.md | 8 + .../test/instrumentation.e2e.ts | 25 +++ .../node/src/hang-detection-provider.test.ts | 171 +++++++++++++++++- packages/node/src/hang-detection-provider.ts | 52 +++++- packages/node/src/hang-stack.test.ts | 148 +++++++++++++++ packages/node/src/hang-stack.ts | 131 ++++++++++++++ packages/node/src/launch.test.ts | 87 +++++++++ packages/node/src/launch.ts | 5 + .../node/src/profiling-controller.test.ts | 108 +++++++++++ packages/node/src/profiling-controller.ts | 38 +++- 10 files changed, 764 insertions(+), 9 deletions(-) create mode 100644 packages/node/src/hang-stack.test.ts create mode 100644 packages/node/src/hang-stack.ts diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index c07fd9778..b7e7fbdd9 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -757,6 +757,14 @@ Profiler all present). is `unref()`'d so default-ON never blocks a clean exit. Per-episode dedup (each distinct hang re-reports — a documented divergence from Android's per-session, right for a long-running server). Blocking stack comes from the CPU profile in the same bundle. `mechanism: 'hang'` added to the wire. +- **Hang `crash.json` (#14, 2026-11-12):** with `profiling` on, the hang report now ships a `crash.json` + (`exception.name` `AppHang`, `domain: AppHang::*`, frames = the hottest non-idle stack of the profile's trailing + stall window, built through the normal `buildCrashJson` so scrubbing/debug-ids/`user` apply) and drops the fixed + `signatures` (the worker derives the signature from the frames). No profile or no application stack → unchanged + report (own signature, no crash.json) — an empty crash.json would collapse every hang into one issue. The + profiling controller `hold()`s the segment ~3s so the fair→medium→severe burst (delivered together once the loop + frees) all see the stall and still bundle `profile.json`. Renderer-gone hangs need the worker's minidump + stackwalk (not an SDK change). - **Bun (B):** both inherited by `@bugsee/bun` via node-tier reuse; capability-guarded (degrade to no-op if worker_threads/inspector absent). Deferred: Node-only live-inspector `Debugger.pause` stack; main-thread-misuse. diff --git a/packages/instrumentation-tests/test/instrumentation.e2e.ts b/packages/instrumentation-tests/test/instrumentation.e2e.ts index e88f77a4b..49db61342 100644 --- a/packages/instrumentation-tests/test/instrumentation.e2e.ts +++ b/packages/instrumentation-tests/test/instrumentation.e2e.ts @@ -322,6 +322,31 @@ describe.each( ].join('\n'), ).toBe(true); }); + + // Held by the profile, turned into frames: the AppHang report's crash.json names WHERE the loop blocked, so + // the backend groups hangs by that frame. Asserted across every hang bundle for the reason the profile test + // above spells out: a CPU-starved runner adds genuine extra episodes that did not see the deliberate spin. + it('a delivered AppHang report carries a crash.json whose frames hold the blocking function', () => { + const hangs = bundles.filter((b) => b.request.source.mechanism === 'hang'); + type Crash = { + exception: { name: string; domain?: string; frames: Array<{ data?: { member?: string } }> }; + }; + const crashes = hangs + .filter((b) => b.files['crash.json'] !== undefined) + .map((b) => parseJson(b.files['crash.json'])); + expect( + crashes.length, + `no AppHang bundle carries crash.json (${hangs.length} delivered)`, + ).toBeGreaterThan(0); + for (const crash of crashes) { + expect(crash.exception.name).toBe('AppHang'); + expect(crash.exception.domain).toMatch(/^AppHang::(Fair|Medium|Severe)$/); + } + expect( + crashes.some((c) => c.exception.frames.some((f) => f.data?.member === 'e2eHangSpin')), + `e2eHangSpin is in none of the ${crashes.length} hang crash.json(s)`, + ).toBe(true); + }); }); describe('server scenario: node:http incoming request → per-request context', () => { diff --git a/packages/node/src/hang-detection-provider.test.ts b/packages/node/src/hang-detection-provider.test.ts index 083e519dd..19f6ec8fc 100644 --- a/packages/node/src/hang-detection-provider.test.ts +++ b/packages/node/src/hang-detection-provider.test.ts @@ -1,5 +1,6 @@ -import type { Client, ReportingRequest, Scheduler } from '@bugsee/core'; +import type { Client, CrashJson, ReportingRequest, Scheduler } from '@bugsee/core'; import { describe, expect, it } from 'vitest'; +import type { CpuProfile } from './cpu-profiler'; import type { EventLoopWatchdog, EventLoopWatchdogDeps, @@ -8,6 +9,7 @@ import type { } from './event-loop-watchdog'; import { createHangDetectionProvider } from './hang-detection-provider'; +const exceptionOf = (r?: ReportingRequest) => (r?.report.crash as CrashJson | undefined)?.exception; const T: HangThresholds = { fairMs: 3000, mediumMs: 5000, severeMs: 10_000 }; const fakeClient = {} as Client; const noopScheduler: Scheduler = { setInterval: () => 'h', clearInterval: () => {} }; @@ -103,4 +105,171 @@ describe('createHangDetectionProvider', () => { fw.hang('fair', 3000); // after stop → sink detached expect(reports).toHaveLength(0); }); + + describe('with a blocking-stack profile source', () => { + const flush = () => new Promise((r) => setTimeout(r, 0)); + // One application frame sampled for the whole window. + const stalled: CpuProfile = { + nodes: [ + { + id: 1, + callFrame: { functionName: '(root)', url: '', lineNumber: -1, columnNumber: -1 }, + children: [2], + }, + { + id: 2, + callFrame: { + functionName: 'crunch', + url: 'file:///srv/app.js', + lineNumber: 9, + columnNumber: 2, + }, + }, + ], + startTime: 0, + endTime: 5_000_000, + samples: [2, 2, 2], + timeDeltas: [1000, 1000, 1000], + }; + const make = (blockingProfile: () => Promise) => { + const fw = fakeWatchdog(); + const reports: ReportingRequest[] = []; + const p = createHangDetectionProvider({ + thresholds: T, + createWatchdog: fw.create, + blockingProfile, + }); + p.start(fakeClient, (r) => reports.push(r)); + return { fw, reports, p }; + }; + + it('attaches a crash.json with the blocking frames and the AppHang domain', async () => { + const { fw, reports } = make(async () => stalled); + fw.hang('severe', 12_000); + expect(reports).toHaveLength(0); // the profile is awaited before the report is submitted + await flush(); + expect(reports).toHaveLength(1); + const r = reports[0] as ReportingRequest; + expect(exceptionOf(r)?.domain).toBe('AppHang::Severe'); + expect(exceptionOf(r)?.reason).toBe('Event loop blocked for 12000ms'); + expect(exceptionOf(r)?.frames[0]?.data).toEqual({ + source: '/srv/app.js', + member: 'crunch', + line: 10, + column: 3, + }); + expect(r.report.summary).toBe('Main thread hang detected'); + expect(r.report.labels).toEqual(['AppHang::Severe']); + // The backend derives the grouping signature from the frames now; the fixed one would override it. + expect(r.report.signatures).toEqual([]); + }); + + it('looks at a window as long as the stall that was detected', async () => { + const window: CpuProfile = { + ...stalled, + nodes: [ + ...stalled.nodes, + { + id: 3, + callFrame: { + functionName: 'older', + url: 'file:///srv/o.js', + lineNumber: 0, + columnNumber: 0, + }, + }, + ], + samples: [3, 3, 3, 2], + timeDeltas: [1000, 1000, 1000, 1000], + }; + const { fw, reports } = make(async () => window); + fw.hang('fair', 1); // a 1ms window: only the newest sample + await flush(); + expect(exceptionOf(reports[0])?.frames[0]?.data?.member).toBe('crunch'); + }); + + const failing: Array<[string, () => Promise]> = [ + ['no profile', async () => undefined], + ['an unusable profile', async () => ({ nodes: [], startTime: 0, endTime: 0 })], + [ + 'a failing source', + async () => { + throw new Error('inspector gone'); + }, + ], + ]; + it.each( + failing, + )('falls back to the plain hang report (own signature) on %s', async (_n, source) => { + const { fw, reports } = make(source); + fw.hang('medium', 6000); + await flush(); + expect(reports).toHaveLength(1); + expect(reports[0]?.report.crash).toBeUndefined(); + expect(reports[0]?.report.signatures).toEqual(['AppHang::Medium']); + }); + + it('a longer stall looks at more of the profile', async () => { + const older: CpuProfile = { + ...stalled, + nodes: [ + ...stalled.nodes, + { + id: 3, + callFrame: { + functionName: 'older', + url: 'file:///srv/o.js', + lineNumber: 0, + columnNumber: 0, + }, + }, + ], + samples: [3, 3, 3, 2], + timeDeltas: [1000, 1000, 1000, 1000], + }; + const { fw, reports } = make(async () => older); + fw.hang('fair', 4); + await flush(); + expect(exceptionOf(reports[0])?.frames[0]?.data?.member).toBe('older'); + }); + + it('keeps escalation reports in order even when an earlier profile is slower', async () => { + let calls = 0; + const { fw, reports } = make(async () => { + calls += 1; + if (calls === 1) { + await new Promise((r) => setTimeout(r, 20)); + } + return stalled; + }); + fw.hang('fair', 3000); + fw.hang('medium', 5000); + await new Promise((r) => setTimeout(r, 60)); + expect(reports.map((r) => r.report.labels?.[0])).toEqual([ + 'AppHang::Fair', + 'AppHang::Medium', + ]); + }); + + it('keeps escalation reports in order', async () => { + const { fw, reports } = make(async () => stalled); + fw.hang('fair', 3000); + fw.hang('medium', 5000); + fw.hang('severe', 10_000); + await flush(); + expect(reports.map((r) => r.report.labels?.[0])).toEqual([ + 'AppHang::Fair', + 'AppHang::Medium', + 'AppHang::Severe', + ]); + }); + + it('does not deliver a report whose profile resolves after stop()', async () => { + const { fw, reports, p } = make(async () => stalled); + fw.hang('fair', 3000); + p.stop(); + await flush(); + expect(reports).toHaveLength(0); + }); + }); }); diff --git a/packages/node/src/hang-detection-provider.ts b/packages/node/src/hang-detection-provider.ts index fa4a5c2c6..7084057b4 100644 --- a/packages/node/src/hang-detection-provider.ts +++ b/packages/node/src/hang-detection-provider.ts @@ -1,5 +1,11 @@ -import { type DetectionProvider, DetectionProviderBase, type Scheduler } from '@bugsee/core'; +import { + type CrashJson, + type DetectionProvider, + DetectionProviderBase, + type Scheduler, +} from '@bugsee/core'; import { BugseeOption } from '@bugsee/protocol'; +import type { CpuProfile } from './cpu-profiler'; import { createEventLoopWatchdog, type EventLoopWatchdog, @@ -7,13 +13,15 @@ import { type HangLevel, type HangThresholds, } from './event-loop-watchdog'; +import { hangCrashFromProfile } from './hang-stack'; // The hang detection provider (node diagnostics, A2 — Android `BugseeDetectionHang` parity). Wraps the // event-loop watchdog (A1) as a DetectionProvider: on each newly-crossed hang level it submits an ERROR // report "Main thread hang detected" carrying the Android-canonical domain `AppHang::{Fair|Medium|Severe}` // (as a label + signature for grouping) and the stall duration. The BLOCKING STACK is not captured here — -// it comes from the CPU profile in the same bundle (when profiling is on), since V8 keeps sampling during a -// synchronous block. Gated by `detect.hang`; node-specific (worker_threads), so it degrades to a no-op +// it comes from the CPU profile (when profiling is on), since V8 keeps sampling during a synchronous block: +// the profile's hottest stack in the stall window becomes the report's `crash.json` frames, so hangs group by +// where they block. Without a profile the report keeps its fixed `AppHang::*` signature. Gated by `detect.hang`; node-specific (worker_threads), so it degrades to a no-op // where the watchdog cannot spawn a worker. const DOMAIN: Record = { @@ -28,6 +36,11 @@ export interface HangDetectionProviderDeps { heartbeatIntervalMs?: number; /** Heartbeat timer; the launch passes the client's scheduler. Default global timers. */ scheduler?: Scheduler; + /** + * The CPU profile covering the stall, when profiling is on. Resolving undefined (or an unusable profile, or + * rejecting) keeps the plain hang report: a crash.json with no frames would make every hang one issue. + */ + blockingProfile?: () => Promise; /** Watchdog factory — tests inject a fake to drive onHang without a real worker. Default the real one. */ createWatchdog?: (deps: EventLoopWatchdogDeps) => EventLoopWatchdog; } @@ -36,9 +49,14 @@ class HangDetectionProvider extends DetectionProviderBase { readonly name = 'node-hang'; readonly controllingOption = BugseeOption.DetectHang; readonly #watchdog: EventLoopWatchdog; + readonly #blockingProfile: HangDetectionProviderDeps['blockingProfile']; + // Escalation reports (fair → medium → severe) arrive together; chaining keeps them in order while each + // awaits its profile. + #pending: Promise = Promise.resolve(); constructor(deps: HangDetectionProviderDeps) { super(); + this.#blockingProfile = deps.blockingProfile; const create = deps.createWatchdog ?? createEventLoopWatchdog; this.#watchdog = create({ thresholds: deps.thresholds, @@ -60,13 +78,39 @@ class HangDetectionProvider extends DetectionProviderBase { #report(level: HangLevel, durationMs: number): void { const domain = DOMAIN[level]; + const source = this.#blockingProfile; + if (source === undefined) { + this.#submit(domain, durationMs); + return; + } + this.#pending = this.#pending.then(async () => { + let crash: CrashJson | undefined; + try { + const profile = await source(); + crash = + profile !== undefined + ? hangCrashFromProfile(profile, { + windowMs: durationMs, + domain, + reason: `Event loop blocked for ${durationMs}ms`, + }) + : undefined; + } catch { + crash = undefined; // no stack is better than no report + } + this.#submit(domain, durationMs, crash); + }); + } + + #submit(domain: string, durationMs: number, crash?: CrashJson): void { this.handleReportingRequest( this.createErrorReport({ mechanism: 'hang', summary: 'Main thread hang detected', description: `Event loop blocked for ${durationMs}ms (${domain})`, labels: [domain], - signatures: [domain], + // With frames the backend derives the signature from them; the fixed one would override it. + ...(crash !== undefined ? { crash } : { signatures: [domain] }), }), ); } diff --git a/packages/node/src/hang-stack.test.ts b/packages/node/src/hang-stack.test.ts new file mode 100644 index 000000000..f3313cefa --- /dev/null +++ b/packages/node/src/hang-stack.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it } from 'vitest'; +import type { CpuProfile } from './cpu-profiler'; +import { hangCrashFromProfile } from './hang-stack'; + +interface N { + id: number; + fn: string; + url?: string; + line?: number; + col?: number; + children?: number[]; +} + +const node = (n: N) => ({ + id: n.id, + callFrame: { + functionName: n.fn, + scriptId: '1', + url: n.url ?? '', + lineNumber: n.line ?? -1, + columnNumber: n.col ?? -1, + }, + ...(n.children !== undefined ? { children: n.children } : {}), +}); + +// A profile whose samples are 1ms apart. `samples` lists node ids oldest → newest. +const profile = (nodes: N[], samples: number[], deltaUs = 1000): CpuProfile => ({ + nodes: nodes.map(node), + startTime: 0, + endTime: samples.length * deltaUs, + samples, + timeDeltas: samples.map(() => deltaUs), +}); + +// root → main(app.js) → parse(lib.js) ; main → render(app.js) +const TREE: N[] = [ + { id: 1, fn: '(root)', children: [2, 7, 8, 9] }, + { id: 2, fn: 'main', url: 'file:///srv/app.js', line: 9, col: 4, children: [3, 5] }, + { id: 3, fn: 'parse', url: 'file:///srv/lib.js', line: 0, col: 0 }, + { id: 5, fn: 'render', url: 'file:///srv/app.js', line: 19, col: 2 }, + { id: 7, fn: '(idle)' }, + { id: 8, fn: '(program)' }, + { id: 9, fn: '(garbage collector)' }, +]; + +const opts = { + windowMs: 1000, + domain: 'AppHang::Severe', + reason: 'Event loop blocked for 12000ms', +}; + +describe('hangCrashFromProfile', () => { + it('builds a crash.json whose frames are the hottest stack (leaf first), 1-based, with the AppHang domain', () => { + const crash = hangCrashFromProfile(profile(TREE, [3, 3, 3, 5]), opts); + expect(crash).toBeDefined(); + expect(crash?.exception_type).toBe('error'); + expect(crash?.ndkCrash).toBe(false); + expect(crash?.handled).toBe(false); + expect(crash?.exception.name).toBe('AppHang'); + expect(crash?.exception.reason).toBe('Event loop blocked for 12000ms'); + expect(crash?.exception.domain).toBe('AppHang::Severe'); + expect(crash?.exception.frames.map((f) => f.data)).toEqual([ + { source: '/srv/lib.js', member: 'parse', line: 1, column: 1 }, + { source: '/srv/app.js', member: 'main', line: 10, column: 5 }, + ]); + expect(crash?.exception.frames.every((f) => f.user)).toBe(true); + }); + + it('picks the node with the most self samples', () => { + const crash = hangCrashFromProfile(profile(TREE, [3, 5, 5, 5]), opts); + expect(crash?.exception.frames[0]?.data?.member).toBe('render'); + }); + + it('ignores idle, program and GC samples however many there are', () => { + const crash = hangCrashFromProfile(profile(TREE, [7, 7, 7, 8, 8, 9, 9, 3]), opts); + expect(crash?.exception.frames[0]?.data?.member).toBe('parse'); + }); + + it('only counts the trailing window (the stall), not older work', () => { + // 1ms samples: the last 2 are 5, everything before is 3; a 2ms window sees only 5. + const crash = hangCrashFromProfile(profile(TREE, [3, 3, 3, 3, 5, 5]), { ...opts, windowMs: 2 }); + expect(crash?.exception.frames[0]?.data?.member).toBe('render'); + const wide = hangCrashFromProfile(profile(TREE, [3, 3, 3, 3, 5, 5]), { ...opts, windowMs: 6 }); + expect(wide?.exception.frames[0]?.data?.member).toBe('parse'); + }); + + it('the window ends exactly at its length (a tie goes to the newest sample)', () => { + // 2ms window over [3,3,5]: sees 5 and one 3 (a 1-1 tie → newest wins). One sample more would make 3 win. + const crash = hangCrashFromProfile(profile(TREE, [3, 3, 5]), { ...opts, windowMs: 2 }); + expect(crash?.exception.frames[0]?.data?.member).toBe('render'); + }); + + it('is undefined when nothing but idle/program/GC ran in the window', () => { + expect(hangCrashFromProfile(profile(TREE, [7, 8, 9]), opts)).toBeUndefined(); + }); + + it('is undefined for a profile without samples, or with an empty sample list', () => { + expect(hangCrashFromProfile({ nodes: [], startTime: 0, endTime: 0 }, opts)).toBeUndefined(); + expect(hangCrashFromProfile(profile(TREE, []), opts)).toBeUndefined(); + }); + + it('skips samples that point at an unknown node and tolerates missing timeDeltas', () => { + const p = profile(TREE, [99, 3]); + delete (p as { timeDeltas?: number[] }).timeDeltas; + expect(hangCrashFromProfile(p, opts)?.exception.frames[0]?.data?.member).toBe('parse'); + }); + + it('renders native and anonymous frames as V8 does, and classifies runtime internals as not the app', () => { + const nodes: N[] = [ + { id: 1, fn: '(root)', children: [2] }, + { id: 2, fn: '', url: 'node:internal/main/run_main_module', line: 0, col: 0, children: [3] }, + { id: 3, fn: '', url: 'file:///srv/app.js', line: 4, col: 1, children: [4] }, + { id: 4, fn: 'parse' }, // a native builtin: no script + ]; + const crash = hangCrashFromProfile(profile(nodes, [4]), opts); + const frames = crash?.exception.frames ?? []; + expect(frames.map((f) => f.trace)).toEqual([ + 'at parse ()', + 'at (/srv/app.js:5:2)', + 'at (node:internal/main/run_main_module:1:1)', + ]); + expect(frames.map((f) => f.user)).toEqual([true, true, false]); + }); + + it('caps a pathologically deep stack, keeping the leaf end', () => { + const nodes: N[] = [{ id: 1, fn: '(root)', children: [2] }]; + for (let i = 2; i <= 200; i += 1) { + nodes.push({ + id: i, + fn: `f${i}`, + url: 'file:///srv/a.js', + line: i, + col: 0, + ...(i < 200 ? { children: [i + 1] } : {}), + }); + } + const frames = hangCrashFromProfile(profile(nodes, [200]), opts)?.exception.frames ?? []; + expect(frames).toHaveLength(64); + expect(frames[0]?.data?.member).toBe('f200'); + expect(frames[63]?.data?.member).toBe('f137'); + }); + + it('does not let a malformed node take the report down', () => { + const p = profile(TREE, [3]); + p.nodes.push(null, 5, { id: 'x' }, { id: 50 }); + expect(hangCrashFromProfile(p, opts)?.exception.frames[0]?.data?.member).toBe('parse'); + }); +}); diff --git a/packages/node/src/hang-stack.ts b/packages/node/src/hang-stack.ts new file mode 100644 index 000000000..2eff42794 --- /dev/null +++ b/packages/node/src/hang-stack.ts @@ -0,0 +1,131 @@ +import { buildCrashJson, type CrashJson } from '@bugsee/core'; +import type { CpuProfile } from './cpu-profiler'; + +// The blocking stack of a hang (node diagnostics). A hang report carries no stack of its own — the event +// loop was stuck, nothing threw — but V8 keeps sampling during a synchronous block, so the CPU profile taken +// at the report has it. This turns the profile's hottest stack in the stall window into a `crash.json` +// (`exception.frames` + `domain: AppHang::*`), which is what lets the backend group hangs by WHERE they +// block instead of collapsing every hang in an app into one issue. +// +// It goes through the SAME crash builder every other report uses (a synthetic Error whose `stack` is the +// profile's frames in V8's format), so path scrubbing, the runtime-internal/`user` classification and the +// debug-id stamp are not re-implemented here. + +/** Frames kept, leaf end first. Bounds a runaway recursion; the grouping location is at the top anyway. */ +const MAX_FRAMES = 64; + +/** The profiler's pseudo-frames: time that was not JavaScript in the application. */ +const PSEUDO = new Set(['(root)', '(program)', '(idle)', '(garbage collector)']); + +interface ProfileNode { + id: number; + callFrame: { functionName: string; url: string; lineNumber: number; columnNumber: number }; + children?: number[]; +} + +export interface HangCrashOptions { + /** The trailing slice of the profile to look at, in ms: the stall (the level's threshold), not older work. */ + windowMs: number; + /** `AppHang::Fair|Medium|Severe`. */ + domain: string; + /** The exception reason, e.g. `Event loop blocked for 6000ms`. */ + reason: string; +} + +const isNode = (value: unknown): value is ProfileNode => { + const n = value as Partial | null; + return ( + typeof n === 'object' && + n !== null && + typeof n.id === 'number' && + typeof n.callFrame === 'object' && + n.callFrame !== null + ); +}; + +/** One V8 `at …` line. The profile's line/column are 0-based, a stack's are 1-based. */ +function frameLine(frame: ProfileNode['callFrame']): string { + const name = frame.functionName; + if (frame.url === '') { + return ` at ${name} ()`; + } + const where = `${frame.url}:${frame.lineNumber + 1}:${frame.columnNumber + 1}`; + return name === '' ? ` at ${where}` : ` at ${name} (${where})`; +} + +/** The `id`s of the node's ancestors are not stored, only its children: invert them once. */ +function parentsOf(nodes: Map): Map { + const parents = new Map(); + for (const node of nodes.values()) { + for (const child of node.children ?? []) { + parents.set(child, node.id); + } + } + return parents; +} + +/** + * The `crash.json` for a hang, from the CPU profile taken at its report; undefined when the profile holds no + * application stack in the window (nothing sampled, or only idle/program/GC), so the report ships as it does + * without profiling rather than with an empty crash. + */ +export function hangCrashFromProfile( + profile: CpuProfile, + options: HangCrashOptions, +): CrashJson | undefined { + const { samples, timeDeltas } = profile; + if (samples === undefined || samples.length === 0) { + return undefined; + } + const nodes = new Map(); + for (const candidate of profile.nodes) { + if (isNode(candidate)) { + nodes.set(candidate.id, candidate); + } + } + + // Self samples per node over the trailing window, newest first. `timeDeltas[i]` is the gap before sample i. + const windowUs = options.windowMs * 1000; + const counts = new Map(); + let elapsedUs = 0; + for (let i = samples.length - 1; i >= 0 && elapsedUs < windowUs; i -= 1) { + const id = samples[i] as number; + const node = nodes.get(id); + if (node !== undefined && !PSEUDO.has(node.callFrame.functionName)) { + counts.set(id, (counts.get(id) ?? 0) + 1); + } + elapsedUs += timeDeltas?.[i] ?? 0; + } + + let hottest: number | undefined; + let most = 0; + for (const [id, count] of counts) { + if (count > most) { + hottest = id; + most = count; + } + } + if (hottest === undefined) { + return undefined; + } + + const parents = parentsOf(nodes); + const lines: string[] = []; + for ( + let id: number | undefined = hottest; + id !== undefined && lines.length < MAX_FRAMES; + id = parents.get(id) + ) { + const frame = nodes.get(id)?.callFrame; + if (frame !== undefined && !PSEUDO.has(frame.functionName)) { + lines.push(frameLine(frame)); + } + } + + const error = new Error(options.reason); + error.name = 'AppHang'; + error.stack = `AppHang: ${options.reason}\n${lines.join('\n')}`; + const crash = buildCrashJson(error, { handled: false }); + crash.exception.domain = options.domain; + return crash; +} diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index dbb11740d..436ec9fb7 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -2474,6 +2474,93 @@ describe('launch — capture recovery', () => { expect(req.labels).toContain('AppHang::Severe'); }); + it('with profiling on, a hang ships a crash.json of the stall (frames + AppHang domain) alongside profile.json', async () => { + const transport = uploadTransport(); + const cpuProfile = { + nodes: [ + { + id: 1, + callFrame: { functionName: '(root)', url: '', lineNumber: -1, columnNumber: -1 }, + children: [2], + }, + { + id: 2, + callFrame: { + functionName: 'crunch', + url: 'file:///srv/app.js', + lineNumber: 9, + columnNumber: 2, + }, + }, + ], + startTime: 0, + endTime: 3000, + samples: [2, 2, 2], + timeDeltas: [1000, 1000, 1000], + }; + const cpuProfiler = { + running: false, + start: async () => {}, + collect: vi.fn(async () => cpuProfile), + stop: async () => cpuProfile, + }; + let onHang: ((l: HangLevel, d: number) => void) | undefined; + launchTracked( + 'tok', + baseOptions({ + transport, + captureStore: memStore(), + scheduler: fakeScheduler().scheduler, + profiling: true, + cpuProfiler, + hangWatchdogFactory: (deps) => { + onHang = deps.onHang; + return { start() {}, stop() {} }; + }, + }), + ); + onHang?.('severe', 12_000); + await vi.waitFor(() => + expect(transport.mock.calls.some(([u]) => u === 'https://s3.test/put')).toBe(true), + ); + const put = transport.mock.calls.find(([u]) => u === 'https://s3.test/put'); + const files = unzipSync((put?.[1] as HttpRequestOptions).body as Uint8Array); + const crash = JSON.parse(strFromU8(files['crash.json'] as Uint8Array)); + expect(crash.exception.domain).toBe('AppHang::Severe'); + expect(crash.exception.frames[0].data).toMatchObject({ member: 'crunch', line: 10, column: 3 }); + expect(JSON.parse(strFromU8(files['request.json'] as Uint8Array)).signatures).toBeUndefined(); + // The hang's own profile is still in the bundle (the report reused the held segment, not an empty one). + expect(JSON.parse(strFromU8(files['profile.json'] as Uint8Array))).toEqual(cpuProfile); + expect(cpuProfiler.collect).toHaveBeenCalledTimes(1); + }); + + it('without profiling a hang ships no crash.json and keeps its AppHang signature', async () => { + const transport = uploadTransport(); + let onHang: ((l: HangLevel, d: number) => void) | undefined; + launchTracked( + 'tok', + baseOptions({ + transport, + captureStore: memStore(), + scheduler: fakeScheduler().scheduler, + hangWatchdogFactory: (deps) => { + onHang = deps.onHang; + return { start() {}, stop() {} }; + }, + }), + ); + onHang?.('fair', 3000); + await vi.waitFor(() => + expect(transport.mock.calls.some(([u]) => u === 'https://s3.test/put')).toBe(true), + ); + const put = transport.mock.calls.find(([u]) => u === 'https://s3.test/put'); + const files = unzipSync((put?.[1] as HttpRequestOptions).body as Uint8Array); + expect('crash.json' in files).toBe(false); + expect(JSON.parse(strFromU8(files['request.json'] as Uint8Array)).signatures).toEqual([ + 'AppHang::Fair', + ]); + }); + it('does not start hang detection when detectHangs is false', () => { let started = false; launchTracked( diff --git a/packages/node/src/launch.ts b/packages/node/src/launch.ts index 2fb72b97f..a3dbb66ef 100644 --- a/packages/node/src/launch.ts +++ b/packages/node/src/launch.ts @@ -1161,6 +1161,11 @@ function buildLaunch(appToken: string, options: BugseeLaunchOptions = {}): Launc severeMs: resolved.options.get(BugseeOption.DetectHangSevereMs, 10_000), }, scheduler: client.getService(SchedulerToken), + // The stall's frames come from the rolling CPU profile (opt-in): without profiling a hang keeps its + // fixed AppHang::* signature. Late-bound — the controller is built above, but only when profiling is on. + ...(profilingController !== undefined + ? { blockingProfile: () => profilingController?.hold() ?? Promise.resolve(undefined) } + : {}), ...(options.hangWatchdogFactory !== undefined ? { createWatchdog: options.hangWatchdogFactory } : {}), diff --git a/packages/node/src/profiling-controller.test.ts b/packages/node/src/profiling-controller.test.ts index ee5238cba..9d930f2f6 100644 --- a/packages/node/src/profiling-controller.test.ts +++ b/packages/node/src/profiling-controller.test.ts @@ -169,4 +169,112 @@ describe('createProfilingController', () => { expect(s.cleared()).toBe(false); expect(p.calls.stop).toBe(1); // profiler.stop() is still called (idempotent no-op when not running) }); + + describe('hold() — the hang-report segment', () => { + const mk = (nowRef: { t: number }) => { + const p = fakeProfiler(); + const s = fakeScheduler(); + const c = createProfilingController({ + profiler: p.profiler, + scheduler: s.scheduler, + rollingIntervalMs: 60_000, + now: () => nowRef.t, + }); + c.start(); + return { p, s, c }; + }; + + it('collects the segment and returns the profile', async () => { + const { p, c } = mk({ t: 0 }); + expect(await c.hold()).toEqual(p.profile); + expect(p.calls.collect).toBe(1); + }); + + it('returns undefined when there is no profile, and holds nothing', async () => { + const p = fakeProfiler({ profile: undefined }); + const s = fakeScheduler(); + const c = createProfilingController({ + profiler: p.profiler, + scheduler: s.scheduler, + rollingIntervalMs: 60_000, + }); + c.start(); + expect(await c.hold()).toBeUndefined(); + await c.hold(); + expect(p.calls.collect).toBe(2); // nothing was retained, so the second call collects again + }); + + it('a second hold() within the TTL reuses the held segment instead of collecting an empty one', async () => { + const now = { t: 0 }; + const { p, c } = mk(now); + await c.hold(); + now.t = 2999; + expect(await c.hold()).toEqual(p.profile); + expect(p.calls.collect).toBe(1); + }); + + it('collects afresh once the TTL has passed', async () => { + const now = { t: 0 }; + const { p, c } = mk(now); + await c.hold(); + now.t = 3000; + await c.hold(); + expect(p.calls.collect).toBe(2); + }); + + it('snapshot() within the TTL returns the held segment (the hang report keeps its profile.json)', async () => { + const now = { t: 0 }; + const { p, c } = mk(now); + await c.hold(); + now.t = 10; + const entries = await c.snapshot(1700); + expect(entries[0]?.data).toEqual(p.profile); + expect(entries[0]?.timestamp).toBe(1700); + expect(p.calls.collect).toBe(1); + }); + + it('snapshot() alone never retains (a later snapshot collects a fresh segment)', async () => { + const { p, c } = mk({ t: 0 }); + await c.snapshot(1); + await c.snapshot(2); + expect(p.calls.collect).toBe(2); + }); + + it('the rolling tick drops the held segment so it is never retained for a whole window', async () => { + const { p, s, c } = mk({ t: 0 }); + await c.hold(); + s.fire(); + await flush(); + expect(p.calls.collect).toBe(2); + await c.hold(); + expect(p.calls.collect).toBe(3); + }); + + it('serializes with snapshot(): a snapshot queued behind a hold reuses its segment', async () => { + const p = fakeProfiler({ defer: true }); + const s = fakeScheduler(); + const c = createProfilingController({ + profiler: p.profiler, + scheduler: s.scheduler, + rollingIntervalMs: 60_000, + now: () => 0, + }); + c.start(); + const held = c.hold(); + const snap = c.snapshot(5); + await flush(); + p.resolveNext(aProfile({ endTime: 7 })); + expect(await held).toEqual(aProfile({ endTime: 7 })); + expect((await snap)[0]?.data).toEqual(aProfile({ endTime: 7 })); + expect(p.calls.collect).toBe(1); + }); + + it('stop() drops the held segment', async () => { + const { p, c } = mk({ t: 0 }); + await c.hold(); + c.stop(); + await c.hold(); + expect(p.calls.collect).toBe(2); + }); + }); }); diff --git a/packages/node/src/profiling-controller.ts b/packages/node/src/profiling-controller.ts index d09d4fec7..59e451c66 100644 --- a/packages/node/src/profiling-controller.ts +++ b/packages/node/src/profiling-controller.ts @@ -16,26 +16,52 @@ export interface ProfilingControllerDeps { scheduler: Scheduler; /** Rolling-restart interval (ms) — the cap on a single segment; typically the recording window. */ rollingIntervalMs: number; + /** Wall-clock ms; injectable for tests. Default `Date.now`. */ + now?: () => number; } +/** + * How long a segment taken for a hang report stays reusable. A hang escalates fair → medium → severe and the + * main thread hears all of them at once, when the block ends: only the first would otherwise see the stall in + * its profile (the collect restarts the segment, so the rest would get an empty one). + */ +const HOLD_MS = 3000; + export interface ProfilingController { /** Start sampling + the rolling-restart timer. */ start(): void; /** The pull-at-report snapshot source: collect the current segment as a `profile` capture entry. */ snapshot(now: number): Promise; + /** + * Collect the current segment for a HANG report and retain it for a few seconds, so the burst of escalation + * reports (and the profile.json each bundles) all see the stall. Resolves undefined when there is no profile. + */ + hold(): Promise; /** Stop the rolling timer and the profiler. */ stop(): void; } export function createProfilingController(deps: ProfilingControllerDeps): ProfilingController { const { profiler, scheduler, rollingIntervalMs } = deps; + const now = deps.now ?? Date.now; let handle: unknown; + let held: { profile: CpuProfile; at: number } | undefined; // Serialize every collect() so the rolling tick and a report never stop+restart the session at once. // profiler.collect() resolves (never rejects), so the chain stays settled. let chain: Promise = Promise.resolve(); - const collect = (): Promise => { - const next = chain.then(() => profiler.collect()); + const collect = (retain: boolean): Promise => { + const next = chain.then(async () => { + if (held !== undefined && now() - held.at < HOLD_MS) { + return held.profile; + } + held = undefined; + const profile = await profiler.collect(); + if (retain && profile !== undefined) { + held = { profile, at: now() }; + } + return profile; + }); chain = next; return next; }; @@ -44,16 +70,20 @@ export function createProfilingController(deps: ProfilingControllerDeps): Profil start() { void profiler.start(); handle = scheduler.setInterval(() => { - void collect(); // discard — the rolling tick just caps the segment length + held = undefined; // never keep a stale segment for a whole window + void collect(false); // discard — the rolling tick just caps the segment length }, rollingIntervalMs); }, async snapshot(now: number): Promise { - const profile = await collect(); + const profile = await collect(false); return profile ? [new CaptureDataEntryBase('profile', now, profile)] : []; }, + hold: () => collect(true), + stop() { + held = undefined; if (handle !== undefined) { scheduler.clearInterval(handle); handle = undefined; From 2bbf490014207bdeaef8348db3107fdbb7e085eb Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 12 Nov 2026 20:24:26 +0500 Subject: [PATCH 02/11] fix(node): hang crash.json review fixes (#14) Require the profile to span the stall window, report hangs as handled (Android parity), bound the frame walk, keep the report chain alive after a failed submit. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSd4XxSkeZk5vaw6dX --- docs/PROGRESS.md | 2 +- .../node/src/hang-detection-provider.test.ts | 2 +- packages/node/src/hang-detection-provider.ts | 1 + packages/node/src/hang-stack.test.ts | 21 +++++++++++++++++-- packages/node/src/hang-stack.ts | 14 ++++++++++--- packages/node/src/launch.test.ts | 2 +- 6 files changed, 34 insertions(+), 8 deletions(-) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index b7e7fbdd9..3b6946b0f 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -763,7 +763,7 @@ Profiler all present). `signatures` (the worker derives the signature from the frames). No profile or no application stack → unchanged report (own signature, no crash.json) — an empty crash.json would collapse every hang into one issue. The profiling controller `hold()`s the segment ~3s so the fair→medium→severe burst (delivered together once the loop - frees) all see the stall and still bundle `profile.json`. Renderer-gone hangs need the worker's minidump + frees) all see the stall (their `profile.json` too, unless a slow upload delays a later report's snapshot past the hold). A profile spanning less than the stall window yields no crash.json. Renderer-gone hangs need the worker's minidump stackwalk (not an SDK change). - **Bun (B):** both inherited by `@bugsee/bun` via node-tier reuse; capability-guarded (degrade to no-op if worker_threads/inspector absent). Deferred: Node-only live-inspector `Debugger.pause` stack; main-thread-misuse. diff --git a/packages/node/src/hang-detection-provider.test.ts b/packages/node/src/hang-detection-provider.test.ts index 19f6ec8fc..da5368b19 100644 --- a/packages/node/src/hang-detection-provider.test.ts +++ b/packages/node/src/hang-detection-provider.test.ts @@ -127,7 +127,7 @@ describe('createHangDetectionProvider', () => { }, ], startTime: 0, - endTime: 5_000_000, + endTime: 20_000_000, samples: [2, 2, 2], timeDeltas: [1000, 1000, 1000], }; diff --git a/packages/node/src/hang-detection-provider.ts b/packages/node/src/hang-detection-provider.ts index 7084057b4..d78cb30c8 100644 --- a/packages/node/src/hang-detection-provider.ts +++ b/packages/node/src/hang-detection-provider.ts @@ -100,6 +100,7 @@ class HangDetectionProvider extends DetectionProviderBase { } this.#submit(domain, durationMs, crash); }); + this.#pending = this.#pending.catch(() => undefined); // one failed submit must not stall later reports } #submit(domain: string, durationMs: number, crash?: CrashJson): void { diff --git a/packages/node/src/hang-stack.test.ts b/packages/node/src/hang-stack.test.ts index f3313cefa..af0e77174 100644 --- a/packages/node/src/hang-stack.test.ts +++ b/packages/node/src/hang-stack.test.ts @@ -27,7 +27,7 @@ const node = (n: N) => ({ const profile = (nodes: N[], samples: number[], deltaUs = 1000): CpuProfile => ({ nodes: nodes.map(node), startTime: 0, - endTime: samples.length * deltaUs, + endTime: 10_000_000, // spans any window the tests use samples, timeDeltas: samples.map(() => deltaUs), }); @@ -55,7 +55,7 @@ describe('hangCrashFromProfile', () => { expect(crash).toBeDefined(); expect(crash?.exception_type).toBe('error'); expect(crash?.ndkCrash).toBe(false); - expect(crash?.handled).toBe(false); + expect(crash?.handled).toBe(true); expect(crash?.exception.name).toBe('AppHang'); expect(crash?.exception.reason).toBe('Event loop blocked for 12000ms'); expect(crash?.exception.domain).toBe('AppHang::Severe'); @@ -90,6 +90,14 @@ describe('hangCrashFromProfile', () => { expect(crash?.exception.frames[0]?.data?.member).toBe('render'); }); + it('is undefined when the profile does not span the window (a segment restarted after the stall)', () => { + const short = { ...profile(TREE, [3, 3, 3]), endTime: 2999 }; + expect(hangCrashFromProfile(short, { ...opts, windowMs: 3 })).toBeUndefined(); + expect( + hangCrashFromProfile({ ...short, endTime: 3000 }, { ...opts, windowMs: 3 }), + ).toBeDefined(); + }); + it('is undefined when nothing but idle/program/GC ran in the window', () => { expect(hangCrashFromProfile(profile(TREE, [7, 8, 9]), opts)).toBeUndefined(); }); @@ -140,6 +148,15 @@ describe('hangCrashFromProfile', () => { expect(frames[63]?.data?.member).toBe('f137'); }); + it('terminates on a parent cycle made of skipped pseudo frames', () => { + const nodes: N[] = [ + { id: 1, fn: '(root)', children: [2] }, + { id: 2, fn: '(program)', children: [1, 3] }, + { id: 3, fn: 'parse', url: 'file:///srv/lib.js', line: 0, col: 0 }, + ]; + expect(hangCrashFromProfile(profile(nodes, [3]), opts)?.exception.frames).toHaveLength(1); + }); + it('does not let a malformed node take the report down', () => { const p = profile(TREE, [3]); p.nodes.push(null, 5, { id: 'x' }, { id: 50 }); diff --git a/packages/node/src/hang-stack.ts b/packages/node/src/hang-stack.ts index 2eff42794..aa71bae07 100644 --- a/packages/node/src/hang-stack.ts +++ b/packages/node/src/hang-stack.ts @@ -9,7 +9,7 @@ import type { CpuProfile } from './cpu-profiler'; // // It goes through the SAME crash builder every other report uses (a synthetic Error whose `stack` is the // profile's frames in V8's format), so path scrubbing, the runtime-internal/`user` classification and the -// debug-id stamp are not re-implemented here. +// debug-id stamp are not re-implemented here. `handled: true`, as Android's hang report: the process did not crash. /** Frames kept, leaf end first. Bounds a runaway recursion; the grouping location is at the top anyway. */ const MAX_FRAMES = 64; @@ -77,6 +77,11 @@ export function hangCrashFromProfile( if (samples === undefined || samples.length === 0) { return undefined; } + // A segment restarted after the stall (another collect got there first) holds only what ran since: its hottest + // frame would be confidently wrong, so a profile that does not span the window yields no crash at all. + if (profile.endTime - profile.startTime < options.windowMs * 1000) { + return undefined; + } const nodes = new Map(); for (const candidate of profile.nodes) { if (isNode(candidate)) { @@ -111,11 +116,14 @@ export function hangCrashFromProfile( const parents = parentsOf(nodes); const lines: string[] = []; + // Steps are bounded by the node count, so a (malformed) parent cycle through skipped pseudo frames ends too. + let steps = 0; for ( let id: number | undefined = hottest; - id !== undefined && lines.length < MAX_FRAMES; + id !== undefined && lines.length < MAX_FRAMES && steps <= nodes.size; id = parents.get(id) ) { + steps += 1; const frame = nodes.get(id)?.callFrame; if (frame !== undefined && !PSEUDO.has(frame.functionName)) { lines.push(frameLine(frame)); @@ -125,7 +133,7 @@ export function hangCrashFromProfile( const error = new Error(options.reason); error.name = 'AppHang'; error.stack = `AppHang: ${options.reason}\n${lines.join('\n')}`; - const crash = buildCrashJson(error, { handled: false }); + const crash = buildCrashJson(error, { handled: true }); crash.exception.domain = options.domain; return crash; } diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index 436ec9fb7..353ef7ce8 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -2494,7 +2494,7 @@ describe('launch — capture recovery', () => { }, ], startTime: 0, - endTime: 3000, + endTime: 20_000_000, samples: [2, 2, 2], timeDeltas: [1000, 1000, 1000], }; From e4ac44ff8222b72a394454453f09da3ebbcc7dcc Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 12 Nov 2026 20:24:47 +0500 Subject: [PATCH 03/11] test(node): cover the failed-submit chain recovery (#14) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSd4XxSkeZk5vaw6dX --- .../node/src/hang-detection-provider.test.ts | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/node/src/hang-detection-provider.test.ts b/packages/node/src/hang-detection-provider.test.ts index da5368b19..00bd14155 100644 --- a/packages/node/src/hang-detection-provider.test.ts +++ b/packages/node/src/hang-detection-provider.test.ts @@ -251,6 +251,28 @@ describe('createHangDetectionProvider', () => { ]); }); + it('keeps reporting after a submit throws (one failure must not stall the chain)', async () => { + const fw = fakeWatchdog(); + const reports: ReportingRequest[] = []; + const p = createHangDetectionProvider({ + thresholds: T, + createWatchdog: fw.create, + blockingProfile: async () => stalled, + }); + let first = true; + p.start(fakeClient, (r) => { + if (first) { + first = false; + throw new Error('sink down'); + } + reports.push(r); + }); + fw.hang('fair', 3000); + fw.hang('medium', 5000); + await flush(); + expect(reports.map((r) => r.report.labels?.[0])).toEqual(['AppHang::Medium']); + }); + it('keeps escalation reports in order', async () => { const { fw, reports } = make(async () => stalled); fw.hang('fair', 3000); From 0621f76fbb04e1672e6ca87a5d8a10dee25f447d Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 12 Nov 2026 20:29:35 +0500 Subject: [PATCH 04/11] fix(node): rolling tick retains its segment so an overdue tick cannot swallow a hang's stall (#14) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSd4XxSkeZk5vaw6dX --- packages/node/src/profiling-controller.test.ts | 16 +++++++++++----- packages/node/src/profiling-controller.ts | 7 +++++-- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/packages/node/src/profiling-controller.test.ts b/packages/node/src/profiling-controller.test.ts index 9d930f2f6..8c76c0177 100644 --- a/packages/node/src/profiling-controller.test.ts +++ b/packages/node/src/profiling-controller.test.ts @@ -124,12 +124,14 @@ describe('createProfilingController', () => { }); it('SERIALIZES overlapping collects (a report during a rolling tick never double-stops the session)', async () => { + let clockMs = 0; const p = fakeProfiler({ defer: true }); const s = fakeScheduler(); const c = createProfilingController({ profiler: p.profiler, scheduler: s.scheduler, rollingIntervalMs: 60_000, + now: () => (clockMs += 4000), // every read is past the hold TTL: the tick's segment is not reusable }); c.start(); s.fire(); // rolling collect #1 — pending (deferred) @@ -240,14 +242,18 @@ describe('createProfilingController', () => { expect(p.calls.collect).toBe(2); }); - it('the rolling tick drops the held segment so it is never retained for a whole window', async () => { - const { p, s, c } = mk({ t: 0 }); + it('the rolling tick replaces the held segment, and retains its own for a hang report that follows it', async () => { + const now = { t: 0 }; + const { p, s, c } = mk(now); await c.hold(); - s.fire(); + s.fire(); // an overdue tick that ran just before the hang message await flush(); - expect(p.calls.collect).toBe(2); + expect(p.calls.collect).toBe(2); // the tick collected afresh rather than reusing the old hold + await c.hold(); + expect(p.calls.collect).toBe(2); // ...and the hang's hold() reuses the tick's segment + now.t = 3000; await c.hold(); - expect(p.calls.collect).toBe(3); + expect(p.calls.collect).toBe(3); // never retained beyond the TTL }); it('serializes with snapshot(): a snapshot queued behind a hold reuses its segment', async () => { diff --git a/packages/node/src/profiling-controller.ts b/packages/node/src/profiling-controller.ts index 59e451c66..a1af6c46a 100644 --- a/packages/node/src/profiling-controller.ts +++ b/packages/node/src/profiling-controller.ts @@ -25,7 +25,7 @@ export interface ProfilingControllerDeps { * main thread hears all of them at once, when the block ends: only the first would otherwise see the stall in * its profile (the collect restarts the segment, so the rest would get an empty one). */ -const HOLD_MS = 3000; +const HOLD_MS = 3000; // any report in that window shares the held segment, not only a hang's export interface ProfilingController { /** Start sampling + the rolling-restart timer. */ @@ -71,7 +71,10 @@ export function createProfilingController(deps: ProfilingControllerDeps): Profil void profiler.start(); handle = scheduler.setInterval(() => { held = undefined; // never keep a stale segment for a whole window - void collect(false); // discard — the rolling tick just caps the segment length + // The tick caps the segment length, but it can run just BEFORE the watchdog's hang message is handled + // (a block that started in a check-phase callback), taking the stall with it: retain it briefly so the + // hang report's hold() still sees it. + void collect(true); }, rollingIntervalMs); }, From ed463b9c448335ad0a2a643b5ec272c0030ed00f Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 12 Nov 2026 20:33:57 +0500 Subject: [PATCH 05/11] fix(node): decode the profiler's file URLs in hang frames (#14) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSd4XxSkeZk5vaw6dX --- packages/node/src/hang-stack.test.ts | 19 +++++++++++++++++++ packages/node/src/hang-stack.ts | 19 ++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/packages/node/src/hang-stack.test.ts b/packages/node/src/hang-stack.test.ts index af0e77174..4ebf310f1 100644 --- a/packages/node/src/hang-stack.test.ts +++ b/packages/node/src/hang-stack.test.ts @@ -130,6 +130,25 @@ describe('hangCrashFromProfile', () => { expect(frames.map((f) => f.user)).toEqual([true, true, false]); }); + it("decodes the profiler's percent-encoded file URLs to the raw path an Error.stack would carry", () => { + const nodes: N[] = [ + { id: 1, fn: '(root)', children: [2] }, + { id: 2, fn: 'spin', url: 'file:///srv/my%20dir/a.js', line: 0, col: 0 }, + ]; + const frames = hangCrashFromProfile(profile(nodes, [2]), opts)?.exception.frames ?? []; + expect(frames[0]?.data?.source).toBe('/srv/my dir/a.js'); + }); + + it('keeps a malformed file URL rather than losing the frame', () => { + const nodes: N[] = [ + { id: 1, fn: '(root)', children: [2] }, + { id: 2, fn: 'spin', url: 'file://remote-host/srv/a.js', line: 0, col: 0 }, + ]; + const frames = hangCrashFromProfile(profile(nodes, [2]), opts)?.exception.frames ?? []; + expect(frames).toHaveLength(1); + expect(frames[0]?.data?.member).toBe('spin'); + }); + it('caps a pathologically deep stack, keeping the leaf end', () => { const nodes: N[] = [{ id: 1, fn: '(root)', children: [2] }]; for (let i = 2; i <= 200; i += 1) { diff --git a/packages/node/src/hang-stack.ts b/packages/node/src/hang-stack.ts index aa71bae07..f5d1124e8 100644 --- a/packages/node/src/hang-stack.ts +++ b/packages/node/src/hang-stack.ts @@ -1,3 +1,4 @@ +import { fileURLToPath } from 'node:url'; import { buildCrashJson, type CrashJson } from '@bugsee/core'; import type { CpuProfile } from './cpu-profiler'; @@ -43,13 +44,29 @@ const isNode = (value: unknown): value is ProfileNode => { ); }; +/** + * The profiler reports every script as a percent-encoded `file://` URL, CommonJS included, where an + * `Error.stack` carries the raw filesystem path. Decode it so the frame matches the path an uncaught crash + * reports (and so the app-root scrub, which matches raw paths, can make it relative). + */ +function filePath(url: string): string { + if (!url.startsWith('file://')) { + return url; + } + try { + return fileURLToPath(url); + } catch { + return url; // a malformed URL (wrong host, bad escape): keep it as the profiler gave it + } +} + /** One V8 `at …` line. The profile's line/column are 0-based, a stack's are 1-based. */ function frameLine(frame: ProfileNode['callFrame']): string { const name = frame.functionName; if (frame.url === '') { return ` at ${name} ()`; } - const where = `${frame.url}:${frame.lineNumber + 1}:${frame.columnNumber + 1}`; + const where = `${filePath(frame.url)}:${frame.lineNumber + 1}:${frame.columnNumber + 1}`; return name === '' ? ` at ${where}` : ` at ${name} (${where})`; } From b8eeab93f66fd9f06cdbede18c3b9f23f1624350 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 12 Nov 2026 20:39:29 +0500 Subject: [PATCH 06/11] fix(node): never reuse a held profile segment that predates the stall; retain only late ticks (#14) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSd4XxSkeZk5vaw6dX --- .../node/src/hang-detection-provider.test.ts | 11 +++ packages/node/src/hang-detection-provider.ts | 4 +- packages/node/src/launch.test.ts | 6 ++ packages/node/src/launch.ts | 5 +- .../node/src/profiling-controller.test.ts | 84 +++++++++++++++---- packages/node/src/profiling-controller.ts | 30 +++++-- 6 files changed, 111 insertions(+), 29 deletions(-) diff --git a/packages/node/src/hang-detection-provider.test.ts b/packages/node/src/hang-detection-provider.test.ts index 00bd14155..5df89f53a 100644 --- a/packages/node/src/hang-detection-provider.test.ts +++ b/packages/node/src/hang-detection-provider.test.ts @@ -251,6 +251,17 @@ describe('createHangDetectionProvider', () => { ]); }); + it('tells the profile source how long the stall was', async () => { + const asked: number[] = []; + const { fw } = make(async (stallMs) => { + asked.push(stallMs); + return stalled; + }); + fw.hang('medium', 6123); + await flush(); + expect(asked).toEqual([6123]); + }); + it('keeps reporting after a submit throws (one failure must not stall the chain)', async () => { const fw = fakeWatchdog(); const reports: ReportingRequest[] = []; diff --git a/packages/node/src/hang-detection-provider.ts b/packages/node/src/hang-detection-provider.ts index d78cb30c8..45c9ba504 100644 --- a/packages/node/src/hang-detection-provider.ts +++ b/packages/node/src/hang-detection-provider.ts @@ -40,7 +40,7 @@ export interface HangDetectionProviderDeps { * The CPU profile covering the stall, when profiling is on. Resolving undefined (or an unusable profile, or * rejecting) keeps the plain hang report: a crash.json with no frames would make every hang one issue. */ - blockingProfile?: () => Promise; + blockingProfile?: (stallMs: number) => Promise; /** Watchdog factory — tests inject a fake to drive onHang without a real worker. Default the real one. */ createWatchdog?: (deps: EventLoopWatchdogDeps) => EventLoopWatchdog; } @@ -86,7 +86,7 @@ class HangDetectionProvider extends DetectionProviderBase { this.#pending = this.#pending.then(async () => { let crash: CrashJson | undefined; try { - const profile = await source(); + const profile = await source(durationMs); crash = profile !== undefined ? hangCrashFromProfile(profile, { diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index 353ef7ce8..fdb16810b 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -2532,6 +2532,12 @@ describe('launch — capture recovery', () => { // The hang's own profile is still in the bundle (the report reused the held segment, not an empty one). expect(JSON.parse(strFromU8(files['profile.json'] as Uint8Array))).toEqual(cpuProfile); expect(cpuProfiler.collect).toHaveBeenCalledTimes(1); + // The rest of a burst reuses the held segment (the stall length reaches the controller, so it is reusable). + onHang?.('medium', 6000); + await vi.waitFor(() => + expect(transport.mock.calls.filter(([u]) => u === 'https://s3.test/put')).toHaveLength(2), + ); + expect(cpuProfiler.collect).toHaveBeenCalledTimes(1); }); it('without profiling a hang ships no crash.json and keeps its AppHang signature', async () => { diff --git a/packages/node/src/launch.ts b/packages/node/src/launch.ts index a3dbb66ef..bccd44e1b 100644 --- a/packages/node/src/launch.ts +++ b/packages/node/src/launch.ts @@ -1164,7 +1164,10 @@ function buildLaunch(appToken: string, options: BugseeLaunchOptions = {}): Launc // The stall's frames come from the rolling CPU profile (opt-in): without profiling a hang keeps its // fixed AppHang::* signature. Late-bound — the controller is built above, but only when profiling is on. ...(profilingController !== undefined - ? { blockingProfile: () => profilingController?.hold() ?? Promise.resolve(undefined) } + ? { + blockingProfile: (stallMs) => + profilingController?.hold(stallMs) ?? Promise.resolve(undefined), + } : {}), ...(options.hangWatchdogFactory !== undefined ? { createWatchdog: options.hangWatchdogFactory } diff --git a/packages/node/src/profiling-controller.test.ts b/packages/node/src/profiling-controller.test.ts index 8c76c0177..cec6c915f 100644 --- a/packages/node/src/profiling-controller.test.ts +++ b/packages/node/src/profiling-controller.test.ts @@ -173,6 +173,7 @@ describe('createProfilingController', () => { }); describe('hold() — the hang-report segment', () => { + const STALL = 5000; // a stall long enough that the held segment is always after its start const mk = (nowRef: { t: number }) => { const p = fakeProfiler(); const s = fakeScheduler(); @@ -188,7 +189,7 @@ describe('createProfilingController', () => { it('collects the segment and returns the profile', async () => { const { p, c } = mk({ t: 0 }); - expect(await c.hold()).toEqual(p.profile); + expect(await c.hold(STALL)).toEqual(p.profile); expect(p.calls.collect).toBe(1); }); @@ -201,33 +202,33 @@ describe('createProfilingController', () => { rollingIntervalMs: 60_000, }); c.start(); - expect(await c.hold()).toBeUndefined(); - await c.hold(); + expect(await c.hold(STALL)).toBeUndefined(); + await c.hold(STALL); expect(p.calls.collect).toBe(2); // nothing was retained, so the second call collects again }); it('a second hold() within the TTL reuses the held segment instead of collecting an empty one', async () => { const now = { t: 0 }; const { p, c } = mk(now); - await c.hold(); + await c.hold(STALL); now.t = 2999; - expect(await c.hold()).toEqual(p.profile); + expect(await c.hold(STALL)).toEqual(p.profile); expect(p.calls.collect).toBe(1); }); it('collects afresh once the TTL has passed', async () => { const now = { t: 0 }; const { p, c } = mk(now); - await c.hold(); + await c.hold(STALL); now.t = 3000; - await c.hold(); + await c.hold(STALL); expect(p.calls.collect).toBe(2); }); it('snapshot() within the TTL returns the held segment (the hang report keeps its profile.json)', async () => { const now = { t: 0 }; const { p, c } = mk(now); - await c.hold(); + await c.hold(STALL); now.t = 10; const entries = await c.snapshot(1700); expect(entries[0]?.data).toEqual(p.profile); @@ -242,20 +243,67 @@ describe('createProfilingController', () => { expect(p.calls.collect).toBe(2); }); - it('the rolling tick replaces the held segment, and retains its own for a hang report that follows it', async () => { + it('a LATE rolling tick (it ran behind a block) retains its segment for the hang report that follows it', async () => { const now = { t: 0 }; const { p, s, c } = mk(now); - await c.hold(); - s.fire(); // an overdue tick that ran just before the hang message + await c.hold(STALL); + now.t = 60_251; // 251ms behind its interval + s.fire(); await flush(); expect(p.calls.collect).toBe(2); // the tick collected afresh rather than reusing the old hold - await c.hold(); - expect(p.calls.collect).toBe(2); // ...and the hang's hold() reuses the tick's segment - now.t = 3000; - await c.hold(); + now.t = 60_300; + await c.hold(STALL); + expect(p.calls.collect).toBe(2); // the hang's hold() reuses the tick's segment + now.t = 63_251; + await c.hold(STALL); expect(p.calls.collect).toBe(3); // never retained beyond the TTL }); + it('an ON-TIME rolling tick retains nothing (its segment predates any later stall)', async () => { + const now = { t: 0 }; + const { p, s, c } = mk(now); + now.t = 60_250; // exactly on the slack boundary: not late + s.fire(); + await flush(); + now.t = 62_500; + await c.hold(STALL); + expect(p.calls.collect).toBe(2); // hold() collected its own + }); + + it('lateness is measured between ticks, not from launch', async () => { + const now = { t: 0 }; + const { p, s, c } = mk(now); + now.t = 60_000; + s.fire(); + await flush(); + now.t = 120_100; // 60.1s after the previous tick: on time + s.fire(); + await flush(); + await c.hold(STALL); + expect(p.calls.collect).toBe(3); + }); + + it('never reuses a held segment taken before the stall began (an earlier hang, or an earlier tick)', async () => { + const now = { t: 0 }; + const { p, c } = mk(now); + await c.hold(STALL); // an earlier hang's segment, taken at 0 + now.t = 1000; + await c.hold(500); // a new stall that began at 500 + expect(p.calls.collect).toBe(2); + now.t = 1100; + await c.hold(500); // the stall began at 600, the held segment was taken at 1000: reusable + expect(p.calls.collect).toBe(2); + }); + + it('a segment taken exactly when the stall began is not reusable (it ended before the stall)', async () => { + const now = { t: 0 }; + const { p, c } = mk(now); + await c.hold(STALL); // taken at 0 + now.t = 1000; + await c.hold(1000); // the stall began at 0 + expect(p.calls.collect).toBe(2); + }); + it('serializes with snapshot(): a snapshot queued behind a hold reuses its segment', async () => { const p = fakeProfiler({ defer: true }); const s = fakeScheduler(); @@ -266,7 +314,7 @@ describe('createProfilingController', () => { now: () => 0, }); c.start(); - const held = c.hold(); + const held = c.hold(STALL); const snap = c.snapshot(5); await flush(); p.resolveNext(aProfile({ endTime: 7 })); @@ -277,9 +325,9 @@ describe('createProfilingController', () => { it('stop() drops the held segment', async () => { const { p, c } = mk({ t: 0 }); - await c.hold(); + await c.hold(STALL); c.stop(); - await c.hold(); + await c.hold(STALL); expect(p.calls.collect).toBe(2); }); }); diff --git a/packages/node/src/profiling-controller.ts b/packages/node/src/profiling-controller.ts index a1af6c46a..f5dd0df2f 100644 --- a/packages/node/src/profiling-controller.ts +++ b/packages/node/src/profiling-controller.ts @@ -27,6 +27,9 @@ export interface ProfilingControllerDeps { */ const HOLD_MS = 3000; // any report in that window shares the held segment, not only a hang's +/** A rolling tick this much later than its interval ran behind a block: its segment may hold a stall. */ +const LATE_TICK_MS = 250; + export interface ProfilingController { /** Start sampling + the rolling-restart timer. */ start(): void; @@ -35,8 +38,10 @@ export interface ProfilingController { /** * Collect the current segment for a HANG report and retain it for a few seconds, so the burst of escalation * reports (and the profile.json each bundles) all see the stall. Resolves undefined when there is no profile. + * `stallMs` is the stall's measured length: a retained segment taken before the stall began (an earlier hang's, + * or an earlier tick's) is never reused, so a hang cannot be reported with another one's frames. */ - hold(): Promise; + hold(stallMs: number): Promise; /** Stop the rolling timer and the profiler. */ stop(): void; } @@ -46,13 +51,18 @@ export function createProfilingController(deps: ProfilingControllerDeps): Profil const now = deps.now ?? Date.now; let handle: unknown; let held: { profile: CpuProfile; at: number } | undefined; + let lastTickAt = now(); // Serialize every collect() so the rolling tick and a report never stop+restart the session at once. // profiler.collect() resolves (never rejects), so the chain stays settled. let chain: Promise = Promise.resolve(); - const collect = (retain: boolean): Promise => { + const collect = (retain: boolean, notBefore?: number): Promise => { const next = chain.then(async () => { - if (held !== undefined && now() - held.at < HOLD_MS) { + if ( + held !== undefined && + now() - held.at < HOLD_MS && + (notBefore === undefined || held.at > notBefore) + ) { return held.profile; } held = undefined; @@ -69,12 +79,16 @@ export function createProfilingController(deps: ProfilingControllerDeps): Profil return { start() { void profiler.start(); + lastTickAt = now(); handle = scheduler.setInterval(() => { held = undefined; // never keep a stale segment for a whole window - // The tick caps the segment length, but it can run just BEFORE the watchdog's hang message is handled - // (a block that started in a check-phase callback), taking the stall with it: retain it briefly so the - // hang report's hold() still sees it. - void collect(true); + // The tick caps the segment length, but a tick that ran LATE ran behind a block, just BEFORE the + // watchdog's hang message was handled, taking the stall with it: retain that one briefly so the hang + // report's hold() still sees it. An on-time tick holds nothing of a later stall, so it keeps nothing. + const at = now(); + const late = at - lastTickAt > rollingIntervalMs + LATE_TICK_MS; + lastTickAt = at; + void collect(late); }, rollingIntervalMs); }, @@ -83,7 +97,7 @@ export function createProfilingController(deps: ProfilingControllerDeps): Profil return profile ? [new CaptureDataEntryBase('profile', now, profile)] : []; }, - hold: () => collect(true), + hold: (stallMs) => collect(true, now() - stallMs), stop() { held = undefined; From d16260d06165664b5ccd0ab90349716f121b132b Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 12 Nov 2026 20:39:54 +0500 Subject: [PATCH 07/11] test(node): type the stall argument of the profile source (#14) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSd4XxSkeZk5vaw6dX --- packages/node/src/hang-detection-provider.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/node/src/hang-detection-provider.test.ts b/packages/node/src/hang-detection-provider.test.ts index 5df89f53a..c74a80716 100644 --- a/packages/node/src/hang-detection-provider.test.ts +++ b/packages/node/src/hang-detection-provider.test.ts @@ -131,7 +131,7 @@ describe('createHangDetectionProvider', () => { samples: [2, 2, 2], timeDeltas: [1000, 1000, 1000], }; - const make = (blockingProfile: () => Promise) => { + const make = (blockingProfile: (stallMs: number) => Promise) => { const fw = fakeWatchdog(); const reports: ReportingRequest[] = []; const p = createHangDetectionProvider({ From b88fd48695745b483cfb93ec9216aad6fe972caf Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 12 Nov 2026 20:44:38 +0500 Subject: [PATCH 08/11] fix(node): a rolling tick never discards a fresh held hang segment (#14) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSd4XxSkeZk5vaw6dX --- packages/node/src/profiling-controller.test.ts | 13 +++++++++++++ packages/node/src/profiling-controller.ts | 7 ++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/packages/node/src/profiling-controller.test.ts b/packages/node/src/profiling-controller.test.ts index cec6c915f..183dbad55 100644 --- a/packages/node/src/profiling-controller.test.ts +++ b/packages/node/src/profiling-controller.test.ts @@ -259,6 +259,19 @@ describe('createProfilingController', () => { expect(p.calls.collect).toBe(3); // never retained beyond the TTL }); + it("a tick that lands right after a hang's hold leaves the held stall alone (no collect, no discard)", async () => { + const now = { t: 60_300 }; + const { p, s, c } = mk(now); + await c.hold(STALL); // the hang's segment, taken at 60300 + now.t = 60_400; + s.fire(); // the overdue tick, handled after the hang message + await flush(); + expect(p.calls.collect).toBe(1); + const entries = await c.snapshot(5); // the hang report's profile.json is still the stall + expect(entries[0]?.data).toEqual(p.profile); + expect(p.calls.collect).toBe(1); + }); + it('an ON-TIME rolling tick retains nothing (its segment predates any later stall)', async () => { const now = { t: 0 }; const { p, s, c } = mk(now); diff --git a/packages/node/src/profiling-controller.ts b/packages/node/src/profiling-controller.ts index f5dd0df2f..f446b0bdc 100644 --- a/packages/node/src/profiling-controller.ts +++ b/packages/node/src/profiling-controller.ts @@ -81,13 +81,18 @@ export function createProfilingController(deps: ProfilingControllerDeps): Profil void profiler.start(); lastTickAt = now(); handle = scheduler.setInterval(() => { - held = undefined; // never keep a stale segment for a whole window // The tick caps the segment length, but a tick that ran LATE ran behind a block, just BEFORE the // watchdog's hang message was handled, taking the stall with it: retain that one briefly so the hang // report's hold() still sees it. An on-time tick holds nothing of a later stall, so it keeps nothing. const at = now(); const late = at - lastTickAt > rollingIntervalMs + LATE_TICK_MS; lastTickAt = at; + // A fresh held segment already bounds the segment length and holds a stall: a tick landing after it (a + // block that ran in a timer callback delivers the hang message first) must not discard it. + if (held !== undefined && at - held.at < HOLD_MS) { + return; + } + held = undefined; // never keep a stale segment for a whole window void collect(late); }, rollingIntervalMs); }, From fcf6b999061a42c09e9605d9bcaa845df2f52b13 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 12 Nov 2026 21:00:45 +0500 Subject: [PATCH 09/11] fix(node): attribute builtin/runtime time to the application caller, anchor the window at the profile end, stable hang reason (#14) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSd4XxSkeZk5vaw6dX --- .../node/src/hang-detection-provider.test.ts | 12 +-- packages/node/src/hang-detection-provider.ts | 3 +- packages/node/src/hang-stack.test.ts | 82 +++++++++++++++++-- packages/node/src/hang-stack.ts | 43 ++++++++-- packages/node/src/launch.test.ts | 4 +- 5 files changed, 121 insertions(+), 23 deletions(-) diff --git a/packages/node/src/hang-detection-provider.test.ts b/packages/node/src/hang-detection-provider.test.ts index c74a80716..4246be7e1 100644 --- a/packages/node/src/hang-detection-provider.test.ts +++ b/packages/node/src/hang-detection-provider.test.ts @@ -127,9 +127,9 @@ describe('createHangDetectionProvider', () => { }, ], startTime: 0, - endTime: 20_000_000, + endTime: 20_002_000, samples: [2, 2, 2], - timeDeltas: [1000, 1000, 1000], + timeDeltas: [20_000_000, 1000, 1000], }; const make = (blockingProfile: (stallMs: number) => Promise) => { const fw = fakeWatchdog(); @@ -151,7 +151,7 @@ describe('createHangDetectionProvider', () => { expect(reports).toHaveLength(1); const r = reports[0] as ReportingRequest; expect(exceptionOf(r)?.domain).toBe('AppHang::Severe'); - expect(exceptionOf(r)?.reason).toBe('Event loop blocked for 12000ms'); + expect(exceptionOf(r)?.reason).toBe('Event loop blocked (AppHang::Severe)'); expect(exceptionOf(r)?.frames[0]?.data).toEqual({ source: '/srv/app.js', member: 'crunch', @@ -180,7 +180,8 @@ describe('createHangDetectionProvider', () => { }, ], samples: [3, 3, 3, 2], - timeDeltas: [1000, 1000, 1000, 1000], + timeDeltas: [20_000_000, 1000, 1000, 1000], + endTime: 20_003_000, }; const { fw, reports } = make(async () => window); fw.hang('fair', 1); // a 1ms window: only the newest sample @@ -225,7 +226,8 @@ describe('createHangDetectionProvider', () => { }, ], samples: [3, 3, 3, 2], - timeDeltas: [1000, 1000, 1000, 1000], + timeDeltas: [20_000_000, 1000, 1000, 1000], + endTime: 20_003_000, }; const { fw, reports } = make(async () => older); fw.hang('fair', 4); diff --git a/packages/node/src/hang-detection-provider.ts b/packages/node/src/hang-detection-provider.ts index 45c9ba504..294b32b29 100644 --- a/packages/node/src/hang-detection-provider.ts +++ b/packages/node/src/hang-detection-provider.ts @@ -92,7 +92,8 @@ class HangDetectionProvider extends DetectionProviderBase { ? hangCrashFromProfile(profile, { windowMs: durationMs, domain, - reason: `Event loop blocked for ${durationMs}ms`, + // Stable per level: the measured duration varies per occurrence and must not feed grouping. + reason: `Event loop blocked (${domain})`, }) : undefined; } catch { diff --git a/packages/node/src/hang-stack.test.ts b/packages/node/src/hang-stack.test.ts index 4ebf310f1..62e3dcf5a 100644 --- a/packages/node/src/hang-stack.test.ts +++ b/packages/node/src/hang-stack.test.ts @@ -27,9 +27,10 @@ const node = (n: N) => ({ const profile = (nodes: N[], samples: number[], deltaUs = 1000): CpuProfile => ({ nodes: nodes.map(node), startTime: 0, - endTime: 10_000_000, // spans any window the tests use + // The first delta is the idle lead-in since the profile started, so it spans any window the tests use. + endTime: 10_000_000 + (samples.length - 1) * deltaUs, samples, - timeDeltas: samples.map(() => deltaUs), + timeDeltas: samples.map((_, i) => (i === 0 ? 10_000_000 : deltaUs)), }); // root → main(app.js) → parse(lib.js) ; main → render(app.js) @@ -46,7 +47,7 @@ const TREE: N[] = [ const opts = { windowMs: 1000, domain: 'AppHang::Severe', - reason: 'Event loop blocked for 12000ms', + reason: 'Event loop blocked (AppHang::Severe)', }; describe('hangCrashFromProfile', () => { @@ -57,7 +58,7 @@ describe('hangCrashFromProfile', () => { expect(crash?.ndkCrash).toBe(false); expect(crash?.handled).toBe(true); expect(crash?.exception.name).toBe('AppHang'); - expect(crash?.exception.reason).toBe('Event loop blocked for 12000ms'); + expect(crash?.exception.reason).toBe('Event loop blocked (AppHang::Severe)'); expect(crash?.exception.domain).toBe('AppHang::Severe'); expect(crash?.exception.frames.map((f) => f.data)).toEqual([ { source: '/srv/lib.js', member: 'parse', line: 1, column: 1 }, @@ -109,7 +110,7 @@ describe('hangCrashFromProfile', () => { it('skips samples that point at an unknown node and tolerates missing timeDeltas', () => { const p = profile(TREE, [99, 3]); - delete (p as { timeDeltas?: number[] }).timeDeltas; + delete (p as { timeDeltas?: number[] }).timeDeltas; // no deltas: the window cannot be placed, all samples count expect(hangCrashFromProfile(p, opts)?.exception.frames[0]?.data?.member).toBe('parse'); }); @@ -122,12 +123,64 @@ describe('hangCrashFromProfile', () => { ]; const crash = hangCrashFromProfile(profile(nodes, [4]), opts); const frames = crash?.exception.frames ?? []; + // The native leaf's time is attributed to the application frame that called it (see the next tests). expect(frames.map((f) => f.trace)).toEqual([ - 'at parse ()', 'at (/srv/app.js:5:2)', 'at (node:internal/main/run_main_module:1:1)', ]); - expect(frames.map((f) => f.user)).toEqual([true, true, false]); + expect(frames.map((f) => f.user)).toEqual([true, false]); + }); + + it("attributes a native builtin's time to its application caller, so different callers do not group together", () => { + const nodes: N[] = [ + { id: 1, fn: '(root)', children: [2, 4] }, + { id: 2, fn: 'routeA', url: 'file:///srv/a.js', line: 0, col: 0, children: [3] }, + { id: 3, fn: 'parse' }, // JSON.parse + { id: 4, fn: 'routeB', url: 'file:///srv/b.js', line: 0, col: 0, children: [5] }, + { id: 5, fn: 'parse' }, + ]; + const a = hangCrashFromProfile(profile(nodes, [3, 3, 3]), opts); + const b = hangCrashFromProfile(profile(nodes, [5, 5, 5]), opts); + expect(a?.exception.frames[0]?.data?.member).toBe('routeA'); + expect(b?.exception.frames[0]?.data?.member).toBe('routeB'); + }); + + it("pools a builtin's samples with its caller's own, across different builtins", () => { + const nodes: N[] = [ + { id: 1, fn: '(root)', children: [2, 5] }, + { id: 2, fn: 'busy', url: 'file:///srv/a.js', line: 0, col: 0, children: [3, 4] }, + { id: 3, fn: 'parse' }, + { id: 4, fn: 'sort' }, + { id: 5, fn: 'other', url: 'file:///srv/b.js', line: 0, col: 0 }, + ]; + // 2+2 samples under `busy` (self + builtins) beat 3 in `other`. + const crash = hangCrashFromProfile(profile(nodes, [3, 3, 4, 4, 5, 5, 5]), opts); + expect(crash?.exception.frames[0]?.data?.member).toBe('busy'); + }); + + it('is undefined when the only time was in runtime internals or builtins with no application caller', () => { + const nodes: N[] = [ + { id: 1, fn: '(root)', children: [2] }, + { + id: 2, + fn: 'tick', + url: 'node:internal/process/task_queues', + line: 0, + col: 0, + children: [3], + }, + { id: 3, fn: 'parse' }, + ]; + expect(hangCrashFromProfile(profile(nodes, [2, 3]), opts)).toBeUndefined(); + }); + + it('anchors the window at the profile END: samples older than the stall are not the stall', () => { + // The last sample is 1ms in, and the profile runs on idle to 10s: a 3s window ending at 10s sees none. + const p = { ...profile(TREE, [3]), timeDeltas: [1000], endTime: 10_000_000 }; + expect(hangCrashFromProfile(p, { ...opts, windowMs: 3000 })).toBeUndefined(); + // ...but a sample inside the trailing window counts. + const recent = { ...profile(TREE, [3]), timeDeltas: [9_999_000], endTime: 10_000_000 }; + expect(hangCrashFromProfile(recent, { ...opts, windowMs: 3000 })).toBeDefined(); }); it("decodes the profiler's percent-encoded file URLs to the raw path an Error.stack would carry", () => { @@ -149,6 +202,21 @@ describe('hangCrashFromProfile', () => { expect(frames[0]?.data?.member).toBe('spin'); }); + it('keeps a native builtin that sits BETWEEN application frames, rendered as V8 does', () => { + const nodes: N[] = [ + { id: 1, fn: '(root)', children: [2] }, + { id: 2, fn: 'main', url: 'file:///srv/app.js', line: 0, col: 0, children: [3] }, + { id: 3, fn: 'map', children: [4] }, // Array.prototype.map calling back into the app + { id: 4, fn: 'cb', url: 'file:///srv/app.js', line: 4, col: 2 }, + ]; + const frames = hangCrashFromProfile(profile(nodes, [4]), opts)?.exception.frames ?? []; + expect(frames.map((f) => f.trace)).toEqual([ + 'at cb (/srv/app.js:5:3)', + 'at map ()', + 'at main (/srv/app.js:1:1)', + ]); + }); + it('caps a pathologically deep stack, keeping the leaf end', () => { const nodes: N[] = [{ id: 1, fn: '(root)', children: [2] }]; for (let i = 2; i <= 200; i += 1) { diff --git a/packages/node/src/hang-stack.ts b/packages/node/src/hang-stack.ts index f5d1124e8..f3f4e159a 100644 --- a/packages/node/src/hang-stack.ts +++ b/packages/node/src/hang-stack.ts @@ -25,7 +25,7 @@ interface ProfileNode { } export interface HangCrashOptions { - /** The trailing slice of the profile to look at, in ms: the stall (the level's threshold), not older work. */ + /** The trailing slice of the profile to look at, in ms: the measured stall, not older work. */ windowMs: number; /** `AppHang::Fair|Medium|Severe`. */ domain: string; @@ -70,6 +70,16 @@ function frameLine(frame: ProfileNode['callFrame']): string { return name === '' ? ` at ${where}` : ` at ${name} (${where})`; } +/** + * Is this the application's own code, as opposed to the profiler's pseudo-frames, a native builtin (no script: + * `JSON.parse`, `sort`, a regex exec) or a runtime module (`node:internal/...`)? A builtin or runtime frame on + * top would group every hang that ends in the same builtin into one issue whatever called it, so time spent + * there is attributed to the application frame that called in. + */ +function isApplicationFrame(frame: ProfileNode['callFrame']): boolean { + return frame.url !== '' && !frame.url.startsWith('node:'); // the pseudo-frames have no script either +} + /** The `id`s of the node's ancestors are not stored, only its children: invert them once. */ function parentsOf(nodes: Map): Map { const parents = new Map(); @@ -83,7 +93,7 @@ function parentsOf(nodes: Map): Map { /** * The `crash.json` for a hang, from the CPU profile taken at its report; undefined when the profile holds no - * application stack in the window (nothing sampled, or only idle/program/GC), so the report ships as it does + * application stack in the window (nothing sampled, or only idle/program/GC or runtime internals), so the report ships as it does * without profiling rather than with an empty crash. */ export function hangCrashFromProfile( @@ -106,15 +116,33 @@ export function hangCrashFromProfile( } } - // Self samples per node over the trailing window, newest first. `timeDeltas[i]` is the gap before sample i. + const parents = parentsOf(nodes); + /** The call site a sample's time belongs to: itself, or its nearest ancestor that is application code. */ + const callSite = (start: number): number | undefined => { + let id: number | undefined = start; + for (let steps = 0; id !== undefined && steps <= nodes.size; steps += 1) { + const frame = nodes.get(id)?.callFrame; + if (frame !== undefined && isApplicationFrame(frame)) { + return id; + } + id = parents.get(id); + } + return undefined; + }; + + // Self samples per call site over the trailing window, newest first. `timeDeltas[i]` is the gap before sample + // i, and the newest sample may itself be older than the profile's end (the loop was idle since). const windowUs = options.windowMs * 1000; const counts = new Map(); let elapsedUs = 0; + if (timeDeltas !== undefined) { + const sampledUs = timeDeltas.reduce((sum, delta) => sum + delta, 0); + elapsedUs = Math.max(0, profile.endTime - profile.startTime - sampledUs); + } for (let i = samples.length - 1; i >= 0 && elapsedUs < windowUs; i -= 1) { - const id = samples[i] as number; - const node = nodes.get(id); - if (node !== undefined && !PSEUDO.has(node.callFrame.functionName)) { - counts.set(id, (counts.get(id) ?? 0) + 1); + const site = callSite(samples[i] as number); + if (site !== undefined) { + counts.set(site, (counts.get(site) ?? 0) + 1); } elapsedUs += timeDeltas?.[i] ?? 0; } @@ -131,7 +159,6 @@ export function hangCrashFromProfile( return undefined; } - const parents = parentsOf(nodes); const lines: string[] = []; // Steps are bounded by the node count, so a (malformed) parent cycle through skipped pseudo frames ends too. let steps = 0; diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index fdb16810b..10b2cc918 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -2494,9 +2494,9 @@ describe('launch — capture recovery', () => { }, ], startTime: 0, - endTime: 20_000_000, + endTime: 20_002_000, samples: [2, 2, 2], - timeDeltas: [1000, 1000, 1000], + timeDeltas: [20_000_000, 1000, 1000], }; const cpuProfiler = { running: false, From 7d853922129904b545c50dc6b7065d5a681eaaa6 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Thu, 12 Nov 2026 21:03:30 +0500 Subject: [PATCH 10/11] fix(node): treat Bun internal: and @bugsee frames as non-application when attributing hang time (#14) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSd4XxSkeZk5vaw6dX --- packages/node/src/hang-stack.test.ts | 14 ++++++++++++++ packages/node/src/hang-stack.ts | 11 +++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/packages/node/src/hang-stack.test.ts b/packages/node/src/hang-stack.test.ts index 62e3dcf5a..67f6f5a0d 100644 --- a/packages/node/src/hang-stack.test.ts +++ b/packages/node/src/hang-stack.test.ts @@ -217,6 +217,20 @@ describe('hangCrashFromProfile', () => { ]); }); + it.each([ + ['Bun runtime library', 'internal:util/inspect'], + ['Node runtime module', 'node:path'], + ['the SDK itself', 'file:///srv/node_modules/@bugsee/core/dist/index.js'], + ])('attributes time spent in %s to the application caller', (_what, url) => { + const nodes: N[] = [ + { id: 1, fn: '(root)', children: [2] }, + { id: 2, fn: 'handler', url: 'file:///srv/app.js', line: 0, col: 0, children: [3] }, + { id: 3, fn: 'busy', url, line: 0, col: 0 }, + ]; + const crash = hangCrashFromProfile(profile(nodes, [3, 3, 3]), opts); + expect(crash?.exception.frames[0]?.data?.member).toBe('handler'); + }); + it('caps a pathologically deep stack, keeping the leaf end', () => { const nodes: N[] = [{ id: 1, fn: '(root)', children: [2] }]; for (let i = 2; i <= 200; i += 1) { diff --git a/packages/node/src/hang-stack.ts b/packages/node/src/hang-stack.ts index f3f4e159a..37bc1667e 100644 --- a/packages/node/src/hang-stack.ts +++ b/packages/node/src/hang-stack.ts @@ -72,12 +72,19 @@ function frameLine(frame: ProfileNode['callFrame']): string { /** * Is this the application's own code, as opposed to the profiler's pseudo-frames, a native builtin (no script: - * `JSON.parse`, `sort`, a regex exec) or a runtime module (`node:internal/...`)? A builtin or runtime frame on + * `JSON.parse`, `sort`, a regex exec) or a runtime/SDK module (`node:internal/...`, Bun's `internal:...`, `@bugsee/*`)? A builtin or runtime frame on * top would group every hang that ends in the same builtin into one issue whatever called it, so time spent * there is attributed to the application frame that called in. */ function isApplicationFrame(frame: ProfileNode['callFrame']): boolean { - return frame.url !== '' && !frame.url.startsWith('node:'); // the pseudo-frames have no script either + const { url } = frame; // the pseudo-frames have no script either + // `node:` is Node's runtime, `internal:` Bun's; the SDK's own packages sit between the app and its work too. + return ( + url !== '' && + !url.startsWith('node:') && + !url.startsWith('internal:') && + !url.includes('/@bugsee/') + ); } /** The `id`s of the node's ancestors are not stored, only its children: invert them once. */ From 299016be14bcdfc40fe83f825830d082ee9eed8b Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Tue, 17 Nov 2026 13:55:24 +0500 Subject: [PATCH 11/11] fix(node): bound the wait for a hang's CPU profile so a stuck source cannot suppress reports (#14) Co-Authored-By: Claude Sonnet 5.5 --- .../node/src/hang-detection-provider.test.ts | 28 +++++++++++++++++++ packages/node/src/hang-detection-provider.ts | 16 ++++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/packages/node/src/hang-detection-provider.test.ts b/packages/node/src/hang-detection-provider.test.ts index 4246be7e1..e9fc50bda 100644 --- a/packages/node/src/hang-detection-provider.test.ts +++ b/packages/node/src/hang-detection-provider.test.ts @@ -299,6 +299,34 @@ describe('createHangDetectionProvider', () => { ]); }); + it('submits the plain signature report when the profile never settles, and keeps later reports flowing', async () => { + const fw = fakeWatchdog(); + const reports: ReportingRequest[] = []; + let calls = 0; + const p = createHangDetectionProvider({ + thresholds: T, + createWatchdog: fw.create, + blockingProfileTimeoutMs: 15, + blockingProfile: () => { + calls += 1; + return calls === 1 + ? new Promise(() => {}) + : Promise.resolve(stalled); + }, + }); + p.start(fakeClient, (r) => reports.push(r)); + fw.hang('fair', 3000); + fw.hang('medium', 5000); + await new Promise((r) => setTimeout(r, 80)); + expect(reports.map((r) => r.report.labels?.[0])).toEqual([ + 'AppHang::Fair', + 'AppHang::Medium', + ]); + expect(reports[0]?.report.signatures).toEqual(['AppHang::Fair']); + expect(reports[0]?.report.crash).toBeUndefined(); + expect(reports[1]?.report.crash).toBeDefined(); + }); + it('does not deliver a report whose profile resolves after stop()', async () => { const { fw, reports, p } = make(async () => stalled); fw.hang('fair', 3000); diff --git a/packages/node/src/hang-detection-provider.ts b/packages/node/src/hang-detection-provider.ts index 294b32b29..0537705a7 100644 --- a/packages/node/src/hang-detection-provider.ts +++ b/packages/node/src/hang-detection-provider.ts @@ -41,6 +41,8 @@ export interface HangDetectionProviderDeps { * rejecting) keeps the plain hang report: a crash.json with no frames would make every hang one issue. */ blockingProfile?: (stallMs: number) => Promise; + /** Longest wait for the profile before the plain signature report goes out instead (ms). Default 5000. */ + blockingProfileTimeoutMs?: number; /** Watchdog factory — tests inject a fake to drive onHang without a real worker. Default the real one. */ createWatchdog?: (deps: EventLoopWatchdogDeps) => EventLoopWatchdog; } @@ -53,9 +55,11 @@ class HangDetectionProvider extends DetectionProviderBase { // Escalation reports (fair → medium → severe) arrive together; chaining keeps them in order while each // awaits its profile. #pending: Promise = Promise.resolve(); + readonly #profileTimeoutMs: number; constructor(deps: HangDetectionProviderDeps) { super(); + this.#profileTimeoutMs = deps.blockingProfileTimeoutMs ?? 5000; this.#blockingProfile = deps.blockingProfile; const create = deps.createWatchdog ?? createEventLoopWatchdog; this.#watchdog = create({ @@ -86,7 +90,7 @@ class HangDetectionProvider extends DetectionProviderBase { this.#pending = this.#pending.then(async () => { let crash: CrashJson | undefined; try { - const profile = await source(durationMs); + const profile = await this.#withDeadline(source(durationMs)); crash = profile !== undefined ? hangCrashFromProfile(profile, { @@ -104,6 +108,16 @@ class HangDetectionProvider extends DetectionProviderBase { this.#pending = this.#pending.catch(() => undefined); // one failed submit must not stall later reports } + /** A profile source that never settles must not hold back this and every later report: give up with undefined. */ + #withDeadline(profile: Promise): Promise { + let timer: ReturnType | undefined; + const expired = new Promise((resolve) => { + timer = setTimeout(() => resolve(undefined), this.#profileTimeoutMs); + (timer as { unref?: () => void }).unref?.(); + }); + return Promise.race([profile, expired]).finally(() => clearTimeout(timer)); + } + #submit(domain: string, durationMs: number, crash?: CrashJson): void { this.handleReportingRequest( this.createErrorReport({