Skip to content

Commit e38d64c

Browse files
authored
fix(cron): keep a due recurring run when an edit re-saves the same schedule (#96159)
* fix(cron): keep a due recurring run when an edit re-saves the same schedule update() advanced state.nextRunAtMs to the next future slot whenever a patch carried schedule or enabled, even when the schedule was unchanged, dropping an already-due run and re-phasing every-job anchors to now. Gate the advance on cronSchedulingInputsEqual so only a genuine schedule or enabled change recomputes, and inherit the previous every anchor when a re-save omits it, matching the add/remove maintenance recompute. * fix(cron): re-anchor every-job to edit time on a genuine interval change Only inherit the previous cadence anchor for an unchanged-interval every re-save. A real everyMs change (UI omits anchorMs) now re-anchors to the edit time, matching the prior update semantics, while idempotent re-saves still preserve a due slot and phase. Adds a regression test for the interval-change path.
1 parent 7e42879 commit e38d64c

2 files changed

Lines changed: 189 additions & 5 deletions

File tree

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { CronService } from "./service.js";
3+
import {
4+
createCronStoreHarness,
5+
createFinishedBarrier,
6+
createNoopLogger,
7+
installCronTestHooks,
8+
} from "./service.test-harness.js";
9+
10+
const noopLogger = createNoopLogger();
11+
const { makeStorePath } = createCronStoreHarness();
12+
installCronTestHooks({ logger: noopLogger });
13+
14+
describe("update() must not drop a due every-job's pending run", () => {
15+
it("preserves a due every-job nextRunAtMs on an idempotent schedule re-save", async () => {
16+
const store = await makeStorePath();
17+
const base = Date.parse("2025-12-13T00:00:00.000Z");
18+
19+
const finished = createFinishedBarrier();
20+
const cron = new CronService({
21+
storePath: store.storePath,
22+
cronEnabled: true,
23+
log: noopLogger,
24+
enqueueSystemEvent: vi.fn(),
25+
requestHeartbeat: vi.fn(),
26+
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
27+
onEvent: finished.onEvent,
28+
});
29+
30+
await cron.start();
31+
32+
const job = await cron.add({
33+
name: "every 10s",
34+
enabled: true,
35+
schedule: { kind: "every", everyMs: 10_000 },
36+
sessionTarget: "isolated",
37+
wakeMode: "next-heartbeat",
38+
payload: { kind: "agentTurn", message: "tick" },
39+
});
40+
const jobId = job.id;
41+
expect(job.state.nextRunAtMs).toBe(base + 10_000);
42+
43+
// Fire once so the job carries lastRunAtMs and a real next due slot.
44+
vi.setSystemTime(new Date(base + 10_000 + 5));
45+
const firstRun = finished.waitForOk(jobId);
46+
await vi.runOnlyPendingTimersAsync();
47+
await firstRun;
48+
49+
let current = (await cron.list({ includeDisabled: true })).find((j) => j.id === jobId)!;
50+
const lastRunAtMs = current.state.lastRunAtMs!;
51+
const dueSlot = current.state.nextRunAtMs!;
52+
expect(dueSlot).toBe(lastRunAtMs + 10_000);
53+
54+
// Advance past the next slot so it is now due, before the timer services it.
55+
vi.setSystemTime(new Date(dueSlot + 50));
56+
const nowDue = dueSlot + 50;
57+
58+
// User edits the job and the control UI resubmits the unchanged schedule
59+
// (a normal idempotent re-save, e.g. while changing the message). This must
60+
// not advance the already-due slot.
61+
await cron.update(jobId, { schedule: { kind: "every", everyMs: 10_000 } });
62+
63+
current = (await cron.list({ includeDisabled: true })).find((j) => j.id === jobId)!;
64+
// Correct: the due slot is preserved so the pending run still fires.
65+
// Buggy (current main): nextRunAtMs jumps to dueSlot + 10_000 (> nowDue),
66+
// silently dropping this slot's run.
67+
expect(current.state.lastRunAtMs).toBe(lastRunAtMs);
68+
expect(current.state.nextRunAtMs).toBe(dueSlot);
69+
expect(current.state.nextRunAtMs).toBeLessThanOrEqual(nowDue);
70+
// The cadence anchor must not re-phase to "now" on an idempotent re-save.
71+
expect(current.schedule).toMatchObject({ kind: "every", anchorMs: base });
72+
73+
cron.stop();
74+
});
75+
76+
it("re-anchors an every-job to the edit time when the interval actually changes", async () => {
77+
const store = await makeStorePath();
78+
const base = Date.parse("2025-12-13T00:00:00.000Z");
79+
80+
const finished = createFinishedBarrier();
81+
const cron = new CronService({
82+
storePath: store.storePath,
83+
cronEnabled: true,
84+
log: noopLogger,
85+
enqueueSystemEvent: vi.fn(),
86+
requestHeartbeat: vi.fn(),
87+
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
88+
onEvent: finished.onEvent,
89+
});
90+
91+
await cron.start();
92+
93+
const job = await cron.add({
94+
name: "every 10s",
95+
enabled: true,
96+
schedule: { kind: "every", everyMs: 10_000 },
97+
sessionTarget: "isolated",
98+
wakeMode: "next-heartbeat",
99+
payload: { kind: "agentTurn", message: "tick" },
100+
});
101+
const jobId = job.id;
102+
expect(job.schedule).toMatchObject({ kind: "every", anchorMs: base });
103+
104+
// User edits the interval from 10s to 1h. The control UI omits the internal
105+
// anchorMs, so the new cadence must start from the edit time rather than
106+
// keeping the old phase; nextRunAtMs is one new interval from now.
107+
const editTime = base + 3_000;
108+
vi.setSystemTime(new Date(editTime));
109+
await cron.update(jobId, { schedule: { kind: "every", everyMs: 3_600_000 } });
110+
111+
const current = (await cron.list({ includeDisabled: true })).find((j) => j.id === jobId)!;
112+
expect(current.schedule).toMatchObject({
113+
kind: "every",
114+
everyMs: 3_600_000,
115+
anchorMs: editTime,
116+
});
117+
expect(current.state.nextRunAtMs).toBe(editTime + 3_600_000);
118+
119+
cron.stop();
120+
});
121+
122+
it("preserves a due cron-job nextRunAtMs on an idempotent schedule re-save", async () => {
123+
const store = await makeStorePath();
124+
vi.setSystemTime(new Date("2025-12-13T08:59:00.000Z"));
125+
126+
const finished = createFinishedBarrier();
127+
const cron = new CronService({
128+
storePath: store.storePath,
129+
cronEnabled: true,
130+
log: noopLogger,
131+
enqueueSystemEvent: vi.fn(),
132+
requestHeartbeat: vi.fn(),
133+
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
134+
onEvent: finished.onEvent,
135+
});
136+
137+
await cron.start();
138+
139+
const job = await cron.add({
140+
name: "daily 9am",
141+
enabled: true,
142+
schedule: { kind: "cron", expr: "0 9 * * *" },
143+
sessionTarget: "isolated",
144+
wakeMode: "next-heartbeat",
145+
payload: { kind: "agentTurn", message: "report" },
146+
});
147+
const jobId = job.id;
148+
const dueSlot = job.state.nextRunAtMs!;
149+
150+
// Advance past the 09:00 slot so it is now due, before the timer fires it.
151+
vi.setSystemTime(new Date(dueSlot + 50));
152+
const nowDue = dueSlot + 50;
153+
154+
await cron.update(jobId, { schedule: { kind: "cron", expr: "0 9 * * *" } });
155+
156+
const current = (await cron.list({ includeDisabled: true })).find((j) => j.id === jobId)!;
157+
// Correct: the due slot is preserved. Buggy main: nextRunAtMs jumps to the
158+
// next day, dropping today's run.
159+
expect(current.state.nextRunAtMs).toBe(dueSlot);
160+
expect(current.state.nextRunAtMs).toBeLessThanOrEqual(nowDue);
161+
162+
cron.stop();
163+
});
164+
});

‎src/cron/service/ops.ts‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
import { resolveCronDeliveryPlan, resolveFailureDestination } from "../delivery-plan.js";
1919
import { createCronRunDiagnosticsFromError } from "../run-diagnostics.js";
2020
import { createCronExecutionId } from "../run-id.js";
21+
import { cronSchedulingInputsEqual } from "../schedule-identity.js";
2122
import type { CronJob, CronJobCreate, CronJobPatch } from "../types.js";
2223
import { normalizeCronRunErrorText } from "./execution-errors.js";
2324
import { failureNotificationDeliveryFromJobState } from "./failure-alerts.js";
@@ -524,28 +525,47 @@ export async function update(state: CronServiceState, id: string, patch: CronJob
524525
if (nextJob.schedule.kind === "every") {
525526
const anchor = nextJob.schedule.anchorMs;
526527
if (typeof anchor !== "number" || !Number.isFinite(anchor)) {
527-
const patchSchedule = patch.schedule;
528+
// Inherit the previous cadence anchor only for an unchanged-interval
529+
// re-save (UIs resubmit the schedule without the internal anchorMs).
530+
// Without this an idempotent edit re-phases the job to now, shifting
531+
// every future fire time and skipping an already-due slot. A genuine
532+
// interval change still anchors to the edit time so the new cadence
533+
// starts now, matching the prior update semantics.
534+
const previousAnchorMs =
535+
job.schedule.kind === "every" &&
536+
job.schedule.everyMs === nextJob.schedule.everyMs &&
537+
typeof job.schedule.anchorMs === "number" &&
538+
Number.isFinite(job.schedule.anchorMs)
539+
? job.schedule.anchorMs
540+
: undefined;
528541
const fallbackAnchorMs =
529-
patchSchedule?.kind === "every"
542+
previousAnchorMs ??
543+
(patch.schedule?.kind === "every"
530544
? now
531545
: typeof nextJob.createdAtMs === "number" && Number.isFinite(nextJob.createdAtMs)
532546
? nextJob.createdAtMs
533-
: now;
547+
: now);
534548
nextJob.schedule = {
535549
...nextJob.schedule,
536550
anchorMs: Math.max(0, Math.floor(fallbackAnchorMs)),
537551
};
538552
}
539553
}
554+
// Only advance a recurring job's next run when the schedule/enabled inputs
555+
// actually changed. An idempotent re-save (same schedule, or re-enabling an
556+
// already-enabled job) must preserve a still-due slot, matching the
557+
// add/remove maintenance recompute; otherwise the pending run is dropped.
558+
const schedulingInputsChanged =
559+
(patch.schedule !== undefined || patch.enabled !== undefined) &&
560+
!cronSchedulingInputsEqual(job, nextJob);
540561
const scheduleChanged = patch.schedule !== undefined;
541-
const enabledChanged = patch.enabled !== undefined;
542562

543563
if (scheduleChanged && nextJob.schedule.kind === "cron" && !isJobEnabled(nextJob)) {
544564
computeJobNextRunAtMs({ ...nextJob, enabled: true }, now);
545565
}
546566

547567
nextJob.updatedAtMs = now;
548-
if (scheduleChanged || enabledChanged) {
568+
if (schedulingInputsChanged) {
549569
if (isJobEnabled(nextJob)) {
550570
nextJob.state.nextRunAtMs = computeJobNextRunAtMs(nextJob, now);
551571
} else {

0 commit comments

Comments
 (0)