Skip to content

Commit 0073862

Browse files
fix(cron): protect recreated jobs from stale runs (#114756)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent 0d32f85 commit 0073862

7 files changed

Lines changed: 245 additions & 4 deletions

‎src/cron/active-jobs.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
hasActiveCronJobs,
66
hasActiveCronJobsExceptMarker,
77
markCronJobActive,
8+
noteActiveCronJobRemoval,
89
noteActiveCronJobScheduleMutation,
910
resetCronActiveJobs,
1011
} from "./active-jobs.js";
@@ -48,6 +49,31 @@ describe("hasActiveCronJobsExceptMarker", () => {
4849
});
4950

5051
describe("active cron schedule ownership", () => {
52+
it("records durable job removal without releasing the active run marker", () => {
53+
const marker = markCronJobActive("removed-job");
54+
55+
noteActiveCronJobRemoval("removed-job");
56+
57+
expect(marker?.scheduleMutated).toBe(true);
58+
expect(marker?.jobRemoved).toBe(true);
59+
expect(hasActiveCronJobs()).toBe(true);
60+
});
61+
62+
it("does not mistake an ordinary schedule edit for job removal", () => {
63+
const marker = markCronJobActive("updated-job");
64+
65+
noteActiveCronJobScheduleMutation("updated-job");
66+
67+
expect(marker?.scheduleMutated).toBe(true);
68+
expect(marker?.jobRemoved).toBeUndefined();
69+
});
70+
71+
it("does not create active markers when removing an idle job", () => {
72+
noteActiveCronJobRemoval("idle-removed-job");
73+
74+
expect(hasActiveCronJobs()).toBe(false);
75+
});
76+
5177
it("records durable schedule mutations on the admitted active run", () => {
5278
const marker = markCronJobActive("rescheduled-job");
5379

‎src/cron/active-jobs.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export type CronActiveJobMarker = {
1616
generation: number;
1717
token: number;
1818
scheduleMutated?: true;
19+
jobRemoved?: true;
1920
legacy?: boolean;
2021
preserveAcrossGenerationAdvance?: boolean;
2122
};
@@ -133,6 +134,21 @@ export function noteActiveCronJobScheduleMutation(jobId: string): void {
133134
}
134135
}
135136

137+
/** Retires the admitted job identity after its deletion becomes durable. */
138+
export function noteActiveCronJobRemoval(jobId: string): void {
139+
if (!jobId) {
140+
return;
141+
}
142+
const state = getCronActiveJobState();
143+
const marker = state.activeJobs.get(jobId);
144+
if (marker && isMarkerActiveInGeneration(marker, state.generation)) {
145+
// A reused ID names a new job, not a reschedule of the old invocation.
146+
// Keep its marker until completion so duplicate-run guards remain intact.
147+
marker.scheduleMutated = true;
148+
marker.jobRemoved = true;
149+
}
150+
}
151+
136152
/** Returns whether the given cron job id is currently executing in this process. */
137153
export function isCronJobActive(jobId: string) {
138154
if (!jobId) {

‎src/cron/service.one-shot-schedule-ownership.test.ts‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,11 @@ async function addOneShot(params: {
4141
cron: CronService;
4242
name: string;
4343
atMs: number;
44+
id?: string;
4445
deleteAfterRun?: boolean;
4546
}) {
4647
return await params.cron.add({
48+
...(params.id === undefined ? {} : { id: params.id }),
4749
name: params.name,
4850
enabled: true,
4951
...(params.deleteAfterRun === undefined ? {} : { deleteAfterRun: params.deleteAfterRun }),
@@ -83,6 +85,105 @@ async function expectFutureOneShot(params: {
8385
}
8486

8587
describe("cron one-shot schedule ownership", () => {
88+
it.each([
89+
{ mode: "direct", deleteAfterRun: false },
90+
{ mode: "direct", deleteAfterRun: true },
91+
{ mode: "queued", deleteAfterRun: false },
92+
{ mode: "queued", deleteAfterRun: true },
93+
] as const)(
94+
"does not finalize an active $mode run into a removed and recreated one-shot (deleteAfterRun=$deleteAfterRun)",
95+
async ({ mode, deleteAfterRun }) => {
96+
const store = await makeStorePath();
97+
const started = createDeferred<void>();
98+
const release = createDeferred<{ status: "ok"; summary: string }>();
99+
const finished = createDeferred<void>();
100+
const events: CronEvent[] = [];
101+
const cron = createCron({
102+
storePath: store.storePath,
103+
runIsolatedAgentJob: vi.fn(async () => {
104+
started.resolve();
105+
return await release.promise;
106+
}),
107+
onEvent: (event) => {
108+
events.push(event);
109+
if (event.action === "finished") {
110+
finished.resolve();
111+
}
112+
},
113+
});
114+
115+
try {
116+
await cron.start();
117+
const atMs = Date.now() + 60 * 60_000;
118+
const original = await addOneShot({
119+
cron,
120+
id: `removed-active-${mode}-${deleteAfterRun}`,
121+
name: "removed original one-shot",
122+
atMs,
123+
deleteAfterRun,
124+
});
125+
const directRun = mode === "direct" ? cron.run(original.id, "force") : undefined;
126+
if (mode === "queued") {
127+
await expect(cron.enqueueRun(original.id, "force")).resolves.toMatchObject({
128+
ok: true,
129+
enqueued: true,
130+
});
131+
}
132+
await started.promise;
133+
134+
await expect(cron.remove(original.id)).resolves.toEqual({ ok: true, removed: true });
135+
await addOneShot({
136+
cron,
137+
id: original.id,
138+
name: "independent replacement one-shot",
139+
atMs,
140+
deleteAfterRun,
141+
});
142+
143+
release.resolve({ status: "ok", summary: "original run finished" });
144+
if (directRun) {
145+
await expect(directRun).resolves.toEqual({ ok: true, ran: true });
146+
} else {
147+
await finished.promise;
148+
}
149+
await cron.status();
150+
151+
for (const jobs of [
152+
await cron.list({ includeDisabled: true }),
153+
(await loadCronStore(store.storePath)).jobs,
154+
]) {
155+
const replacement = jobs.find((job) => job.id === original.id);
156+
expect(replacement).toMatchObject({
157+
id: original.id,
158+
name: "independent replacement one-shot",
159+
enabled: true,
160+
deleteAfterRun,
161+
state: { nextRunAtMs: atMs },
162+
});
163+
expect(replacement?.state.lastRunAtMs).toBeUndefined();
164+
expect(replacement?.state.lastRunStatus).toBeUndefined();
165+
expect(replacement?.state.lastStatus).toBeUndefined();
166+
expect(replacement?.state.runningAtMs).toBeUndefined();
167+
}
168+
169+
if (mode === "queued") {
170+
expect(
171+
events.filter((event) => event.action === "finished" && event.jobId === original.id),
172+
).toEqual([
173+
expect.objectContaining({
174+
status: "ok",
175+
summary: "original run finished",
176+
job: expect.objectContaining({ name: "removed original one-shot" }),
177+
}),
178+
]);
179+
}
180+
} finally {
181+
release.resolve({ status: "ok", summary: "original run finished" });
182+
cron.stop();
183+
}
184+
},
185+
);
186+
86187
it.each([
87188
{ label: "successful", outcome: { status: "ok", summary: "done" } },
88189
{ label: "failed", outcome: { status: "error", error: "temporary provider failure" } },

‎src/cron/service/ops-mutations.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@ import {
44
AgentDeletionAuthorityRollbackError,
55
AgentDeletionCommitUncertainError,
66
} from "../../agents/agent-lifecycle-registry.js";
7-
import { isCronJobActive, noteActiveCronJobScheduleMutation } from "../active-jobs.js";
7+
import {
8+
isCronJobActive,
9+
noteActiveCronJobRemoval,
10+
noteActiveCronJobScheduleMutation,
11+
} from "../active-jobs.js";
812
import { cronSchedulingInputsEqual } from "../schedule-identity.js";
913
import { deleteCronJobScratch } from "../scratch-store.js";
1014
import { createCronStreamSourceIdentity, cronStreamScheduleKey } from "../stream-schedule.js";
@@ -407,6 +411,7 @@ export async function remove(
407411
suppressScheduledJobId: id,
408412
});
409413
if (removed) {
414+
noteActiveCronJobRemoval(id);
410415
try {
411416
deleteCronJobScratch(state.deps.storePath, id);
412417
} catch (error) {
@@ -456,6 +461,7 @@ export async function removeAgentJobsTransactional<T>(
456461
if (error instanceof AgentDeletionCommitUncertainError) {
457462
armTimer(state);
458463
for (const job of removedJobs) {
464+
noteActiveCronJobRemoval(job.id);
459465
emit(state, { jobId: job.id, action: "removed", job });
460466
}
461467
throw error;
@@ -477,6 +483,7 @@ export async function removeAgentJobsTransactional<T>(
477483
throw error;
478484
}
479485
for (const job of removedJobs) {
486+
noteActiveCronJobRemoval(job.id);
480487
try {
481488
deleteCronJobScratch(state.deps.storePath, job.id);
482489
} catch (error) {

‎src/cron/service/ops-run.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,10 @@ async function finishPreparedManualRun(
8383
if (!tracker || tracker.emitted) {
8484
return;
8585
}
86-
const job = state.store?.jobs.find((entry) => entry.id === jobId);
86+
const job =
87+
prepared.activeJobMarker?.jobRemoved === true
88+
? executionJob
89+
: state.store?.jobs.find((entry) => entry.id === jobId);
8790
// enqueueRun acknowledges a concrete run id, so every accepted request
8891
// needs one terminal event even if the job or service owner changes mid-run.
8992
emitCronRunFinished(
@@ -140,7 +143,10 @@ async function finishPreparedManualRun(
140143
let notifySetupTimeout = coreResult.isolatedAgentSetupTimeout !== undefined;
141144
await locked(state, async () => {
142145
await ensureLoaded(state, { skipRecompute: true });
143-
if (!isCronActiveJobMarkerCurrent(prepared.activeJobMarker)) {
146+
if (
147+
!isCronActiveJobMarkerCurrent(prepared.activeJobMarker) ||
148+
prepared.activeJobMarker?.jobRemoved === true
149+
) {
144150
notifySetupTimeout = false;
145151
return;
146152
}

‎src/cron/service/timer-outcomes.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -541,7 +541,7 @@ export function applyOutcomeToStoredJob(
541541
}
542542
const jobs = store.jobs;
543543
const job = jobs.find((entry) => entry.id === result.jobId);
544-
if (!job) {
544+
if (!job || result.activeJobMarker?.jobRemoved === true) {
545545
if (result.status === "ok" && result.triggerEval?.fired === false) {
546546
tryFinishCronTaskRunWithoutHistory(state, result);
547547
return undefined;

‎src/cron/service/timer.batch-finalization.test.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { isCronJobActive, markCronJobActive } from "../active-jobs.js";
1313
import * as cronStoreModule from "../store.js";
1414
import { loadCronStore, saveCronStore } from "../store.js";
1515
import type { CronJob } from "../types.js";
16+
import { add, remove } from "./ops-mutations.js";
1617
import { createCronServiceState } from "./state.js";
1718
import {
1819
createCompletedCronRunOutcomeDrain,
@@ -69,6 +70,90 @@ function findCronTask(jobId: string) {
6970
}
7071

7172
describe("cron batch outcome finalization", () => {
73+
it.each([
74+
{ trigger: "scheduled", deleteAfterRun: false },
75+
{ trigger: "scheduled", deleteAfterRun: true },
76+
{ trigger: "startup", deleteAfterRun: false },
77+
{ trigger: "startup", deleteAfterRun: true },
78+
] as const)(
79+
"does not apply a removed $trigger run to a same-id replacement (deleteAfterRun=$deleteAfterRun)",
80+
async ({ trigger, deleteAfterRun }) => {
81+
const store = fixtures.makeStorePath();
82+
const dueAt = Date.parse("2026-02-06T10:05:00.750Z");
83+
const replacementAt = dueAt + 60 * 60_000;
84+
const original = createDueIsolatedJob({
85+
id: `removed-${trigger}-replacement-${deleteAfterRun}`,
86+
nowMs: dueAt,
87+
nextRunAtMs: dueAt,
88+
deleteAfterRun,
89+
});
90+
original.name = "removed original scheduled job";
91+
await saveCronStore(store.storePath, { version: 1, jobs: [original] });
92+
93+
const started = createDeferred<void>();
94+
const release = createDeferred<{ status: "ok"; summary: string }>();
95+
const events: Array<{ action: string; jobId: string; job?: CronJob }> = [];
96+
const state = createBatchState({
97+
storePath: store.storePath,
98+
nowMs: dueAt,
99+
runIsolatedAgentJob: vi.fn(async () => {
100+
started.resolve();
101+
return await release.promise;
102+
}),
103+
onEvent: (event) => events.push(event),
104+
});
105+
const batch = startBatch(trigger, state);
106+
107+
try {
108+
await started.promise;
109+
await expect(remove(state, original.id)).resolves.toEqual({ ok: true, removed: true });
110+
await add(state, {
111+
id: original.id,
112+
name: "independent replacement scheduled job",
113+
enabled: true,
114+
deleteAfterRun,
115+
schedule: { kind: "at", at: new Date(replacementAt).toISOString() },
116+
sessionTarget: "isolated",
117+
wakeMode: "next-heartbeat",
118+
payload: { kind: "agentTurn", message: "run only the replacement occurrence" },
119+
delivery: { mode: "none" },
120+
});
121+
122+
release.resolve({ status: "ok", summary: "removed original completed" });
123+
await batch;
124+
125+
for (const jobs of [state.store?.jobs ?? [], (await loadCronStore(store.storePath)).jobs]) {
126+
const replacement = jobs.find((job) => job.id === original.id);
127+
expect(replacement).toMatchObject({
128+
id: original.id,
129+
name: "independent replacement scheduled job",
130+
enabled: true,
131+
deleteAfterRun,
132+
state: { nextRunAtMs: replacementAt },
133+
});
134+
expect(replacement?.state.lastRunAtMs).toBeUndefined();
135+
expect(replacement?.state.lastRunStatus).toBeUndefined();
136+
expect(replacement?.state.lastStatus).toBeUndefined();
137+
expect(replacement?.state.runningAtMs).toBeUndefined();
138+
}
139+
expect(
140+
events.filter((event) => event.action === "finished" && event.jobId === original.id),
141+
).toEqual([
142+
expect.objectContaining({
143+
job: expect.objectContaining({ name: "removed original scheduled job" }),
144+
}),
145+
]);
146+
expect(isCronJobActive(original.id)).toBe(false);
147+
} finally {
148+
release.resolve({ status: "ok", summary: "removed original completed" });
149+
await batch;
150+
if (state.timer) {
151+
clearTimeout(state.timer);
152+
}
153+
}
154+
},
155+
);
156+
72157
it("coalesces simultaneously finished outcomes into one durable write", async () => {
73158
const store = fixtures.makeStorePath();
74159
const dueAt = Date.parse("2026-02-06T10:05:01.000Z");

0 commit comments

Comments
 (0)