Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/PROGRESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
25 changes: 25 additions & 0 deletions packages/instrumentation-tests/test/instrumentation.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Crash>(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', () => {
Expand Down
234 changes: 233 additions & 1 deletion packages/node/src/hang-detection-provider.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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: () => {} };
Expand Down Expand Up @@ -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<CpuProfile | undefined>) => {
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<CpuProfile | undefined>]> = [
['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<CpuProfile | undefined>(() => {})
: 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);
});
});
});
Loading