Skip to content

Commit fd267b2

Browse files
committed
fix(cron): protect schedule activation ownership
1 parent 03200c9 commit fd267b2

6 files changed

Lines changed: 180 additions & 5 deletions

File tree

‎packages/gateway-protocol/src/schema/cron.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,7 @@ const CronFailureNotificationDeliverySchema = closedObject({
432432
/** Scheduler-maintained state for the latest run/delivery outcome. */
433433
export const CronJobStateSchema = closedObject({
434434
nextRunAtMs: Type.Optional(Type.Integer({ minimum: 0 })),
435+
scheduleActivatedAtMs: Type.Optional(Type.Integer({ minimum: 0 })),
435436
runningAtMs: Type.Optional(Type.Integer({ minimum: 0 })),
436437
lastRunAtMs: Type.Optional(Type.Integer({ minimum: 0 })),
437438
lastRunStatus: Type.Optional(CronRunStatusSchema),

‎src/cron/cron-protocol-schema.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,16 @@ describe("cron protocol schema", () => {
4040
expect(patchStateProperties.streamSourceIdentity).toBeUndefined();
4141
});
4242

43+
it("reports schedule activation without accepting it in state patches", () => {
44+
const stateProperties = (CronJobStateSchema as SchemaLike).properties ?? {};
45+
expect(stateProperties.scheduleActivatedAtMs).toBeDefined();
46+
47+
const updateProperties = (CronUpdateParamsSchema as SchemaLike).properties ?? {};
48+
const patchProperties = (updateProperties.patch as SchemaLike | undefined)?.properties ?? {};
49+
const patchState = patchProperties.state as SchemaLike | undefined;
50+
expect(patchState?.properties?.scheduleActivatedAtMs).toBeUndefined();
51+
});
52+
4353
it("documents that pacing requires at least one bound", () => {
4454
expect((CronPacingSchema as SchemaLike).description).toContain(
4555
"at least one of min or max is required",

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

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,17 @@ describe("CronService restart catch-up after a schedule change", () => {
5757
await editor.update(jobId, {
5858
schedule: { kind: "cron", expr: "0 21 * * *", tz: "Europe/Istanbul" },
5959
});
60+
const activatedAtMs = Date.parse("2026-07-28T07:18:00.000Z");
61+
expect(editor.getJob(jobId)?.state.scheduleActivatedAtMs).toBe(activatedAtMs);
62+
63+
vi.setSystemTime(new Date("2026-07-28T08:18:00.000Z"));
64+
await editor.update(jobId, { name: "renamed daily briefing" });
65+
await editor.update(jobId, {
66+
schedule: { kind: "cron", expr: "0 21 * * *", tz: "Europe/Istanbul" },
67+
});
68+
const idempotentlyUpdated = editor.getJob(jobId);
69+
expect(idempotentlyUpdated?.state.scheduleActivatedAtMs).toBe(activatedAtMs);
70+
expect(idempotentlyUpdated?.updatedAtMs).toBe(Date.parse("2026-07-28T08:18:00.000Z"));
6071
} finally {
6172
editor.stop();
6273
}
@@ -79,4 +90,108 @@ describe("CronService restart catch-up after a schedule change", () => {
7990
await store.cleanup();
8091
}
8192
});
93+
94+
it("runs a genuine missed slot that occurred after schedule activation", async () => {
95+
const store = await makeStorePath();
96+
const runCommandJob = vi.fn(async () => ({ status: "ok" as const, summary: "done" }));
97+
const now = Date.parse("2026-07-30T13:18:00.000Z");
98+
await writeCronStoreSnapshot({
99+
storePath: store.storePath,
100+
jobs: [
101+
{
102+
id: "restart-post-activation-slot",
103+
name: "daily briefing",
104+
enabled: true,
105+
createdAtMs: Date.parse("2026-07-01T12:00:00.000Z"),
106+
updatedAtMs: Date.parse("2026-07-29T08:00:00.000Z"),
107+
schedule: { kind: "cron", expr: "0 12 * * *", tz: "UTC" },
108+
sessionTarget: "isolated",
109+
wakeMode: "next-heartbeat",
110+
payload: { kind: "command", argv: ["echo", "FIRED"] },
111+
state: {
112+
nextRunAtMs: Date.parse("2026-07-31T12:00:00.000Z"),
113+
lastRunAtMs: Date.parse("2026-07-28T12:00:00.000Z"),
114+
lastStatus: "ok",
115+
scheduleActivatedAtMs: Date.parse("2026-07-29T08:00:00.000Z"),
116+
},
117+
},
118+
],
119+
});
120+
const service = new CronService({
121+
storePath: store.storePath,
122+
cronEnabled: true,
123+
log: noopLogger,
124+
nowMs: () => now,
125+
enqueueSystemEvent: vi.fn(),
126+
requestHeartbeat: vi.fn(),
127+
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
128+
runCommandJob: runCommandJob as never,
129+
});
130+
131+
try {
132+
await service.start();
133+
134+
expect(runCommandJob).toHaveBeenCalledTimes(1);
135+
expect(service.getJob("restart-post-activation-slot")?.state.lastRunAtMs).toBe(now);
136+
} finally {
137+
service.stop();
138+
await store.cleanup();
139+
}
140+
});
141+
142+
it("preserves one legacy catch-up for an unstamped pre-upgrade job", async () => {
143+
const store = await makeStorePath();
144+
const runCommandJob = vi.fn(async () => ({ status: "ok" as const, summary: "done" }));
145+
const now = Date.parse("2026-07-30T13:18:00.000Z");
146+
await writeCronStoreSnapshot({
147+
storePath: store.storePath,
148+
jobs: [
149+
{
150+
id: "restart-legacy-unstamped-slot",
151+
name: "legacy daily briefing",
152+
enabled: true,
153+
createdAtMs: Date.parse("2026-07-01T12:00:00.000Z"),
154+
updatedAtMs: Date.parse("2026-07-29T08:00:00.000Z"),
155+
schedule: { kind: "cron", expr: "0 12 * * *", tz: "UTC" },
156+
sessionTarget: "isolated",
157+
wakeMode: "next-heartbeat",
158+
payload: { kind: "command", argv: ["echo", "FIRED"] },
159+
state: {
160+
nextRunAtMs: Date.parse("2026-07-31T12:00:00.000Z"),
161+
lastRunAtMs: Date.parse("2026-07-28T12:00:00.000Z"),
162+
lastStatus: "ok",
163+
},
164+
},
165+
],
166+
});
167+
const createService = () =>
168+
new CronService({
169+
storePath: store.storePath,
170+
cronEnabled: true,
171+
log: noopLogger,
172+
nowMs: () => now,
173+
enqueueSystemEvent: vi.fn(),
174+
requestHeartbeat: vi.fn(),
175+
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
176+
runCommandJob: runCommandJob as never,
177+
});
178+
179+
const firstRestart = createService();
180+
try {
181+
await firstRestart.start();
182+
expect(runCommandJob).toHaveBeenCalledTimes(1);
183+
expect(firstRestart.getJob("restart-legacy-unstamped-slot")?.state.lastRunAtMs).toBe(now);
184+
} finally {
185+
firstRestart.stop();
186+
}
187+
188+
const secondRestart = createService();
189+
try {
190+
await secondRestart.start();
191+
expect(runCommandJob).toHaveBeenCalledTimes(1);
192+
} finally {
193+
secondRestart.stop();
194+
await store.cleanup();
195+
}
196+
});
82197
});

‎src/cron/service/jobs.apply-patch.test.ts‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
import { describe, expect, it } from "vitest";
33
import { resolveCronDeliveryPlan, resolveFailureDestination } from "../delivery-plan.js";
44
import { projectCronJobThroughStorageCodec } from "../store/row-codec.js";
5-
import type { CronJob } from "../types.js";
6-
import { applyJobPatch } from "./jobs.js";
5+
import type { CronJob, CronJobCreate, CronJobPatch } from "../types.js";
6+
import { applyJobPatch, createJob } from "./jobs.js";
77

88
function makeJob(overrides: Partial<CronJob> = {}): CronJob {
99
const now = Date.now();
@@ -89,6 +89,44 @@ describe("applyJobPatch schedule retention", () => {
8989
});
9090
});
9191

92+
describe("schedule activation ownership", () => {
93+
it("ignores caller-supplied activation state during creation", () => {
94+
const now = Date.parse("2026-07-30T00:00:00.000Z");
95+
const input = {
96+
name: "owned activation",
97+
enabled: true,
98+
schedule: { kind: "cron", expr: "0 * * * *", tz: "UTC" },
99+
sessionTarget: "main",
100+
wakeMode: "now",
101+
payload: { kind: "systemEvent", text: "tick" },
102+
state: { scheduleActivatedAtMs: now - 60_000 },
103+
} as unknown as CronJobCreate;
104+
105+
const job = createJob(
106+
{
107+
deps: {
108+
nowMs: () => now,
109+
defaultAgentId: "main",
110+
},
111+
} as never,
112+
input,
113+
);
114+
115+
expect(job.state.scheduleActivatedAtMs).toBeUndefined();
116+
});
117+
118+
it("ignores caller-supplied activation state during updates", () => {
119+
const job = makeJob({ state: { scheduleActivatedAtMs: 456 } });
120+
const patch = {
121+
state: { scheduleActivatedAtMs: 123 },
122+
} as unknown as CronJobPatch;
123+
124+
applyJobPatch(job, patch);
125+
126+
expect(job.state.scheduleActivatedAtMs).toBe(456);
127+
});
128+
});
129+
92130
describe("applyJobPatch delivery merge", () => {
93131
it("threads explicit delivery threadId patches into delivery", () => {
94132
const job = makeJob();

‎src/cron/service/jobs.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import type {
2424
CronJob,
2525
CronJobCreate,
2626
CronJobPatch,
27+
CronJobState,
2728
} from "../types.js";
2829
import { resolveInitialCronDelivery } from "./initial-delivery.js";
2930
import {
@@ -172,6 +173,10 @@ export function createJob(
172173
const ownerAgentId = normalizeOptionalAgentId(input.owner?.agentId);
173174
const ownerSessionKey = normalizeOptionalString(input.owner?.sessionKey);
174175
const ownerAccountId = normalizeOptionalAccountId(input.owner?.accountId);
176+
const initialState = { ...input.state } as Partial<CronJobState>;
177+
// Schedule activation is stamped only by committed scheduling mutations.
178+
// Accepting caller state here would let imports spoof restart catch-up ownership.
179+
delete initialState.scheduleActivatedAtMs;
175180
const job: CronJob = {
176181
id,
177182
...(declarationKey ? { declarationKey } : {}),
@@ -205,7 +210,7 @@ export function createJob(
205210
failureAlert: input.failureAlert,
206211
...(input.trigger ? { trigger: structuredClone(input.trigger) } : {}),
207212
state: {
208-
...input.state,
213+
...initialState,
209214
...(schedule.kind === "stream"
210215
? { streamSourceIdentity: createCronStreamSourceIdentity() }
211216
: {}),
@@ -376,7 +381,11 @@ export function applyJobPatch(
376381
: undefined;
377382
}
378383
if (patch.state) {
379-
job.state = { ...job.state, ...patch.state };
384+
const statePatch = { ...patch.state } as Partial<CronJobState>;
385+
// Runtime state patches may report execution progress, but the scheduler
386+
// alone owns the boundary that decides whether restart catch-up can run.
387+
delete statePatch.scheduleActivatedAtMs;
388+
job.state = { ...job.state, ...statePatch };
380389
}
381390
if ("agentId" in patch) {
382391
job.agentId = normalizeOptionalAgentId((patch as { agentId?: unknown }).agentId);

‎src/cron/types.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,9 @@ export type CronStoreFile = {
486486
jobs: CronJob[];
487487
};
488488

489-
type CronJobStateInput = Partial<Omit<CronJobState, "streamSourceIdentity">>;
489+
type CronJobStateInput = Partial<
490+
Omit<CronJobState, "scheduleActivatedAtMs" | "streamSourceIdentity">
491+
>;
490492

491493
/** Create input accepted by cron APIs before id/timestamps/state are assigned. */
492494
export type CronJobCreate = Omit<

0 commit comments

Comments
 (0)