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
89 changes: 86 additions & 3 deletions pm-stack/exporters/src/watchdog-escalation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
// (source, failure class) while the incident is open — the dedupe
// record lives on the incident itself (Incident.escalation), so a
// second escalation tick for the same pair creates neither;
// - dedupe is not silence (#10630): once a confirmed hand-off has been
// unresolved for ESCALATION_REPEAT_AFTER_MS, the plan updates the
// EXISTING escalation — one comment on the incident issue — and
// repeats once per window while the source stays down, so a repair
// task nobody picks up cannot go quiet past the second threshold;
// - the queue task carries the full context packet (below), so a
// browser-enabled agent can start from the packet alone;
// - on producer success, the recovery plan comments the resolution on
Expand Down Expand Up @@ -41,6 +46,13 @@ import type { EscalationRecord, FailureClass, SourceHealth } from "./watchdog-st
/** How long an ordinary escalation stays quiet before it surfaces. */
export const ESCALATION_NEEDS_DREW_AFTER_MS = 24 * 60 * 60_000;

/** How long a confirmed hand-off may sit unresolved before the
* escalation re-fires on its existing incident issue (#10630: the
* second threshold). It matches the surfacing threshold: the tick
* that earns the NEEDS DREW line also posts the re-escalation
* update, and each further window earns one more. */
export const ESCALATION_REPEAT_AFTER_MS = ESCALATION_NEEDS_DREW_AFTER_MS;

/** Per-source wiring the entry point supplies from the adapter. */
export interface EscalationContext {
/** Repo that owns the adapter, e.g. "developing-today-forks/openchamber". */
Expand Down Expand Up @@ -159,16 +171,37 @@ function issueBody(health: SourceHealth, packet: EscalationPacket): string {
].join("\n");
}

function reEscalationBody(health: SourceHealth, rec: EscalationRecord, nowMs: number): string {
const anchor = Date.parse(rec.lastReEscalatedAt ?? rec.since);
const hours = Math.floor((nowMs - anchor) / 3_600_000);
return [
`Still unresolved: source \`${health.source}\` is still failing (${health.currentClass ?? "unknown"}) ${hours}h after the last escalation update, and no fresh read has landed.`,
"",
`- consecutive failures: ${health.consecutiveFailures}`,
`- last detail: ${health.lastDetail || "(none)"}`,
`- repair task: ${rec.queueTaskId ?? "(unrecorded)"} (dedupe \`${escalationDedupeKey(health.source, rec.class)}\`)`,
"",
"The watchdog re-escalates on the existing incident instead of opening a new one (#10630); the repair task above remains the work item. Recovery is recorded here when a fresh read lands; disposition stays with the authorized authority.",
].join("\n");
}

/**
* Plan the rung-4 effects for a tick whose health record carries an
* escalating incident. Pure: returns the actions to run, or an empty
* list when the (source, class) pair is already escalated (dedupe) or
* the incident is not in an escalating state.
* the incident is not in an escalating state. One exception to the
* empty dedupe plan (#10630): when `nowMs` is supplied and the
* confirmed hand-off has been unresolved for
* ESCALATION_REPEAT_AFTER_MS since it (last re-)fired, the plan is a
* single re-escalation comment on the existing incident issue,
* flagged `reEscalated` so the caller can stamp it via
* recordReEscalation once the comment confirms.
*/
export function planEscalation(
health: SourceHealth,
ctx: EscalationContext,
): { actions: EscalationAction[]; deduped: boolean } {
nowMs?: number,
): { actions: EscalationAction[]; deduped: boolean; reEscalated?: boolean } {
const incident = health.incident;
if (!incident || incident.surfacing !== "escalate" || incident.humanBlocked) {
return { actions: [], deduped: false };
Expand All @@ -194,7 +227,30 @@ export function planEscalation(
const actions: EscalationAction[] = [];
if (forClass.issueNumber === null) actions.push(openIssue);
if (forClass.queueTaskId === null) actions.push({ type: "enqueue_task", packet });
return { actions, deduped: actions.length === 0 };
if (actions.length > 0) return { actions, deduped: false };
// Fully confirmed hand-off: dedupe holds — unless the escalation
// has been unresolved past the repeat window (#10630). Then the
// plan updates the existing escalation with one comment on its
// incident issue; no new issue, no new task. The window is
// measured from the last re-escalation, else from the hand-off.
if (nowMs !== undefined && forClass.issueNumber !== null) {
const anchor = Date.parse(forClass.lastReEscalatedAt ?? forClass.since);
if (Number.isFinite(anchor) && nowMs - anchor >= ESCALATION_REPEAT_AFTER_MS) {
return {
actions: [
{
type: "comment_issue",
repo: forClass.issueRepo,
issueNumber: forClass.issueNumber,
body: reEscalationBody(health, forClass, nowMs),
},
],
deduped: false,
reEscalated: true,
};
}
}
return { actions: [], deduped: true };
}
return {
deduped: false,
Expand Down Expand Up @@ -342,6 +398,33 @@ export function recordEscalation(
};
}

/**
* Stamp a confirmed re-escalation (#10630) onto the hand-off record
* for the health record's current failure class — the current record,
* or the displaced one in `previous` when the class changed away and
* back. The next repeat window is measured from this stamp, so a
* re-escalation fires once per window, never once per tick. Pure.
*/
export function recordReEscalation(health: SourceHealth, at: string): SourceHealth {
const incident = health.incident;
if (!incident?.escalation) return health;
const esc = incident.escalation;
if (esc.class === health.currentClass) {
return { ...health, incident: { ...incident, escalation: { ...esc, lastReEscalatedAt: at } } };
}
if (!esc.previous) return health;
let stamped = false;
const previous = esc.previous.map((rec) => {
if (!stamped && rec.class === health.currentClass) {
stamped = true;
return { ...rec, lastReEscalatedAt: at };
}
return rec;
});
if (!stamped) return health;
return { ...health, incident: { ...incident, escalation: { ...esc, previous } } };
}

/**
* The NEEDS DREW line for this source, or null while it should stay
* quiet. Human-blocked surfaces the same tick it is marked; an ordinary
Expand Down
6 changes: 6 additions & 0 deletions pm-stack/exporters/src/watchdog-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ export interface EscalationRecord {
class: FailureClass;
/** When the escalation effects ran. */
since: string;
/** When the latest re-escalation update was posted to the incident
* issue (#10630), or absent if the hand-off has not re-fired yet.
* The repeat window is measured from this stamp when present, else
* from `since`. */
lastReEscalatedAt?: string;
/** Fleet queue task id, or null if the enqueue has not confirmed. */
queueTaskId: string | null;
/** Repo owning the adapter (and therefore the incident issue). */
Expand Down Expand Up @@ -427,6 +432,7 @@ export function coerceHealth(source: string, raw: unknown): SourceHealth {
queueTaskId: typeof e.queueTaskId === "string" ? e.queueTaskId : null,
issueRepo: e.issueRepo,
issueNumber: typeof e.issueNumber === "number" && Number.isFinite(e.issueNumber) ? e.issueNumber : null,
...(typeof e.lastReEscalatedAt === "string" ? { lastReEscalatedAt: e.lastReEscalatedAt } : {}),
}
: null;
};
Expand Down
4 changes: 3 additions & 1 deletion pm-stack/exporters/src/watchdog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
planEscalation,
planRecovery,
recordEscalation,
recordReEscalation,
surfacingLine,
type EscalationContext,
type EscalationEffectors,
Expand Down Expand Up @@ -612,12 +613,13 @@ export async function runTick(
adapterRef: `adapters/${adapter.name}.json`,
historyRef: opts.historyFile,
};
const plan = planEscalation(health, ctx);
const plan = planEscalation(health, ctx, now.getTime());
if (plan.actions.length > 0) {
if (opts.liveEscalation) {
try {
const refs = await applyEscalationActions(plan.actions, opts.effects.escalation);
health = recordEscalation(health, ctx, refs, at);
if (plan.reEscalated) health = recordReEscalation(health, at);
} catch (e) {
if (e instanceof EscalationPartialError) {
health = recordEscalation(health, ctx, e.refs, at);
Expand Down
85 changes: 85 additions & 0 deletions pm-stack/exporters/test/watchdog-escalation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import {
buildQueueTaskWrapper,
EscalationPartialError,
ESCALATION_NEEDS_DREW_AFTER_MS,
ESCALATION_REPEAT_AFTER_MS,
planEscalation,
planRecovery,
recordEscalation,
recordReEscalation,
surfacingLine,
type EscalationContext,
type EscalationEffectors,
Expand Down Expand Up @@ -319,3 +321,86 @@ describe("Codex findings on PR #8357 (class change, partial progress, surfacing
expect(back.incident?.escalation?.previous?.[0].queueTaskId).toBe("task-a");
});
});
describe("re-escalation at the second threshold (#10630 acceptance 3)", () => {
// T0 + ESCALATION_REPEAT_AFTER_MS (24h): the second threshold.
const T1 = "2026-11-11T00:00:00Z";

test("a confirmed hand-off still dedupes before the repeat window", () => {
const recorded = recordEscalation(escalatingHealth(), CTX, { queueTaskId: "task-4242", issueNumber: 777 }, T0);
const plan = planEscalation(recorded, CTX, Date.parse(T0) + ESCALATION_REPEAT_AFTER_MS - 1);
expect(plan.deduped).toBe(true);
expect(plan.actions).toEqual([]);
});

test("at the second threshold the plan re-fires as ONE comment on the existing issue — no new issue, no new task", async () => {
const recorded = recordEscalation(escalatingHealth(), CTX, { queueTaskId: "task-4242", issueNumber: 777 }, T0);
const plan = planEscalation(recorded, CTX, Date.parse(T1));
expect(plan.deduped).toBe(false);
expect(plan.reEscalated).toBe(true);
expect(plan.actions).toHaveLength(1);
const action = plan.actions[0];
expect(action.type).toBe("comment_issue");
if (action.type === "comment_issue") {
expect(action.repo).toBe(CTX.issueRepo);
expect(action.issueNumber).toBe(777);
expect(action.body).toContain("Still unresolved");
expect(action.body).toContain("task-4242");
expect(action.body).toContain("24h");
}
const { calls, effectors } = countingEffectors();
await applyEscalationActions(plan.actions, effectors);
expect(calls).toEqual(["comment"]);
});

test("the stamp restarts the window: one re-escalation per window, never one per tick", () => {
const recorded = recordEscalation(escalatingHealth(), CTX, { queueTaskId: "task-4242", issueNumber: 777 }, T0);
const stamped = recordReEscalation(recorded, T1);
expect(stamped.incident?.escalation?.lastReEscalatedAt).toBe(T1);
// A tick later in the same window dedupes again...
expect(planEscalation(stamped, CTX, Date.parse(T1) + 60_000).actions).toEqual([]);
expect(planEscalation(stamped, CTX, Date.parse(T1) + ESCALATION_REPEAT_AFTER_MS - 1).deduped).toBe(true);
// ...and the next window re-fires again — silence stays impossible.
const next = planEscalation(stamped, CTX, Date.parse(T1) + ESCALATION_REPEAT_AFTER_MS);
expect(next.reEscalated).toBe(true);
expect(next.actions.map((a) => a.type)).toEqual(["comment_issue"]);
});

test("without a clock the planner keeps the old dedupe behavior", () => {
const recorded = recordEscalation(escalatingHealth(), CTX, { queueTaskId: "task-4242", issueNumber: 777 }, T0);
const plan = planEscalation(recorded, CTX);
expect(plan.deduped).toBe(true);
expect(plan.actions).toEqual([]);
});

test("a partial hand-off still plans only its missing creations, even past the window", () => {
const partial = recordEscalation(escalatingHealth(), CTX, { queueTaskId: null, issueNumber: 777 }, T0);
const plan = planEscalation(partial, CTX, Date.parse(T1));
expect(plan.reEscalated).toBeUndefined();
expect(plan.actions.map((a) => a.type)).toEqual(["enqueue_task"]);
});

test("the stamp lands on the displaced record when the class changed away and back", () => {
const first = recordEscalation(escalatingHealth(), CTX, { queueTaskId: "task-a", issueNumber: 111 }, T0);
const changed: SourceHealth = { ...first, currentClass: "endpoint-changed" };
const second = recordEscalation(changed, CTX, { queueTaskId: "task-b", issueNumber: 222 }, T0);
const backAgain: SourceHealth = { ...second, currentClass: "session-expired" };
const plan = planEscalation(backAgain, CTX, Date.parse(T1));
expect(plan.reEscalated).toBe(true);
expect(plan.actions[0]).toMatchObject({ type: "comment_issue", issueNumber: 111 });
const stamped = recordReEscalation(backAgain, T1);
expect(stamped.incident?.escalation?.previous?.[0].lastReEscalatedAt).toBe(T1);
expect(stamped.incident?.escalation?.lastReEscalatedAt).toBeUndefined();
});

test("coerceHealth round-trips the re-escalation stamp and drops a malformed one", () => {
const recorded = recordEscalation(escalatingHealth(), CTX, { queueTaskId: "task-4242", issueNumber: 777 }, T0);
const stamped = recordReEscalation(recorded, T1);
const back = coerceHealth("mistral", JSON.parse(JSON.stringify(stamped)));
expect(back.incident?.escalation?.lastReEscalatedAt).toBe(T1);

const corrupt = JSON.parse(JSON.stringify(stamped));
corrupt.incident.escalation.lastReEscalatedAt = 42;
const dropped = coerceHealth("mistral", corrupt);
expect(dropped.incident?.escalation?.lastReEscalatedAt).toBeUndefined();
});
});