Skip to content

Commit 5c22988

Browse files
committed
fix(cron): avoid no-op schedule repair writes
1 parent 02c095f commit 5c22988

10 files changed

Lines changed: 498 additions & 94 deletions

‎src/cron/service.overdue-scheduling.test.ts‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
// Cron service regression tests cover historical scheduling edge cases.
22
import { describe, expect, it } from "vitest";
33
import { createMockCronStateForJobs } from "./service.test-harness.js";
4-
import { recomputeNextRunsForMaintenance } from "./service/jobs-scheduling.js";
4+
import {
5+
needsCronTimerMaintenance,
6+
recomputeNextRunsForMaintenance,
7+
} from "./service/jobs-scheduling.js";
58
import { reserveQueuedCronRun } from "./service/run-admission.js";
69
import type { CronRunReceiptHandle } from "./store/run-receipt-store.js";
710
import type { CronJob } from "./types.js";
@@ -38,6 +41,63 @@ function testReceipt(jobId: string, startedAtMs: number): CronRunReceiptHandle {
3841

3942
// regression: #13992
4043
describe("issue #13992 regression - cron jobs skip execution", () => {
44+
it.each([
45+
{
46+
name: "already-executed slot",
47+
state: (now: number, next: number) => ({ nextRunAtMs: next, lastRunAtMs: next + 1 }),
48+
expected: true,
49+
},
50+
{
51+
name: "stale backoff slot",
52+
state: (now: number, next: number) => ({
53+
nextRunAtMs: next,
54+
lastRunAtMs: now - 10_000,
55+
lastRunStatus: "error" as const,
56+
consecutiveErrors: 1,
57+
}),
58+
expected: true,
59+
},
60+
{
61+
name: "ordinary due slot",
62+
state: (_now: number, next: number) => ({ nextRunAtMs: next }),
63+
expected: false,
64+
},
65+
{
66+
name: "active queued slot",
67+
state: (now: number, next: number) => ({ nextRunAtMs: next, queuedAtMs: now }),
68+
expected: false,
69+
},
70+
{
71+
name: "active running slot",
72+
state: (now: number, next: number) => ({ nextRunAtMs: next, runningAtMs: now }),
73+
expected: false,
74+
},
75+
{
76+
name: "startup catch-up slot",
77+
state: (_now: number, next: number) => ({
78+
nextRunAtMs: next,
79+
lastRunAtMs: next + 1,
80+
startupCatchupAtMs: next,
81+
}),
82+
expected: false,
83+
},
84+
{
85+
name: "force-preserved slot",
86+
state: (_now: number, next: number) => ({
87+
nextRunAtMs: next,
88+
lastRunAtMs: next + 1,
89+
forcePreservedNextRunAtMs: next,
90+
}),
91+
expected: false,
92+
},
93+
])("classifies $name for expired maintenance", ({ state, expected }) => {
94+
const now = Date.now();
95+
const next = now - 60_000;
96+
const job = createCronSystemEventJob(now, { state: state(now, next) });
97+
98+
expect(needsCronTimerMaintenance(job, now)).toBe(expected);
99+
});
100+
41101
it("should NOT recompute nextRunAtMs for past-due jobs by default", () => {
42102
const now = Date.now();
43103
const pastDue = now - 60_000; // 1 minute ago

‎src/cron/service.read-ops-nonblocking.test.ts‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,22 @@ import { describe, expect, it, vi } from "vitest";
66
import { withTimeout } from "../utils/with-timeout.js";
77
import { CronService } from "./service.js";
88
import { writeCronStoreSnapshot } from "./service.test-harness.js";
9+
import type { CronJob } from "./types.js";
10+
11+
const sqliteTransactionLabels = vi.hoisted(() => [] as string[]);
12+
13+
vi.mock("../state/openclaw-state-db.js", async (importOriginal) => {
14+
const actual = await importOriginal<typeof import("../state/openclaw-state-db.js")>();
15+
const runOpenClawStateWriteTransaction: typeof actual.runOpenClawStateWriteTransaction = (
16+
operation,
17+
options,
18+
transactionOptions,
19+
) => {
20+
sqliteTransactionLabels.push(transactionOptions?.operationLabel ?? "state.write");
21+
return actual.runOpenClawStateWriteTransaction(operation, options, transactionOptions);
22+
};
23+
return { ...actual, runOpenClawStateWriteTransaction };
24+
});
925

1026
const noopLogger = {
1127
debug: vi.fn(),
@@ -76,7 +92,84 @@ function expectCronStatus(
7692
}
7793
}
7894

95+
function futureJob(id: string, nowMs: number, withNextRun = true): CronJob {
96+
return {
97+
id,
98+
name: id,
99+
enabled: true,
100+
createdAtMs: nowMs,
101+
updatedAtMs: nowMs,
102+
schedule: { kind: "every", everyMs: 60_000, anchorMs: nowMs },
103+
sessionTarget: "isolated",
104+
wakeMode: "next-heartbeat",
105+
payload: { kind: "agentTurn", message: id },
106+
state: withNextRun ? { nextRunAtMs: nowMs + 60_000 } : {},
107+
};
108+
}
109+
79110
describe("CronService read ops while job is running", () => {
111+
it("keeps started read operations observational across a large stable store", async () => {
112+
const nowMs = Date.parse("2026-08-30T12:00:00.000Z");
113+
const store = await makeStorePath();
114+
const jobs = Array.from({ length: 100 }, (_, index) => futureJob(`stable-${index}`, nowMs));
115+
await writeCronStoreSnapshot({ storePath: store.storePath, jobs });
116+
const cron = new CronService({
117+
storePath: store.storePath,
118+
cronEnabled: true,
119+
log: noopLogger,
120+
nowMs: () => nowMs,
121+
enqueueSystemEvent: vi.fn(),
122+
requestHeartbeat: vi.fn(),
123+
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
124+
});
125+
126+
try {
127+
await cron.start();
128+
sqliteTransactionLabels.length = 0;
129+
130+
await cron.status();
131+
await cron.list({ includeDisabled: true });
132+
await cron.listPage({ limit: 25 });
133+
await cron.readJob(jobs[0]!.id);
134+
135+
expect(
136+
sqliteTransactionLabels.filter((label) => label === "cron.schedule-unowned"),
137+
).toHaveLength(0);
138+
} finally {
139+
cron.stop();
140+
await store.cleanup();
141+
}
142+
});
143+
144+
it("retains one durable missing-schedule repair before the scheduler starts", async () => {
145+
const nowMs = Date.parse("2026-08-30T12:00:00.000Z");
146+
const store = await makeStorePath();
147+
const job = futureJob("unstarted-missing-next", nowMs, false);
148+
await writeCronStoreSnapshot({ storePath: store.storePath, jobs: [job] });
149+
const cron = new CronService({
150+
storePath: store.storePath,
151+
cronEnabled: true,
152+
log: noopLogger,
153+
nowMs: () => nowMs,
154+
enqueueSystemEvent: vi.fn(),
155+
requestHeartbeat: vi.fn(),
156+
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
157+
});
158+
159+
try {
160+
sqliteTransactionLabels.length = 0;
161+
await expect(cron.readJob(job.id)).resolves.toMatchObject({
162+
state: { nextRunAtMs: nowMs + 60_000 },
163+
});
164+
expect(
165+
sqliteTransactionLabels.filter((label) => label === "cron.schedule-unowned"),
166+
).toHaveLength(1);
167+
} finally {
168+
cron.stop();
169+
await store.cleanup();
170+
}
171+
});
172+
80173
it.each([
81174
{ deleteAfterRun: true, status: "ok" },
82175
{ deleteAfterRun: false, status: "ok" },
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { setupCronServiceSuite, writeCronStoreSnapshot } from "./service.test-harness.js";
3+
import { createCronServiceState } from "./service/state.js";
4+
import { onTimer } from "./service/timer.test-support.js";
5+
import type { CronJob } from "./types.js";
6+
7+
const sqliteTransactionLabels = vi.hoisted(() => [] as string[]);
8+
9+
vi.mock("../state/openclaw-state-db.js", async (importOriginal) => {
10+
const actual = await importOriginal<typeof import("../state/openclaw-state-db.js")>();
11+
const runOpenClawStateWriteTransaction: typeof actual.runOpenClawStateWriteTransaction = (
12+
operation,
13+
options,
14+
transactionOptions,
15+
) => {
16+
sqliteTransactionLabels.push(transactionOptions?.operationLabel ?? "state.write");
17+
return actual.runOpenClawStateWriteTransaction(operation, options, transactionOptions);
18+
};
19+
return { ...actual, runOpenClawStateWriteTransaction };
20+
});
21+
22+
const { logger, makeStorePath } = setupCronServiceSuite({
23+
prefix: "cron-timer-maintenance-",
24+
baseTimeIso: "2026-08-30T12:00:00.000Z",
25+
});
26+
27+
function job(
28+
id: string,
29+
nowMs: number,
30+
schedule: CronJob["schedule"],
31+
state: CronJob["state"],
32+
): CronJob {
33+
return {
34+
id,
35+
name: id,
36+
enabled: true,
37+
createdAtMs: nowMs - 60_000,
38+
updatedAtMs: nowMs - 60_000,
39+
schedule,
40+
sessionTarget: "isolated",
41+
wakeMode: "next-heartbeat",
42+
payload: { kind: "agentTurn", message: id },
43+
state,
44+
};
45+
}
46+
47+
async function runTimer(jobs: CronJob[], nowMs: number) {
48+
const store = await makeStorePath();
49+
await writeCronStoreSnapshot({ storePath: store.storePath, jobs });
50+
const state = createCronServiceState({
51+
storePath: store.storePath,
52+
cronEnabled: true,
53+
log: logger,
54+
nowMs: () => nowMs,
55+
enqueueSystemEvent: vi.fn(),
56+
requestHeartbeat: vi.fn(),
57+
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
58+
});
59+
state.schedulerStarted = true;
60+
sqliteTransactionLabels.length = 0;
61+
await onTimer(state);
62+
if (state.timer) {
63+
clearTimeout(state.timer);
64+
state.timer = null;
65+
}
66+
return {
67+
jobs: state.store?.jobs ?? [],
68+
maintenanceCount: sqliteTransactionLabels.filter((label) => label === "cron.schedule-unowned")
69+
.length,
70+
};
71+
}
72+
73+
describe("cron timer maintenance admission", () => {
74+
it.each([
75+
{
76+
name: "stable future schedule",
77+
create: (nowMs: number) =>
78+
job(
79+
"future",
80+
nowMs,
81+
{ kind: "every", everyMs: 60_000, anchorMs: nowMs },
82+
{ nextRunAtMs: nowMs + 60_000 },
83+
),
84+
},
85+
{
86+
name: "valid future cron slot",
87+
create: (nowMs: number) =>
88+
job(
89+
"future-cron",
90+
nowMs,
91+
{ kind: "cron", expr: "0 * * * * *", tz: "UTC", staggerMs: 0 },
92+
{ nextRunAtMs: Math.floor(nowMs / 60_000) * 60_000 + 60_000 },
93+
),
94+
},
95+
{
96+
name: "event-driven schedule without a timer slot",
97+
create: (nowMs: number) =>
98+
job(
99+
"stream",
100+
nowMs,
101+
{ kind: "stream", command: ["true"] },
102+
{
103+
streamSourceIdentity: "source",
104+
},
105+
),
106+
},
107+
{
108+
name: "active due schedule",
109+
create: (nowMs: number) =>
110+
job(
111+
"active",
112+
nowMs,
113+
{ kind: "every", everyMs: 60_000, anchorMs: nowMs - 120_000 },
114+
{ nextRunAtMs: nowMs - 60_000, runningAtMs: nowMs },
115+
),
116+
},
117+
])("skips a write sweep for $name", async ({ create }) => {
118+
const nowMs = Date.now();
119+
const result = await runTimer([create(nowMs)], nowMs);
120+
expect(result.maintenanceCount).toBe(0);
121+
});
122+
123+
it("runs one sweep for a stale backoff slot", async () => {
124+
const nowMs = Date.now();
125+
const nextRunAtMs = nowMs - 20_000;
126+
const result = await runTimer(
127+
[
128+
job(
129+
"stale-backoff",
130+
nowMs,
131+
{ kind: "every", everyMs: 60_000, anchorMs: nowMs - 120_000 },
132+
{
133+
nextRunAtMs,
134+
lastRunAtMs: nowMs - 10_000,
135+
lastRunStatus: "error",
136+
consecutiveErrors: 1,
137+
},
138+
),
139+
],
140+
nowMs,
141+
);
142+
expect(result.maintenanceCount).toBe(1);
143+
expect(result.jobs[0]?.state.nextRunAtMs).toBeGreaterThan(nowMs);
144+
});
145+
146+
it("repairs a stale future cron slot with one sweep", async () => {
147+
const nowMs = Date.now();
148+
const expected = Math.floor(nowMs / 60_000) * 60_000 + 60_000;
149+
const stale = job(
150+
"stale-future",
151+
nowMs,
152+
{ kind: "cron", expr: "0 * * * * *", tz: "UTC", staggerMs: 0 },
153+
{ nextRunAtMs: nowMs + 7 * 24 * 60 * 60_000 + 30_000 },
154+
);
155+
stale.payload = { kind: "systemEvent", text: "repair stale future slot" };
156+
157+
const result = await runTimer([stale], nowMs);
158+
expect(result.maintenanceCount).toBe(1);
159+
expect(result.jobs[0]?.state.nextRunAtMs).toBe(expected);
160+
});
161+
162+
it("keeps retrying malformed timed schedules until the third failure disables them", async () => {
163+
const nowMs = Date.now();
164+
let current = job(
165+
"malformed",
166+
nowMs,
167+
{ kind: "cron", expr: "0 7 * * *", tz: "Invalid/Timezone" },
168+
{},
169+
);
170+
171+
for (let attempt = 1; attempt <= 3; attempt += 1) {
172+
const result = await runTimer([current], nowMs);
173+
expect(result.maintenanceCount).toBe(1);
174+
current = result.jobs[0]!;
175+
expect(current.state.scheduleErrorCount).toBe(attempt);
176+
expect(current.enabled).toBe(attempt < 3);
177+
}
178+
});
179+
});

0 commit comments

Comments
 (0)