Skip to content

Commit 2c1a8d0

Browse files
committed
fix(cron): deliver failure alerts after persistence
Fixes #118187. Failure-alert cooldown state now commits with the run outcome before any alert delivery, preventing premature or duplicate notifications after a failed cron store write. Release note: cron failure alerts no longer fire for rolled-back run outcomes.
1 parent f4766de commit 2c1a8d0

17 files changed

Lines changed: 372 additions & 112 deletions

‎src/cron/service/auto-disable.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,10 @@ import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
33
import { parseAgentSessionKey } from "../../routing/session-key.js";
44
import type { CronJob, CronJobState } from "../types.js";
55
import { normalizeOptionalAgentId } from "./normalize.js";
6-
import type { CronServiceState } from "./state.js";
6+
import type { CronServiceState, DeferredCronNotifications } from "./state.js";
77

88
type CronAutoDisableReason = NonNullable<CronJobState["autoDisabled"]>["reason"];
99

10-
export type DeferredAutoDisableNotifications = Array<() => void>;
11-
1210
/**
1311
* Run failures get more room than schedule errors (10 vs. 3) because provider
1412
* and network errors are often transient, and restart-interrupted runs count too.
@@ -27,7 +25,7 @@ export function autoDisableCronJob(params: {
2725
atMs: number;
2826
consecutiveErrors: number;
2927
error: unknown;
30-
deferredNotifications?: DeferredAutoDisableNotifications;
28+
deferredNotifications?: DeferredCronNotifications;
3129
}): boolean {
3230
const { state, job } = params;
3331
if (!job.enabled || job.state.autoDisabled) {
@@ -91,7 +89,7 @@ export function maybeAutoDisableCronJobAfterRunFailure(params: {
9189
job: CronJob;
9290
atMs: number;
9391
error: unknown;
94-
deferredNotifications?: DeferredAutoDisableNotifications;
92+
deferredNotifications?: DeferredCronNotifications;
9593
}): boolean {
9694
const consecutiveErrors = params.job.state.consecutiveErrors ?? 0;
9795
if (

‎src/cron/service/failure-alerts.account-routing.test.ts‎

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import {
66
} from "../../test-utils/channel-plugins.js";
77
import type { CronJob } from "../types.js";
88
import { resolveFailureAlert } from "./failure-alerts.js";
9-
import { createCronServiceState } from "./state.js";
9+
import { createCronServiceState, type DeferredCronNotifications } from "./state.js";
1010
import { applyJobResult } from "./timer.js";
1111

1212
describe("cron failure alert account routing", () => {
@@ -278,16 +278,24 @@ describe("cron failure alert account routing", () => {
278278
delivery: { mode: "announce", channel: "telegram", to: "telegram:19098680" },
279279
state: {},
280280
};
281+
const deferredNotifications: DeferredCronNotifications = [];
281282

282-
applyJobResult(state, job, {
283-
status: "error",
284-
error: "provider unavailable",
285-
startedAt: runAtMs,
286-
endedAt,
287-
});
283+
applyJobResult(
284+
state,
285+
job,
286+
{
287+
status: "error",
288+
error: "provider unavailable",
289+
startedAt: runAtMs,
290+
endedAt,
291+
},
292+
{ deferredNotifications },
293+
);
288294

289-
expect(sendCronFailureAlert).toHaveBeenCalledWith(expect.objectContaining({ runAtMs }));
290295
expect(job.state.lastFailureAlertAtMs).toBe(endedAt);
296+
expect(sendCronFailureAlert).not.toHaveBeenCalled();
297+
deferredNotifications[0]?.();
298+
expect(sendCronFailureAlert).toHaveBeenCalledWith(expect.objectContaining({ runAtMs }));
291299
});
292300

293301
it.each([
@@ -334,14 +342,22 @@ describe("cron failure alert account routing", () => {
334342
...(failureAlert ? { failureAlert } : {}),
335343
state: {},
336344
};
345+
const deferredNotifications: DeferredCronNotifications = [];
337346

338-
applyJobResult(state, job, {
339-
status: "error",
340-
error: "provider unavailable",
341-
startedAt: 1,
342-
endedAt: 2,
343-
});
347+
applyJobResult(
348+
state,
349+
job,
350+
{
351+
status: "error",
352+
error: "provider unavailable",
353+
startedAt: 1,
354+
endedAt: 2,
355+
},
356+
{ deferredNotifications },
357+
);
344358

359+
expect(sendCronFailureAlert).not.toHaveBeenCalled();
360+
deferredNotifications[0]?.();
345361
expect(sendCronFailureAlert).toHaveBeenCalledWith(
346362
expect.objectContaining({
347363
channel: "expectedChannel" in testCase ? testCase.expectedChannel : "telegram",
Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
// Failure alerts must describe only cron outcomes that survived durable persistence.
2+
import { describe, expect, it, vi } from "vitest";
3+
import {
4+
createDueIsolatedJob,
5+
noopLogger,
6+
setupCronRegressionFixtures,
7+
} from "../../../test/helpers/cron/service-regression-fixtures.js";
8+
import { markCronJobActive } from "../active-jobs.js";
9+
import * as cronStoreModule from "../store.js";
10+
import { loadCronStore, saveCronStore } from "../store.js";
11+
import type { CronJob, CronRunStatus } from "../types.js";
12+
import { createCronServiceState } from "./state.js";
13+
import { finalizeCompletedCronRunOutcomes } from "./timer-outcome-finalization.js";
14+
15+
const fixtures = setupCronRegressionFixtures({
16+
prefix: "cron-failure-alert-persistence-",
17+
});
18+
19+
type SendCronFailureAlert = NonNullable<
20+
Parameters<typeof createCronServiceState>[0]["sendCronFailureAlert"]
21+
>;
22+
23+
function createAlertJob(params: { id: string; dueAt: number; includeSkipped?: boolean }): CronJob {
24+
const job = createDueIsolatedJob({
25+
id: params.id,
26+
nowMs: params.dueAt,
27+
nextRunAtMs: params.dueAt,
28+
});
29+
job.schedule = { kind: "every", everyMs: 60_000, anchorMs: params.dueAt - 60_000 };
30+
job.failureAlert = {
31+
after: 1,
32+
cooldownMs: 60_000,
33+
...(params.includeSkipped ? { includeSkipped: true } : {}),
34+
};
35+
job.state.runningAtMs = params.dueAt;
36+
return job;
37+
}
38+
39+
function createAlertState(params: {
40+
storePath: string;
41+
nowMs: () => number;
42+
sendCronFailureAlert: SendCronFailureAlert;
43+
}) {
44+
return createCronServiceState({
45+
cronEnabled: true,
46+
storePath: params.storePath,
47+
log: noopLogger,
48+
nowMs: params.nowMs,
49+
enqueueSystemEvent: vi.fn(),
50+
requestHeartbeat: vi.fn(),
51+
sendCronFailureAlert: params.sendCronFailureAlert,
52+
runIsolatedAgentJob: vi.fn(),
53+
});
54+
}
55+
56+
async function finalizeAlertOutcome(params: {
57+
state: ReturnType<typeof createCronServiceState>;
58+
job: CronJob;
59+
status: Extract<CronRunStatus, "error" | "skipped">;
60+
error: string;
61+
startedAt: number;
62+
endedAt: number;
63+
}) {
64+
await finalizeCompletedCronRunOutcomes(params.state, [
65+
{
66+
jobId: params.job.id,
67+
job: structuredClone(params.job),
68+
activeJobMarker: markCronJobActive(params.job.id),
69+
status: params.status,
70+
error: params.error,
71+
startedAt: params.startedAt,
72+
endedAt: params.endedAt,
73+
},
74+
]);
75+
}
76+
77+
describe("cron failure alert persistence", () => {
78+
it.each([
79+
{ status: "error", includeSkipped: false },
80+
{ status: "skipped", includeSkipped: true },
81+
] as const)("delivers a $status alert once after the outcome is durable", async (testCase) => {
82+
const store = fixtures.makeStorePath();
83+
const dueAt = Date.parse("2026-08-01T14:50:00.000Z");
84+
const endedAt = dueAt + 10;
85+
const job = createAlertJob({
86+
id: `${testCase.status}-alert-after-persist`,
87+
dueAt,
88+
includeSkipped: testCase.includeSkipped,
89+
});
90+
await saveCronStore(store.storePath, { version: 1, jobs: [job] });
91+
92+
const order: string[] = [];
93+
const sendCronFailureAlert = vi.fn(async () => {
94+
order.push("alert");
95+
});
96+
const state = createAlertState({
97+
storePath: store.storePath,
98+
nowMs: () => endedAt,
99+
sendCronFailureAlert,
100+
});
101+
const save = cronStoreModule.saveCronJobsStore;
102+
const saveSpy = vi
103+
.spyOn(cronStoreModule, "saveCronJobsStore")
104+
.mockImplementation(async (...args) => {
105+
if (args[1].jobs[0]?.state.lastFailureAlertAtMs === endedAt) {
106+
expect(sendCronFailureAlert).not.toHaveBeenCalled();
107+
await save(...args);
108+
order.push("persist");
109+
return;
110+
}
111+
await save(...args);
112+
});
113+
114+
try {
115+
await finalizeAlertOutcome({
116+
state,
117+
job,
118+
status: testCase.status,
119+
error: testCase.status === "error" ? "provider unavailable" : "disabled",
120+
startedAt: dueAt,
121+
endedAt,
122+
});
123+
124+
expect(order).toEqual(["persist", "alert"]);
125+
expect(sendCronFailureAlert).toHaveBeenCalledOnce();
126+
expect((await loadCronStore(store.storePath)).jobs[0]?.state.lastFailureAlertAtMs).toBe(
127+
endedAt,
128+
);
129+
} finally {
130+
saveSpy.mockRestore();
131+
}
132+
});
133+
134+
it("rolls back the cooldown without delivery when persistence fails", async () => {
135+
const store = fixtures.makeStorePath();
136+
const dueAt = Date.parse("2026-08-01T14:55:00.000Z");
137+
const job = createAlertJob({ id: "failure-alert-persist-rollback", dueAt });
138+
await saveCronStore(store.storePath, { version: 1, jobs: [job] });
139+
140+
const sendCronFailureAlert = vi.fn(async () => undefined);
141+
const state = createAlertState({
142+
storePath: store.storePath,
143+
nowMs: () => dueAt + 10,
144+
sendCronFailureAlert,
145+
});
146+
const saveSpy = vi
147+
.spyOn(cronStoreModule, "saveCronJobsStore")
148+
.mockRejectedValueOnce(new Error("terminal write failed"));
149+
150+
try {
151+
await expect(
152+
finalizeAlertOutcome({
153+
state,
154+
job,
155+
status: "error",
156+
error: "provider unavailable",
157+
startedAt: dueAt,
158+
endedAt: dueAt + 10,
159+
}),
160+
).rejects.toThrow("terminal write failed");
161+
162+
expect(sendCronFailureAlert).not.toHaveBeenCalled();
163+
expect(state.store?.jobs[0]?.state.lastFailureAlertAtMs).toBeUndefined();
164+
expect(
165+
(await loadCronStore(store.storePath)).jobs[0]?.state.lastFailureAlertAtMs,
166+
).toBeUndefined();
167+
} finally {
168+
saveSpy.mockRestore();
169+
}
170+
});
171+
172+
it("persists the cooldown atomically and suppresses a second alert", async () => {
173+
const store = fixtures.makeStorePath();
174+
const dueAt = Date.parse("2026-08-01T14:58:00.000Z");
175+
const firstAlertAt = dueAt + 10;
176+
const job = createAlertJob({ id: "failure-alert-cooldown-persisted", dueAt });
177+
await saveCronStore(store.storePath, { version: 1, jobs: [job] });
178+
179+
let now = firstAlertAt;
180+
const sendCronFailureAlert = vi.fn(async () => undefined);
181+
const state = createAlertState({
182+
storePath: store.storePath,
183+
nowMs: () => now,
184+
sendCronFailureAlert,
185+
});
186+
187+
await finalizeAlertOutcome({
188+
state,
189+
job,
190+
status: "error",
191+
error: "first failure",
192+
startedAt: dueAt,
193+
endedAt: firstAlertAt,
194+
});
195+
expect(sendCronFailureAlert).toHaveBeenCalledOnce();
196+
expect((await loadCronStore(store.storePath)).jobs[0]?.state.lastFailureAlertAtMs).toBe(
197+
firstAlertAt,
198+
);
199+
200+
now += 30_000;
201+
const currentJob = state.store?.jobs[0];
202+
if (!currentJob) {
203+
throw new Error("expected persisted cron job");
204+
}
205+
await finalizeAlertOutcome({
206+
state,
207+
job: currentJob,
208+
status: "error",
209+
error: "second failure",
210+
startedAt: now,
211+
endedAt: now + 10,
212+
});
213+
214+
expect(sendCronFailureAlert).toHaveBeenCalledOnce();
215+
expect((await loadCronStore(store.storePath)).jobs[0]).toMatchObject({
216+
state: { consecutiveErrors: 2, lastFailureAlertAtMs: firstAlertAt },
217+
});
218+
});
219+
});

‎src/cron/service/failure-alerts.ts‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
stripTargetProviderPrefix,
99
} from "../../infra/outbound/channel-target-prefix.js";
1010
import type { CronFailureNotificationDelivery, CronJob, CronMessageChannel } from "../types.js";
11-
import type { CronServiceState } from "./state.js";
11+
import type { CronServiceState, DeferredCronNotifications } from "./state.js";
1212

1313
const DEFAULT_FAILURE_ALERT_AFTER = 2;
1414
const DEFAULT_FAILURE_ALERT_COOLDOWN_MS = 60 * 60_000; // 1 hour
@@ -228,9 +228,11 @@ export function maybeEmitFailureAlert(
228228
consecutiveCount: number;
229229
delivery?: "emit" | "record-only";
230230
occurredAtMs?: number;
231+
deferredNotifications?: DeferredCronNotifications;
231232
},
232233
) {
233-
if (!params.alertConfig || params.consecutiveCount < params.alertConfig.after) {
234+
const alertConfig = params.alertConfig;
235+
if (!alertConfig || params.consecutiveCount < alertConfig.after) {
234236
return;
235237
}
236238
if (
@@ -252,24 +254,33 @@ export function maybeEmitFailureAlert(
252254
// Cooldown is stored on job state so process restarts and service reloads do
253255
// not spam operators with repeated alerts for the same failing job.
254256
const inCooldown =
255-
typeof lastAlert === "number" && now - lastAlert < Math.max(0, params.alertConfig.cooldownMs);
257+
typeof lastAlert === "number" && now - lastAlert < Math.max(0, alertConfig.cooldownMs);
256258
if (inCooldown) {
257259
return;
258260
}
259-
if (params.delivery !== "record-only") {
261+
params.job.state.lastFailureAlertAtMs = now;
262+
if (params.delivery === "record-only") {
263+
return;
264+
}
265+
266+
const job = structuredClone(params.job);
267+
const notify = () =>
260268
emitFailureAlert(state, {
261-
job: params.job,
269+
job,
262270
error: params.error,
263271
errorReason: params.errorReason,
264272
runAtMs: params.runAtMs,
265273
consecutiveErrors: params.consecutiveCount,
266-
channel: params.alertConfig.channel,
267-
to: params.alertConfig.to,
268-
mode: params.alertConfig.mode,
269-
accountId: params.alertConfig.accountId,
270-
threadId: params.alertConfig.threadId,
274+
channel: alertConfig.channel,
275+
to: alertConfig.to,
276+
mode: alertConfig.mode,
277+
accountId: alertConfig.accountId,
278+
threadId: alertConfig.threadId,
271279
status: params.status,
272280
});
281+
if (params.deferredNotifications) {
282+
params.deferredNotifications.push(notify);
283+
} else {
284+
notify();
273285
}
274-
params.job.state.lastFailureAlertAtMs = now;
275286
}

0 commit comments

Comments
 (0)