Skip to content

Commit 9242713

Browse files
authored
fix(cron): record interrupted startup runs
* fix(cron): record interrupted startup runs * test(cron): update interrupted startup expectations
1 parent fc5920f commit 9242713

6 files changed

Lines changed: 226 additions & 35 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ Docs: https://docs.openclaw.ai
2727
- Google video generation: download direct MLDev Veo `video.uri` results instead of passing them through the Files API path, fixing 404s after successful generation/polling. Fixes #71200. Thanks @panhaishan.
2828
- Google video generation: fall back to the REST `predictLongRunning` Veo endpoint for text-only SDK 404s while keeping reference image/video generation on the SDK path. Fixes #62309 and #63008. (#62343) Thanks @leoleedev.
2929
- MiniMax music generation: switch the bundled default model from the unsupported `music-2.5+` id to the current `music-2.6` API model. Fixes #64870 and addresses the music default from #62315. Thanks @noahclanman and @edwardzheng1.
30+
- Cron: record jobs interrupted by a gateway restart as failed at their original `runningAtMs`, skip unsafe startup replay, and disable interrupted one-shot jobs so they show a visible failure instead of silently disappearing or duplicating work. Fixes #59056, #61343, #63657, and #59301. Thanks @ponchoooPenguin, @daemic24, @myradon, and @hikiwibot.
31+
- Cron tool: recover flat top-level schedule shorthand such as `cron`, `tz`, and `staggerMs` before gateway validation, so model-generated cron add/update calls preserve cron jitter settings. Thanks @tyxben.
3032
- Cron: hydrate flat legacy job rows with top-level `cron`, `tz`, `session`, and `message` fields into canonical schedule, target, and payload objects before startup recomputes run times. Fixes #43351.
3133
- Agents/replies: let pending group chat history trigger bare mentioned turns without treating metadata-only inbound context as user input. Fixes #71489. (#71520) Thanks @SymbolStar.
3234
- Google media generation: strip a configured trailing `/v1beta` from Google music/video provider base URLs before calling the Google GenAI SDK, preventing doubled `/v1beta/v1beta` paths. Fixes #63240. (#63258) Thanks @Hybirdss.

‎src/agents/tools/cron-tool.flat-params.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,66 @@ describe("cron tool flat-params", () => {
3636
expect(method).toBe("cron.add");
3737
expect(params.sessionKey).toBe("agent:main:telegram:group:-100123:topic:99");
3838
});
39+
40+
it("recovers flat cron schedule shorthand for add", async () => {
41+
const tool = createCronTool(undefined, { callGatewayTool: callGatewayToolMock });
42+
43+
await tool.execute("call-flat-cron-add", {
44+
action: "add",
45+
name: "hourly report",
46+
cron: "0 * * * *",
47+
tz: "UTC",
48+
staggerMs: 5000,
49+
message: "send report",
50+
});
51+
52+
const [method, _gatewayOpts, params] = callGatewayToolMock.mock.calls[0] as [
53+
string,
54+
unknown,
55+
{
56+
schedule?: unknown;
57+
payload?: unknown;
58+
},
59+
];
60+
expect(method).toBe("cron.add");
61+
expect(params.schedule).toEqual({
62+
kind: "cron",
63+
expr: "0 * * * *",
64+
tz: "UTC",
65+
staggerMs: 5000,
66+
});
67+
expect(params.payload).toEqual({
68+
kind: "agentTurn",
69+
message: "send report",
70+
});
71+
});
72+
73+
it("recovers flat cron schedule shorthand for update", async () => {
74+
const tool = createCronTool(undefined, { callGatewayTool: callGatewayToolMock });
75+
76+
await tool.execute("call-flat-cron-update", {
77+
action: "update",
78+
jobId: "job-123",
79+
cron: "15 8 * * 1-5",
80+
tz: "America/Los_Angeles",
81+
staggerMs: 30_000,
82+
});
83+
84+
const [method, _gatewayOpts, params] = callGatewayToolMock.mock.calls[0] as [
85+
string,
86+
unknown,
87+
{
88+
id?: string;
89+
patch?: { schedule?: unknown };
90+
},
91+
];
92+
expect(method).toBe("cron.update");
93+
expect(params.id).toBe("job-123");
94+
expect(params.patch?.schedule).toEqual({
95+
kind: "cron",
96+
expr: "15 8 * * 1-5",
97+
tz: "America/Los_Angeles",
98+
staggerMs: 30_000,
99+
});
100+
});
39101
});

‎src/agents/tools/cron-tool.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,20 @@ const CRON_FLAT_PAYLOAD_KEYS = [
3939
"lightContext",
4040
"allowUnsafeExternalContent",
4141
] as const;
42+
const CRON_FLAT_SCHEDULE_KEYS = [
43+
"kind",
44+
"at",
45+
"atMs",
46+
"every",
47+
"everyMs",
48+
"anchorMs",
49+
"cron",
50+
"expr",
51+
"tz",
52+
"stagger",
53+
"staggerMs",
54+
"exact",
55+
] as const;
4256
const CRON_RECOVERABLE_OBJECT_KEYS: ReadonlySet<string> = new Set([
4357
"name",
4458
"schedule",
@@ -53,6 +67,7 @@ const CRON_RECOVERABLE_OBJECT_KEYS: ReadonlySet<string> = new Set([
5367
"sessionKey",
5468
"failureAlert",
5569
...CRON_FLAT_PAYLOAD_KEYS,
70+
...CRON_FLAT_SCHEDULE_KEYS,
5671
]);
5772

5873
const REMINDER_CONTEXT_MESSAGES_MAX = 10;
@@ -76,12 +91,29 @@ function recoverCronObjectFromFlatParams(params: Record<string, unknown>): {
7691
found = true;
7792
}
7893
}
94+
if (value.everyMs === undefined && value.every !== undefined) {
95+
value.everyMs = value.every;
96+
}
97+
if (value.staggerMs === undefined && value.stagger !== undefined) {
98+
value.staggerMs = value.stagger;
99+
}
100+
if (value.exact === true && value.staggerMs === undefined) {
101+
value.staggerMs = 0;
102+
}
103+
delete value.every;
104+
delete value.stagger;
105+
delete value.exact;
79106
return { found, value };
80107
}
81108

82109
function hasCronCreateSignal(value: Record<string, unknown>): boolean {
83110
return (
84111
value.schedule !== undefined ||
112+
value.at !== undefined ||
113+
value.atMs !== undefined ||
114+
value.everyMs !== undefined ||
115+
value.cron !== undefined ||
116+
value.expr !== undefined ||
85117
value.payload !== undefined ||
86118
value.message !== undefined ||
87119
value.text !== undefined

‎src/cron/service.restart-catchup.test.ts‎

Lines changed: 43 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import path from "node:path";
33
import { describe, expect, it, vi } from "vitest";
44
import { CronService } from "./service.js";
55
import { setupCronServiceSuite } from "./service.test-harness.js";
6+
import type { CronEvent } from "./service/state.js";
67
import { createCronServiceState } from "./service/state.js";
78
import { runMissedJobs } from "./service/timer.js";
89

@@ -21,6 +22,7 @@ describe("CronService restart catch-up", () => {
2122
storePath: string;
2223
enqueueSystemEvent: ReturnType<typeof vi.fn>;
2324
requestHeartbeatNow: ReturnType<typeof vi.fn>;
25+
onEvent?: ReturnType<typeof vi.fn>;
2426
}) {
2527
return new CronService({
2628
storePath: params.storePath,
@@ -29,6 +31,7 @@ describe("CronService restart catch-up", () => {
2931
enqueueSystemEvent: params.enqueueSystemEvent as never,
3032
requestHeartbeatNow: params.requestHeartbeatNow as never,
3133
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })) as never,
34+
onEvent: params.onEvent as ((evt: CronEvent) => void) | undefined,
3235
});
3336
}
3437

@@ -53,23 +56,26 @@ describe("CronService restart catch-up", () => {
5356
cron: CronService;
5457
enqueueSystemEvent: ReturnType<typeof vi.fn>;
5558
requestHeartbeatNow: ReturnType<typeof vi.fn>;
59+
onEvent: ReturnType<typeof vi.fn>;
5660
}) => Promise<void>,
5761
) {
5862
const store = await makeStorePath();
5963
const enqueueSystemEvent = vi.fn();
6064
const requestHeartbeatNow = vi.fn();
65+
const onEvent = vi.fn();
6166

6267
await writeStoreJobs(store.storePath, jobs);
6368

6469
const cron = createRestartCronService({
6570
storePath: store.storePath,
6671
enqueueSystemEvent,
6772
requestHeartbeatNow,
73+
onEvent,
6874
});
6975

7076
try {
7177
await cron.start();
72-
await run({ cron, enqueueSystemEvent, requestHeartbeatNow });
78+
await run({ cron, enqueueSystemEvent, requestHeartbeatNow, onEvent });
7379
} finally {
7480
cron.stop();
7581
await store.cleanup();
@@ -115,7 +121,7 @@ describe("CronService restart catch-up", () => {
115121
);
116122
});
117123

118-
it("replays interrupted recurring job on first restart (#60495)", async () => {
124+
it("marks interrupted recurring jobs failed instead of replaying them on startup", async () => {
119125
const dueAt = Date.parse("2025-12-13T16:00:00.000Z");
120126
const staleRunningAt = Date.parse("2025-12-13T16:30:00.000Z");
121127

@@ -137,23 +143,32 @@ describe("CronService restart catch-up", () => {
137143
},
138144
},
139145
],
140-
async ({ cron, enqueueSystemEvent, requestHeartbeatNow }) => {
146+
async ({ cron, enqueueSystemEvent, requestHeartbeatNow, onEvent }) => {
141147
expect(noopLogger.warn).toHaveBeenCalledWith(
142148
expect.objectContaining({ jobId: "restart-stale-running" }),
143-
"cron: clearing stale running marker on startup",
149+
"cron: marking interrupted running job failed on startup",
144150
);
145151

146-
expect(enqueueSystemEvent).toHaveBeenCalledWith(
147-
"resume stale marker",
148-
expect.objectContaining({ agentId: undefined }),
149-
);
150-
expect(requestHeartbeatNow).toHaveBeenCalled();
152+
expect(enqueueSystemEvent).not.toHaveBeenCalled();
153+
expect(requestHeartbeatNow).not.toHaveBeenCalled();
151154

152155
const listedJobs = await cron.list({ includeDisabled: true });
153156
const updated = listedJobs.find((job) => job.id === "restart-stale-running");
154157
expect(updated?.state.runningAtMs).toBeUndefined();
155-
expect(updated?.state.lastStatus).toBe("ok");
156-
expect(updated?.state.lastRunAtMs).toBe(Date.parse("2025-12-13T17:00:00.000Z"));
158+
expect(updated?.state.lastStatus).toBe("error");
159+
expect(updated?.state.lastRunStatus).toBe("error");
160+
expect(updated?.state.lastRunAtMs).toBe(staleRunningAt);
161+
expect(updated?.state.lastError).toBe("cron: job interrupted by gateway restart");
162+
expect(updated?.state.nextRunAtMs).toBeGreaterThan(Date.parse("2025-12-13T17:00:00.000Z"));
163+
expect(onEvent).toHaveBeenCalledWith(
164+
expect.objectContaining({
165+
action: "finished",
166+
jobId: "restart-stale-running",
167+
status: "error",
168+
error: "cron: job interrupted by gateway restart",
169+
runAtMs: staleRunningAt,
170+
}),
171+
);
157172
},
158173
);
159174
});
@@ -194,7 +209,7 @@ describe("CronService restart catch-up", () => {
194209
);
195210
});
196211

197-
it("does not replay interrupted one-shot jobs on startup", async () => {
212+
it("marks interrupted one-shot jobs failed and disabled on startup", async () => {
198213
const dueAt = Date.parse("2025-12-13T16:00:00.000Z");
199214
const staleRunningAt = Date.parse("2025-12-13T16:30:00.000Z");
200215

@@ -216,13 +231,28 @@ describe("CronService restart catch-up", () => {
216231
},
217232
},
218233
],
219-
async ({ cron, enqueueSystemEvent, requestHeartbeatNow }) => {
234+
async ({ cron, enqueueSystemEvent, requestHeartbeatNow, onEvent }) => {
220235
expect(enqueueSystemEvent).not.toHaveBeenCalled();
221236
expect(requestHeartbeatNow).not.toHaveBeenCalled();
222237

223238
const listedJobs = await cron.list({ includeDisabled: true });
224239
const updated = listedJobs.find((job) => job.id === "restart-stale-one-shot");
240+
expect(updated?.enabled).toBe(false);
225241
expect(updated?.state.runningAtMs).toBeUndefined();
242+
expect(updated?.state.lastStatus).toBe("error");
243+
expect(updated?.state.lastRunStatus).toBe("error");
244+
expect(updated?.state.lastRunAtMs).toBe(staleRunningAt);
245+
expect(updated?.state.nextRunAtMs).toBeUndefined();
246+
expect(updated?.state.lastError).toBe("cron: job interrupted by gateway restart");
247+
expect(onEvent).toHaveBeenCalledWith(
248+
expect.objectContaining({
249+
action: "finished",
250+
jobId: "restart-stale-one-shot",
251+
status: "error",
252+
error: "cron: job interrupted by gateway restart",
253+
runAtMs: staleRunningAt,
254+
}),
255+
);
226256
},
227257
);
228258
});

‎src/cron/service/ops.test.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ function createMissedIsolatedJob(now: number): CronJob {
128128
}
129129

130130
describe("cron service ops seam coverage", () => {
131-
it("start clears stale running markers, replays interrupted recurring jobs, persists, and arms the timer (#60495)", async () => {
131+
it("start marks interrupted running jobs failed, persists, and arms the timer", async () => {
132132
const { storePath } = await makeStorePath();
133133
const now = Date.parse("2026-03-23T12:00:00.000Z");
134134
const enqueueSystemEvent = vi.fn();
@@ -154,11 +154,10 @@ describe("cron service ops seam coverage", () => {
154154

155155
expect(logger.warn).toHaveBeenCalledWith(
156156
expect.objectContaining({ jobId: "startup-interrupted" }),
157-
"cron: clearing stale running marker on startup",
157+
"cron: marking interrupted running job failed on startup",
158158
);
159-
// Interrupted recurring jobs are now replayed on first restart (#60495)
160-
expect(enqueueSystemEvent).toHaveBeenCalled();
161-
expect(requestHeartbeatNow).toHaveBeenCalled();
159+
expect(enqueueSystemEvent).not.toHaveBeenCalled();
160+
expect(requestHeartbeatNow).not.toHaveBeenCalled();
162161
expect(state.timer).not.toBeNull();
163162

164163
const persisted = (await loadCronStore(storePath)) as {
@@ -167,7 +166,10 @@ describe("cron service ops seam coverage", () => {
167166
const job = persisted.jobs[0];
168167
expect(job).toBeDefined();
169168
expect(job?.state.runningAtMs).toBeUndefined();
170-
expect(job?.state.lastStatus).toBe("ok");
169+
expect(job?.state.lastStatus).toBe("error");
170+
expect(job?.state.lastRunStatus).toBe("error");
171+
expect(job?.state.lastRunAtMs).toBe(now - 30 * 60_000);
172+
expect(job?.state.lastError).toBe("cron: job interrupted by gateway restart");
171173
expect((job?.state.nextRunAtMs ?? 0) > now).toBe(true);
172174

173175
const delays = timeoutSpy.mock.calls

0 commit comments

Comments
 (0)