|
| 1 | +import { describe, expect, it, vi } from "vitest"; |
| 2 | +import { |
| 3 | + clearCommandLane, |
| 4 | + enqueueCommandInLane, |
| 5 | + setCommandLaneConcurrency, |
| 6 | +} from "../process/command-queue.js"; |
| 7 | +import { CommandLane } from "../process/lanes.js"; |
| 8 | +import { CronService } from "./service.js"; |
| 9 | +import { createDeferred, setupCronServiceSuite } from "./service.test-harness.js"; |
| 10 | +import type { CronEvent, CronServiceDeps } from "./service/state.js"; |
| 11 | +import { loadCronStore } from "./store.js"; |
| 12 | + |
| 13 | +const { logger, makeStorePath } = setupCronServiceSuite({ |
| 14 | + prefix: "cron-one-shot-schedule-ownership-", |
| 15 | + baseTimeIso: "2026-07-27T12:00:00.000Z", |
| 16 | +}); |
| 17 | + |
| 18 | +type IsolatedOutcome = |
| 19 | + | { status: "ok"; summary: string } |
| 20 | + | { status: "error"; error: string } |
| 21 | + | { status: "skipped"; error: string }; |
| 22 | + |
| 23 | +function createCron(params: { |
| 24 | + storePath: string; |
| 25 | + runIsolatedAgentJob: CronServiceDeps["runIsolatedAgentJob"]; |
| 26 | + onEvent?: (event: CronEvent) => void; |
| 27 | +}) { |
| 28 | + return new CronService({ |
| 29 | + storePath: params.storePath, |
| 30 | + cronEnabled: true, |
| 31 | + log: logger, |
| 32 | + enqueueSystemEvent: vi.fn(), |
| 33 | + requestHeartbeat: vi.fn(), |
| 34 | + runIsolatedAgentJob: params.runIsolatedAgentJob, |
| 35 | + ...(params.onEvent ? { onEvent: params.onEvent } : {}), |
| 36 | + }); |
| 37 | +} |
| 38 | + |
| 39 | +async function addOneShot(params: { |
| 40 | + cron: CronService; |
| 41 | + name: string; |
| 42 | + atMs: number; |
| 43 | + deleteAfterRun?: boolean; |
| 44 | +}) { |
| 45 | + return await params.cron.add({ |
| 46 | + name: params.name, |
| 47 | + enabled: true, |
| 48 | + ...(params.deleteAfterRun === undefined ? {} : { deleteAfterRun: params.deleteAfterRun }), |
| 49 | + schedule: { kind: "at", at: new Date(params.atMs).toISOString() }, |
| 50 | + sessionTarget: "isolated", |
| 51 | + wakeMode: "next-heartbeat", |
| 52 | + payload: { kind: "agentTurn", message: "verify one-shot schedule ownership" }, |
| 53 | + delivery: { mode: "none" }, |
| 54 | + }); |
| 55 | +} |
| 56 | + |
| 57 | +async function expectFutureOneShot(params: { |
| 58 | + cron: CronService; |
| 59 | + storePath: string; |
| 60 | + jobId: string; |
| 61 | + atMs: number; |
| 62 | + status: IsolatedOutcome["status"]; |
| 63 | +}) { |
| 64 | + const expected = { |
| 65 | + id: params.jobId, |
| 66 | + enabled: true, |
| 67 | + schedule: { kind: "at", at: new Date(params.atMs).toISOString() }, |
| 68 | + state: { |
| 69 | + lastRunStatus: params.status, |
| 70 | + lastStatus: params.status, |
| 71 | + nextRunAtMs: params.atMs, |
| 72 | + }, |
| 73 | + }; |
| 74 | + const listed = await params.cron.list({ includeDisabled: true }); |
| 75 | + const listedJob = listed.find((job) => job.id === params.jobId); |
| 76 | + expect(listedJob).toMatchObject(expected); |
| 77 | + expect(listedJob?.state.runningAtMs).toBeUndefined(); |
| 78 | + const durable = await loadCronStore(params.storePath); |
| 79 | + const durableJob = durable.jobs.find((job) => job.id === params.jobId); |
| 80 | + expect(durableJob).toMatchObject(expected); |
| 81 | + expect(durableJob?.state.runningAtMs).toBeUndefined(); |
| 82 | +} |
| 83 | + |
| 84 | +describe("cron one-shot schedule ownership", () => { |
| 85 | + it.each([ |
| 86 | + { label: "successful", outcome: { status: "ok", summary: "done" } }, |
| 87 | + { label: "failed", outcome: { status: "error", error: "temporary provider failure" } }, |
| 88 | + { label: "skipped", outcome: { status: "skipped", error: "temporarily unavailable" } }, |
| 89 | + ] satisfies Array<{ label: string; outcome: IsolatedOutcome }>)( |
| 90 | + "keeps the future scheduled fire after a $label manual run", |
| 91 | + async ({ outcome }) => { |
| 92 | + const store = await makeStorePath(); |
| 93 | + const events: CronEvent[] = []; |
| 94 | + const cron = createCron({ |
| 95 | + storePath: store.storePath, |
| 96 | + runIsolatedAgentJob: vi.fn(async () => outcome), |
| 97 | + onEvent: (event) => events.push(event), |
| 98 | + }); |
| 99 | + |
| 100 | + try { |
| 101 | + await cron.start(); |
| 102 | + const atMs = Date.now() + 60 * 60_000; |
| 103 | + const job = await addOneShot({ cron, name: `manual ${outcome.status}`, atMs }); |
| 104 | + |
| 105 | + await expect(cron.run(job.id, "force")).resolves.toEqual({ ok: true, ran: true }); |
| 106 | + |
| 107 | + await expectFutureOneShot({ |
| 108 | + cron, |
| 109 | + storePath: store.storePath, |
| 110 | + jobId: job.id, |
| 111 | + atMs, |
| 112 | + status: outcome.status, |
| 113 | + }); |
| 114 | + expect(events.some((event) => event.jobId === job.id && event.action === "removed")).toBe( |
| 115 | + false, |
| 116 | + ); |
| 117 | + } finally { |
| 118 | + cron.stop(); |
| 119 | + } |
| 120 | + }, |
| 121 | + ); |
| 122 | + |
| 123 | + it("keeps the future scheduled fire after a queued manual run", async () => { |
| 124 | + const store = await makeStorePath(); |
| 125 | + const finished = createDeferred<void>(); |
| 126 | + const events: CronEvent[] = []; |
| 127 | + const cron = createCron({ |
| 128 | + storePath: store.storePath, |
| 129 | + runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const, summary: "done" })), |
| 130 | + onEvent: (event) => { |
| 131 | + events.push(event); |
| 132 | + if (event.action === "finished") { |
| 133 | + finished.resolve(); |
| 134 | + } |
| 135 | + }, |
| 136 | + }); |
| 137 | + |
| 138 | + try { |
| 139 | + await cron.start(); |
| 140 | + const atMs = Date.now() + 60 * 60_000; |
| 141 | + const job = await addOneShot({ cron, name: "queued manual one-shot", atMs }); |
| 142 | + |
| 143 | + await expect(cron.enqueueRun(job.id, "force")).resolves.toMatchObject({ |
| 144 | + ok: true, |
| 145 | + enqueued: true, |
| 146 | + }); |
| 147 | + await finished.promise; |
| 148 | + await cron.status(); |
| 149 | + |
| 150 | + await expectFutureOneShot({ |
| 151 | + cron, |
| 152 | + storePath: store.storePath, |
| 153 | + jobId: job.id, |
| 154 | + atMs, |
| 155 | + status: "ok", |
| 156 | + }); |
| 157 | + expect(events.some((event) => event.jobId === job.id && event.action === "removed")).toBe( |
| 158 | + false, |
| 159 | + ); |
| 160 | + } finally { |
| 161 | + cron.stop(); |
| 162 | + } |
| 163 | + }); |
| 164 | + |
| 165 | + it("preserves a manual run accepted before its scheduled fire but admitted afterward", async () => { |
| 166 | + const store = await makeStorePath(); |
| 167 | + const finished = createDeferred<void>(); |
| 168 | + const blockerStarted = createDeferred<void>(); |
| 169 | + const releaseBlocker = createDeferred<void>(); |
| 170 | + const cron = createCron({ |
| 171 | + storePath: store.storePath, |
| 172 | + runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const, summary: "done" })), |
| 173 | + onEvent: (event) => { |
| 174 | + if (event.action === "finished") { |
| 175 | + finished.resolve(); |
| 176 | + } |
| 177 | + }, |
| 178 | + }); |
| 179 | + |
| 180 | + clearCommandLane(CommandLane.Cron); |
| 181 | + setCommandLaneConcurrency(CommandLane.Cron, 1); |
| 182 | + const blocker = enqueueCommandInLane(CommandLane.Cron, async () => { |
| 183 | + blockerStarted.resolve(); |
| 184 | + await releaseBlocker.promise; |
| 185 | + }); |
| 186 | + |
| 187 | + try { |
| 188 | + await blockerStarted.promise; |
| 189 | + await cron.start(); |
| 190 | + cron.pauseScheduling(); |
| 191 | + const atMs = Date.now() + 1_000; |
| 192 | + const job = await addOneShot({ cron, name: "manual queued across deadline", atMs }); |
| 193 | + |
| 194 | + await expect(cron.enqueueRun(job.id, "force")).resolves.toMatchObject({ |
| 195 | + ok: true, |
| 196 | + enqueued: true, |
| 197 | + }); |
| 198 | + vi.setSystemTime(new Date(atMs + 1)); |
| 199 | + releaseBlocker.resolve(); |
| 200 | + await blocker; |
| 201 | + await finished.promise; |
| 202 | + await cron.status(); |
| 203 | + |
| 204 | + await expectFutureOneShot({ |
| 205 | + cron, |
| 206 | + storePath: store.storePath, |
| 207 | + jobId: job.id, |
| 208 | + atMs, |
| 209 | + status: "ok", |
| 210 | + }); |
| 211 | + } finally { |
| 212 | + releaseBlocker.resolve(); |
| 213 | + await blocker; |
| 214 | + cron.stop(); |
| 215 | + clearCommandLane(CommandLane.Cron); |
| 216 | + } |
| 217 | + }); |
| 218 | + |
| 219 | + it("consumes a manually verified one-shot only when its scheduled occurrence fires", async () => { |
| 220 | + const store = await makeStorePath(); |
| 221 | + const removed = createDeferred<void>(); |
| 222 | + const runIsolatedAgentJob = vi.fn(async () => ({ |
| 223 | + status: "ok" as const, |
| 224 | + summary: "done", |
| 225 | + })); |
| 226 | + const cron = createCron({ |
| 227 | + storePath: store.storePath, |
| 228 | + runIsolatedAgentJob, |
| 229 | + onEvent: (event) => { |
| 230 | + if (event.action === "removed") { |
| 231 | + removed.resolve(); |
| 232 | + } |
| 233 | + }, |
| 234 | + }); |
| 235 | + |
| 236 | + try { |
| 237 | + await cron.start(); |
| 238 | + const atMs = Date.now() + 1_000; |
| 239 | + const job = await addOneShot({ cron, name: "manual then scheduled one-shot", atMs }); |
| 240 | + |
| 241 | + await expect(cron.run(job.id, "force")).resolves.toEqual({ ok: true, ran: true }); |
| 242 | + expect(runIsolatedAgentJob).toHaveBeenCalledTimes(1); |
| 243 | + await expectFutureOneShot({ |
| 244 | + cron, |
| 245 | + storePath: store.storePath, |
| 246 | + jobId: job.id, |
| 247 | + atMs, |
| 248 | + status: "ok", |
| 249 | + }); |
| 250 | + |
| 251 | + await vi.advanceTimersByTimeAsync(1_000); |
| 252 | + await removed.promise; |
| 253 | + await cron.status(); |
| 254 | + |
| 255 | + expect(runIsolatedAgentJob).toHaveBeenCalledTimes(2); |
| 256 | + expect( |
| 257 | + (await cron.list({ includeDisabled: true })).find((entry) => entry.id === job.id), |
| 258 | + ).toBe(undefined); |
| 259 | + expect((await loadCronStore(store.storePath)).jobs.find((entry) => entry.id === job.id)).toBe( |
| 260 | + undefined, |
| 261 | + ); |
| 262 | + } finally { |
| 263 | + cron.stop(); |
| 264 | + } |
| 265 | + }); |
| 266 | + |
| 267 | + it("preserves every scheduled one-shot in a concurrent queued manual batch", async () => { |
| 268 | + const store = await makeStorePath(); |
| 269 | + const completions = new Map<string, ReturnType<typeof createDeferred<void>>>(); |
| 270 | + const cron = createCron({ |
| 271 | + storePath: store.storePath, |
| 272 | + runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const, summary: "done" })), |
| 273 | + onEvent: (event) => { |
| 274 | + if (event.action === "finished") { |
| 275 | + completions.get(event.jobId)?.resolve(); |
| 276 | + } |
| 277 | + }, |
| 278 | + }); |
| 279 | + |
| 280 | + try { |
| 281 | + await cron.start(); |
| 282 | + const atMs = Date.now() + 60 * 60_000; |
| 283 | + const jobs = []; |
| 284 | + for (let index = 0; index < 24; index += 1) { |
| 285 | + const job = await addOneShot({ cron, name: `queued one-shot ${index}`, atMs }); |
| 286 | + completions.set(job.id, createDeferred<void>()); |
| 287 | + jobs.push(job); |
| 288 | + } |
| 289 | + |
| 290 | + const acknowledgements = await Promise.all( |
| 291 | + jobs.map(async (job) => await cron.enqueueRun(job.id, "force")), |
| 292 | + ); |
| 293 | + expect(acknowledgements).toHaveLength(jobs.length); |
| 294 | + for (const acknowledgement of acknowledgements) { |
| 295 | + expect(acknowledgement).toMatchObject({ ok: true, enqueued: true }); |
| 296 | + } |
| 297 | + await Promise.all([...completions.values()].map(async (completion) => completion.promise)); |
| 298 | + await cron.status(); |
| 299 | + |
| 300 | + const listed = await cron.list({ includeDisabled: true }); |
| 301 | + const durable = await loadCronStore(store.storePath); |
| 302 | + expect(listed).toHaveLength(jobs.length); |
| 303 | + expect(durable.jobs).toHaveLength(jobs.length); |
| 304 | + for (const job of jobs) { |
| 305 | + for (const stored of [listed, durable.jobs]) { |
| 306 | + expect(stored.find((entry) => entry.id === job.id)).toMatchObject({ |
| 307 | + id: job.id, |
| 308 | + enabled: true, |
| 309 | + state: { lastRunStatus: "ok", nextRunAtMs: atMs }, |
| 310 | + }); |
| 311 | + } |
| 312 | + } |
| 313 | + } finally { |
| 314 | + cron.stop(); |
| 315 | + } |
| 316 | + }); |
| 317 | +}); |
0 commit comments