diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index c07fd977..3b6946b0 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 (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/instrumentation-tests/test/instrumentation.e2e.ts b/packages/instrumentation-tests/test/instrumentation.e2e.ts index e88f77a4..49db6134 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 083e519d..e9fc50bd 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,234 @@ 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: 20_002_000, + samples: [2, 2, 2], + timeDeltas: [20_000_000, 1000, 1000], + }; + const make = (blockingProfile: (stallMs: number) => 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 (AppHang::Severe)'); + 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: [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 + 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: [20_000_000, 1000, 1000, 1000], + endTime: 20_003_000, + }; + 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('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[] = []; + 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); + 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('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); + 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 fa4a5c2c..0537705a 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,13 @@ 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?: (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; } @@ -36,9 +51,16 @@ 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(); + readonly #profileTimeoutMs: number; constructor(deps: HangDetectionProviderDeps) { super(); + this.#profileTimeoutMs = deps.blockingProfileTimeoutMs ?? 5000; + this.#blockingProfile = deps.blockingProfile; const create = deps.createWatchdog ?? createEventLoopWatchdog; this.#watchdog = create({ thresholds: deps.thresholds, @@ -60,13 +82,51 @@ 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 this.#withDeadline(source(durationMs)); + crash = + profile !== undefined + ? hangCrashFromProfile(profile, { + windowMs: durationMs, + domain, + // Stable per level: the measured duration varies per occurrence and must not feed grouping. + reason: `Event loop blocked (${domain})`, + }) + : undefined; + } catch { + crash = undefined; // no stack is better than no report + } + this.#submit(domain, durationMs, crash); + }); + 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({ 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 00000000..67f6f5a0 --- /dev/null +++ b/packages/node/src/hang-stack.test.ts @@ -0,0 +1,266 @@ +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, + // 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((_, i) => (i === 0 ? 10_000_000 : 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 (AppHang::Severe)', +}; + +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(true); + expect(crash?.exception.name).toBe('AppHang'); + 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 }, + { 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 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(); + }); + + 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; // no deltas: the window cannot be placed, all samples count + 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 ?? []; + // 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 (/srv/app.js:5:2)', + 'at (node:internal/main/run_main_module:1:1)', + ]); + 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", () => { + 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('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.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) { + 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('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 }); + 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 00000000..37bc1667 --- /dev/null +++ b/packages/node/src/hang-stack.ts @@ -0,0 +1,190 @@ +import { fileURLToPath } from 'node:url'; +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. `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; + +/** 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 measured stall, 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 + ); +}; + +/** + * 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 = `${filePath(frame.url)}:${frame.lineNumber + 1}:${frame.columnNumber + 1}`; + 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/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 { + 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. */ +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 or runtime internals), 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; + } + // 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)) { + nodes.set(candidate.id, candidate); + } + } + + 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 site = callSite(samples[i] as number); + if (site !== undefined) { + counts.set(site, (counts.get(site) ?? 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 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 && 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)); + } + } + + const error = new Error(options.reason); + error.name = 'AppHang'; + error.stack = `AppHang: ${options.reason}\n${lines.join('\n')}`; + 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 dbb11740..10b2cc91 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -2474,6 +2474,99 @@ 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: 20_002_000, + samples: [2, 2, 2], + timeDeltas: [20_000_000, 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); + // 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 () => { + 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 2fb72b97..bccd44e1 100644 --- a/packages/node/src/launch.ts +++ b/packages/node/src/launch.ts @@ -1161,6 +1161,14 @@ 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: (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 ee5238cb..183dbad5 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) @@ -169,4 +171,177 @@ 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 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(); + 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(STALL)).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(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(STALL); + now.t = 2999; + 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(STALL); + now.t = 3000; + 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(STALL); + 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('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(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 + 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("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); + 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(); + const c = createProfilingController({ + profiler: p.profiler, + scheduler: s.scheduler, + rollingIntervalMs: 60_000, + now: () => 0, + }); + c.start(); + const held = c.hold(STALL); + 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(STALL); + c.stop(); + 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 d09d4fec..f446b0bd 100644 --- a/packages/node/src/profiling-controller.ts +++ b/packages/node/src/profiling-controller.ts @@ -16,26 +16,62 @@ 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; // 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; /** 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. + * `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(stallMs: number): 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; + 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 = (): Promise => { - const next = chain.then(() => profiler.collect()); + const collect = (retain: boolean, notBefore?: number): Promise => { + const next = chain.then(async () => { + if ( + held !== undefined && + now() - held.at < HOLD_MS && + (notBefore === undefined || held.at > notBefore) + ) { + return held.profile; + } + held = undefined; + const profile = await profiler.collect(); + if (retain && profile !== undefined) { + held = { profile, at: now() }; + } + return profile; + }); chain = next; return next; }; @@ -43,17 +79,33 @@ export function createProfilingController(deps: ProfilingControllerDeps): Profil return { start() { void profiler.start(); + lastTickAt = now(); handle = scheduler.setInterval(() => { - void collect(); // discard — the rolling tick just caps the segment length + // 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); }, async snapshot(now: number): Promise { - const profile = await collect(); + const profile = await collect(false); return profile ? [new CaptureDataEntryBase('profile', now, profile)] : []; }, + hold: (stallMs) => collect(true, now() - stallMs), + stop() { + held = undefined; if (handle !== undefined) { scheduler.clearInterval(handle); handle = undefined;