Skip to content

Commit 1aa0f6d

Browse files
fix(diagnostics): bound recent phase attribution
1 parent ebae858 commit 1aa0f6d

4 files changed

Lines changed: 105 additions & 5 deletions

File tree

‎src/logging/diagnostic-phase.test.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Diagnostic phase tests cover phase timing and diagnostic event emission.
2-
import { describe, expect, it } from "vitest";
2+
import { describe, expect, it, vi } from "vitest";
33
import {
4+
getCurrentDiagnosticPhase,
45
getRecentDiagnosticPhases,
56
resetDiagnosticPhasesForTest,
67
withDiagnosticPhase,
@@ -27,4 +28,42 @@ describe("getRecentDiagnosticPhases", () => {
2728
expect(recent).toHaveLength(1);
2829
expect(recent[0]?.name).toBe("phase-b");
2930
});
31+
32+
it("filters completed phases by attribution time without discarding retained history", async () => {
33+
resetDiagnosticPhasesForTest();
34+
const nowSpy = vi.spyOn(Date, "now").mockReturnValue(1_000);
35+
try {
36+
await withDiagnosticPhase("phase-a", () => undefined);
37+
38+
expect(getRecentDiagnosticPhases(1, { completedAfter: 1_001 })).toEqual([]);
39+
expect(getRecentDiagnosticPhases(1)).toEqual([
40+
expect.objectContaining({ name: "phase-a", endedAt: 1_000 }),
41+
]);
42+
} finally {
43+
nowSpy.mockRestore();
44+
}
45+
});
46+
47+
it("does not apply completed-phase recency filtering to active phases", async () => {
48+
resetDiagnosticPhasesForTest();
49+
let releasePhase: (() => void) | undefined;
50+
const phase = withDiagnosticPhase(
51+
"legitimate.long-running-work",
52+
() =>
53+
new Promise<void>((resolve) => {
54+
releasePhase = resolve;
55+
}),
56+
);
57+
if (!releasePhase) {
58+
throw new Error("Expected diagnostic phase release callback to be initialized");
59+
}
60+
61+
try {
62+
expect(getRecentDiagnosticPhases(1, { completedAfter: Date.now() })).toEqual([]);
63+
expect(getCurrentDiagnosticPhase()).toBe("legitimate.long-running-work");
64+
} finally {
65+
releasePhase();
66+
await phase;
67+
}
68+
});
3069
});

‎src/logging/diagnostic-phase.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,22 @@ function resolveRecentPhaseLimit(limit: number): number | null {
4747
return Math.floor(limit);
4848
}
4949

50-
export function getRecentDiagnosticPhases(limit = 8): DiagnosticPhaseSnapshot[] {
50+
export function getRecentDiagnosticPhases(
51+
limit = 8,
52+
options?: { completedAfter?: number },
53+
): DiagnosticPhaseSnapshot[] {
5154
const resolved = resolveRecentPhaseLimit(limit);
5255
if (resolved === null) {
5356
return [];
5457
}
55-
return recentPhases.slice(-resolved).map((phase) => Object.assign({}, phase));
58+
const completedAfter = options?.completedAfter;
59+
const eligiblePhases =
60+
completedAfter === undefined
61+
? recentPhases
62+
: recentPhases.filter(
63+
(phase) => phase.endedAt !== undefined && phase.endedAt >= completedAfter,
64+
);
65+
return eligiblePhases.slice(-resolved).map((phase) => Object.assign({}, phase));
5666
}
5767

5868
/** Records a completed phase in memory and emits it when diagnostics are enabled. */

‎src/logging/diagnostic.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2408,6 +2408,52 @@ describe("stuck session diagnostics threshold", () => {
24082408
).toBe(true);
24092409
});
24102410

2411+
it("attributes only phases completed during the measured liveness interval", async () => {
2412+
const warnSpy = vi.spyOn(diagnosticLogger, "warn").mockImplementation(() => undefined);
2413+
const events: DiagnosticEventPayload[] = [];
2414+
const unsubscribe = onDiagnosticEvent((event) => events.push(event));
2415+
2416+
await withDiagnosticPhase("stale.phase", () => undefined);
2417+
vi.advanceTimersByTime(60_000);
2418+
await withDiagnosticPhase("recent.phase", () => undefined);
2419+
2420+
try {
2421+
startDiagnosticHeartbeat(
2422+
{
2423+
diagnostics: {
2424+
enabled: true,
2425+
},
2426+
},
2427+
{
2428+
emitMemorySample: createEmitMemorySampleMock(),
2429+
sampleLiveness: () => ({
2430+
reasons: ["event_loop_delay"],
2431+
intervalMs: 30_000,
2432+
eventLoopDelayP99Ms: 1_500,
2433+
eventLoopDelayMaxMs: 2_000,
2434+
}),
2435+
},
2436+
);
2437+
2438+
logMessageQueued({ sessionId: "s1", sessionKey: "main", source: "test" });
2439+
vi.advanceTimersByTime(30_000);
2440+
} finally {
2441+
unsubscribe();
2442+
}
2443+
2444+
expectLoggerMessageContaining(warnSpy, "recentPhases=recent.phase:");
2445+
expectNoLoggerMessageContaining(warnSpy, "stale.phase");
2446+
const warning = requireRecord(
2447+
events.findLast((event) => event.type === "diagnostic.liveness.warning"),
2448+
"liveness warning event",
2449+
);
2450+
expect(warning.recentPhases).toEqual([
2451+
expect.objectContaining({
2452+
name: "recent.phase",
2453+
}),
2454+
]);
2455+
});
2456+
24112457
it("keeps transient event-loop max spikes debug-only when only background work is active", () => {
24122458
const warnSpy = vi.spyOn(diagnosticLogger, "warn").mockImplementation(() => undefined);
24132459

‎src/logging/diagnostic.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -421,9 +421,14 @@ function shouldEmitDiagnosticLivenessWarning(now: number, work: DiagnosticWorkSn
421421
function emitDiagnosticLivenessWarning(
422422
sample: DiagnosticLivenessSample,
423423
work: DiagnosticWorkSnapshot,
424+
now: number,
424425
): void {
425426
const phase = getCurrentDiagnosticPhase();
426-
const recentPhases = getRecentDiagnosticPhases(6);
427+
// Attribute only phases completed during this measured liveness interval.
428+
// The retained ring is capacity-bounded history, not a temporal recency signal.
429+
const recentPhases = getRecentDiagnosticPhases(6, {
430+
completedAfter: now - Math.max(0, sample.intervalMs),
431+
});
427432
const recentPhaseSummary = formatRecentDiagnosticPhases(recentPhases);
428433
const workLabelSummary = formatDiagnosticWorkLabels(work);
429434
const message = `liveness warning: reasons=${sample.reasons.join(",")} interval=${Math.round(
@@ -1269,7 +1274,7 @@ export function startDiagnosticHeartbeat(
12691274
}
12701275

12711276
if (shouldEmitLivenessReport && livenessSample) {
1272-
emitDiagnosticLivenessWarning(livenessSample, work);
1277+
emitDiagnosticLivenessWarning(livenessSample, work, now);
12731278
}
12741279

12751280
diag.debug(

0 commit comments

Comments
 (0)