Skip to content

Commit 44a5c40

Browse files
authored
fix(cron): on-exit watcher retries transient failures instead of silently dropping the watch (#120023)
* fix(cron): retry on-exit watcher spawn/wait failures with backoff A transient supervisor failure while arming or waiting on an on-exit watch previously dropped the watch with only a log line: the job would never fire and nothing recorded why. Failures now persist lastError/consecutiveErrors on job state via the gateway cron service and re-arm with bounded backoff (1s/5s/30s/5m); cancel clears any pending retry timer. * chore: re-fire CI * fix(cron): guard watcher-state writes against replaced on-exit jobs ClawSweeper P1: an old watcher's failure write could land on a job that was edited or converted to a different schedule, pushing the replacement into failure backoff or auto-disable. Watcher-state persistence now uses the same identity precondition as persistCompletion (enabled, on-exit, updatedAtMs match) and treats a mismatch as a no-op.
1 parent 4fb43b5 commit 44a5c40

3 files changed

Lines changed: 144 additions & 17 deletions

File tree

‎src/gateway/cron-exit-watchers.test.ts‎

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { setTimeout as delay } from "node:timers/promises";
12
import { expectDefined } from "@openclaw/normalization-core";
23
import { afterEach, describe, expect, it, vi } from "vitest";
34
import type { CronJob } from "../cron/types.js";
@@ -202,15 +203,18 @@ describe("createCronExitWatchers", () => {
202203
expect(w.activeJobIds()).toEqual(["job-a"]);
203204
});
204205

205-
it("releases the slot without firing when run.wait() rejects (fail closed on unknown outcome)", async () => {
206+
it("retries with backoff without firing when run.wait() rejects (fail closed on unknown outcome)", async () => {
206207
const { supervisor, runs } = makeFakeSupervisor();
207208
const persistCompletion = vi.fn(async () => {});
208209
const fireOnExit = vi.fn(async () => {});
210+
const updateWatcherState = vi.fn(async () => {});
209211
const w = createCronExitWatchers({
210212
getProcessSupervisor: () => supervisor as never,
211213
persistCompletion,
212214
fireOnExit,
215+
updateWatcherState,
213216
logger: noopLogger,
217+
retryBackoffMs: [0],
214218
});
215219

216220
w.reconcile([onExitJob("job-a")]);
@@ -227,12 +231,56 @@ describe("createCronExitWatchers", () => {
227231
// Fail closed: no fire, no persisted terminal state on an unknown outcome.
228232
expect(fireOnExit).not.toHaveBeenCalled();
229233
expect(persistCompletion).not.toHaveBeenCalled();
230-
// Slot released so a subsequent reconcile can re-arm the job.
231-
expect(w.activeJobIds()).toEqual([]);
234+
// The failure is recorded on job state, and the slot stays reserved as the
235+
// retry placeholder instead of silently dropping the watch.
236+
expect(updateWatcherState).toHaveBeenCalledWith(
237+
expect.objectContaining({ id: "job-a" }),
238+
expect.objectContaining({ consecutiveErrors: 1 }),
239+
);
240+
expect(w.activeJobIds()).toEqual(["job-a"]);
241+
// The backoff timer re-arms without an external reconcile.
242+
await delay(5);
243+
await flush();
244+
expect(supervisor.spawn).toHaveBeenCalledTimes(2);
245+
expect(w.activeJobIds()).toEqual(["job-a"]);
246+
});
247+
248+
it("retries with backoff when spawn fails and stops retrying once cancelled", async () => {
249+
const { supervisor, runs } = makeFakeSupervisor();
250+
supervisor.spawn.mockRejectedValueOnce(new Error("spawn blew up"));
251+
const updateWatcherState = vi.fn(async () => {});
252+
const w = createCronExitWatchers({
253+
getProcessSupervisor: () => supervisor as never,
254+
persistCompletion: vi.fn(async () => {}),
255+
fireOnExit: vi.fn(async () => {}),
256+
updateWatcherState,
257+
logger: noopLogger,
258+
retryBackoffMs: [0],
259+
});
260+
232261
w.reconcile([onExitJob("job-a")]);
233262
await flush();
263+
expect(updateWatcherState).toHaveBeenCalledWith(
264+
expect.objectContaining({ id: "job-a" }),
265+
expect.objectContaining({ consecutiveErrors: 1 }),
266+
);
267+
// Backoff re-arm succeeds on the second spawn.
268+
await delay(5);
269+
await flush();
234270
expect(supervisor.spawn).toHaveBeenCalledTimes(2);
235271
expect(w.activeJobIds()).toEqual(["job-a"]);
272+
273+
// Cancelling clears any pending retry timer; once the cancelled child
274+
// settles, the slot is released and no further spawns happen.
275+
w.cancel("job-a");
276+
expectDefined(runs[0], "runs[0] test invariant").deferred.resolve({
277+
exitCode: null,
278+
reason: "cancelled",
279+
});
280+
await delay(5);
281+
await flush();
282+
expect(supervisor.spawn).toHaveBeenCalledTimes(2);
283+
expect(w.activeJobIds()).toEqual([]);
236284
});
237285

238286
it("replaces the watcher when the watched command changes", async () => {

‎src/gateway/cron-exit-watchers.ts‎

Lines changed: 73 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { resolveExitWatchShell } from "./cron-exit-watch-shell.js";
1010
* watch ends and the job fires like any other exit.
1111
*/
1212
const ON_EXIT_WATCH_TIMEOUT_MS = 24 * 60 * 60 * 1000;
13+
const ON_EXIT_WATCH_RETRY_BACKOFF_MS = [1_000, 5_000, 30_000, 5 * 60_000] as const;
1314

1415
type Logger = {
1516
info: (obj: unknown, msg?: string) => void;
@@ -48,10 +49,19 @@ export function createCronExitWatchers(params: {
4849
getProcessSupervisor: () => ProcessSupervisor;
4950
persistCompletion: (job: OnExitCronJob) => Promise<(() => void) | void>;
5051
fireOnExit: (job: CronJob, exit: CronExitResult) => void | Promise<void>;
52+
updateWatcherState?: (
53+
job: OnExitCronJob,
54+
patch: Pick<CronJob["state"], "lastError" | "consecutiveErrors">,
55+
) => Promise<CronJob | void>;
5156
logger: Logger;
5257
shell?: { command: string; argsFor: (command: string) => string[] };
58+
retryBackoffMs?: readonly number[];
5359
}): CronExitWatchers {
5460
const shell = params.shell ?? resolveExitWatchShell();
61+
const retryBackoffMs =
62+
params.retryBackoffMs && params.retryBackoffMs.length > 0
63+
? params.retryBackoffMs
64+
: ON_EXIT_WATCH_RETRY_BACKOFF_MS;
5565
// jobId -> watcher state. `armToken` identifies the current arm so an async
5666
// spawn/wait that loses ownership (the job was cancelled or re-armed for a
5767
// changed command) becomes a no-op. The slot is reserved synchronously in
@@ -67,6 +77,8 @@ export function createCronExitWatchers(params: {
6777
lifecycleSettled: boolean;
6878
command: string;
6979
cwd: string | undefined;
80+
consecutiveFailures: number;
81+
retryTimer: NodeJS.Timeout | undefined;
7082
};
7183
const active = new Map<string, WatcherSlot>();
7284
// A cancelled child can keep running until the supervisor observes exit.
@@ -80,6 +92,10 @@ export function createCronExitWatchers(params: {
8092
return;
8193
}
8294
slot.cancelled = true;
95+
if (slot.retryTimer) {
96+
clearTimeout(slot.retryTimer);
97+
slot.retryTimer = undefined;
98+
}
8399
if (!slot.lifecycleSettled) {
84100
settlingCancelledSlots.add(slot);
85101
}
@@ -98,7 +114,7 @@ export function createCronExitWatchers(params: {
98114
}
99115
};
100116

101-
const arm = (job: OnExitCronJob) => {
117+
const arm = (job: OnExitCronJob, consecutiveFailures = 0) => {
102118
const command = job.schedule.command;
103119
const cwd = job.schedule.cwd;
104120
const armToken: object = {};
@@ -114,9 +130,58 @@ export function createCronExitWatchers(params: {
114130
lifecycleSettled: false,
115131
command,
116132
cwd,
133+
consecutiveFailures,
134+
retryTimer: undefined,
117135
};
118136
active.set(job.id, slot);
119137
const owns = () => active.get(job.id) === slot && slot.armToken === armToken;
138+
const persistWatcherState = async (
139+
patch: Pick<CronJob["state"], "lastError" | "consecutiveErrors">,
140+
) => {
141+
if (!params.updateWatcherState) {
142+
return;
143+
}
144+
try {
145+
const updated = await params.updateWatcherState(slot.job, patch);
146+
if (owns() && updated && isWatchableExitJob(updated)) {
147+
slot.job = updated;
148+
}
149+
} catch (err) {
150+
params.logger.warn(
151+
{ err: String(err), jobId: slot.job.id },
152+
"cron-exit: failed to persist watcher state",
153+
);
154+
}
155+
};
156+
const scheduleRetry = async (error: unknown, phase: "spawn" | "wait") => {
157+
if (!owns() || slot.cancelled) {
158+
return;
159+
}
160+
slot.consecutiveFailures += 1;
161+
const errorText = `${phase} failed: ${String(error)}`;
162+
await persistWatcherState({
163+
lastError: `cron on-exit watcher ${errorText}`,
164+
consecutiveErrors: slot.consecutiveFailures,
165+
});
166+
if (!owns() || slot.cancelled) {
167+
return;
168+
}
169+
const delayMs =
170+
retryBackoffMs[Math.min(slot.consecutiveFailures - 1, retryBackoffMs.length - 1)]!;
171+
slot.retryTimer = setTimeout(() => {
172+
slot.retryTimer = undefined;
173+
if (!owns() || slot.cancelled) {
174+
return;
175+
}
176+
active.delete(slot.job.id);
177+
arm(slot.job, slot.consecutiveFailures);
178+
}, delayMs);
179+
slot.retryTimer.unref?.();
180+
params.logger.warn(
181+
{ err: String(error), jobId: slot.job.id, retryInMs: delayMs },
182+
`cron-exit: watcher ${phase} failed; retry scheduled`,
183+
);
184+
};
120185
void (async () => {
121186
let run: ManagedRun;
122187
try {
@@ -136,10 +201,10 @@ export function createCronExitWatchers(params: {
136201
captureOutput: true,
137202
});
138203
} catch (err) {
139-
if (owns()) {
140-
active.delete(job.id);
141-
}
142-
params.logger.warn({ err: String(err), jobId: job.id }, "cron-exit: watcher spawn failed");
204+
// Keep the slot reserved as the retry placeholder; scheduleRetry re-arms
205+
// with backoff so a transient supervisor failure cannot silently drop
206+
// the watch (the job would otherwise never fire with no recorded cause).
207+
await scheduleRetry(err, "spawn");
143208
return;
144209
}
145210
if (!owns()) {
@@ -161,15 +226,9 @@ export function createCronExitWatchers(params: {
161226
exit = await run.wait();
162227
} catch (err) {
163228
// run.wait() rejected (e.g. supervisor error) rather than resolving with
164-
// an exit. Release the slot so a future reconcile can re-arm, and avoid
165-
// an unhandled rejection. FAIL CLOSED: do not fire on an unknown outcome.
166-
if (owns()) {
167-
active.delete(job.id);
168-
}
169-
params.logger.warn(
170-
{ err: String(err), jobId: job.id },
171-
"cron-exit: run.wait() rejected; released watcher slot without firing",
172-
);
229+
// an exit. FAIL CLOSED: do not fire on an unknown outcome; scheduleRetry
230+
// re-arms the watch with backoff instead of dropping it silently.
231+
await scheduleRetry(err, "wait");
173232
return;
174233
}
175234
if (!owns()) {

‎src/gateway/server-cron.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1154,6 +1154,26 @@ export function buildGatewayCronService(params: {
11541154
}),
11551155
);
11561156
},
1157+
updateWatcherState: async (job, patch) =>
1158+
await runWithGatewayIndependentRootWorkAdmission(async () => {
1159+
try {
1160+
// Same identity guard as persistCompletion: a watcher whose job was
1161+
// edited/replaced must not write failure state onto the successor
1162+
// (which could push it into failure backoff or auto-disable).
1163+
return await cron.updateWithPrecondition(job.id, { state: patch }, (current) => {
1164+
if (
1165+
!current.enabled ||
1166+
current.schedule.kind !== "on-exit" ||
1167+
current.updatedAtMs !== job.updatedAtMs
1168+
) {
1169+
throw new Error("cron on-exit job changed before watcher-state write");
1170+
}
1171+
});
1172+
} catch {
1173+
// Stale watcher identity is a no-op, not an error to surface.
1174+
return undefined;
1175+
}
1176+
}),
11571177
logger: cronLogger,
11581178
});
11591179
const updateCron = cron.update.bind(cron);

0 commit comments

Comments
 (0)