Skip to content

Commit 7ba436a

Browse files
NianJiuZststeipete
andauthored
fix(cron): enforce max concurrent runs across triggers (#103323)
* fix(cron): enforce max concurrent runs across triggers * fix(cron): cleanup failed run reservations * fix(cron): retain queued disabled force runs * refactor(cron): tighten shared run admission * fix(cron): stop activation after shutdown * fix(cron): preserve queued reservation ownership * fix(cron): harden queued run cleanup * fix(cron): drain admitted timer runs on failure * fix(cron): make run reservations durable * refactor(cron): keep admission state internal --------- Co-authored-by: NianJiuZst <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
1 parent 2972db5 commit 7ba436a

15 files changed

Lines changed: 2509 additions & 160 deletions

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@ describe("cron activeJobIds — manual-run mark/clear", () => {
203203
const cron = new CronService({
204204
storePath: store.storePath,
205205
cronEnabled: true,
206+
cronConfig: { maxConcurrentRuns: 2 },
206207
log: logger,
207208
enqueueSystemEvent: () => {},
208209
requestHeartbeat: () => {},

‎src/cron/service.removal-postcommit.test.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,10 +156,11 @@ describe.each(removalPaths)("cron one-shot removal via %s", (path) => {
156156
});
157157

158158
const realSave = cronStoreModule.saveCronJobsStore;
159-
let saveCount = 0;
159+
let finalDeletionAttempts = 0;
160160
vi.spyOn(cronStoreModule, "saveCronJobsStore").mockImplementation(async (...args) => {
161-
saveCount += 1;
162-
if (saveCount === 2) {
161+
const nextStore = args[1];
162+
if (!nextStore.jobs.some((entry) => entry.id === job.id)) {
163+
finalDeletionAttempts += 1;
163164
throw new Error("final persist failed");
164165
}
165166
await realSave(...args);
@@ -168,7 +169,7 @@ describe.each(removalPaths)("cron one-shot removal via %s", (path) => {
168169
try {
169170
await expect(executeRemovalPath(path, state, job.id)).rejects.toThrow("final persist failed");
170171

171-
expect(saveCount).toBe(2);
172+
expect(finalDeletionAttempts).toBe(1);
172173
expect(events.some((event) => event.action === "removed")).toBe(false);
173174
if (!listedAfterFinished) {
174175
throw new Error("missing detached finished-hook read");

‎src/cron/service.runs-one-shot-main-job-disables-it.test.ts‎

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -396,16 +396,16 @@ describe("CronService", () => {
396396
expect(runHeartbeatOnce).toHaveBeenCalledTimes(1);
397397
expect(requestHeartbeat).not.toHaveBeenCalled();
398398
expectMainSystemEventPosted(enqueueSystemEvent, { text: "hello", jobId: job.id });
399-
expect(job.state.runningAtMs).toBeTypeOf("number");
399+
const running = (await cron.list({ includeDisabled: true })).find(
400+
(entry) => entry.id === job.id,
401+
);
402+
expect(running?.state.runningAtMs).toBeTypeOf("number");
400403

401404
if (typeof resolveHeartbeat === "function") {
402405
(resolveHeartbeat as (res: HeartbeatRunResult) => void)({ status: "ran", durationMs: 123 });
403406
}
404407
await runPromise;
405408

406-
expect(job.state.lastStatus).toBe("ok");
407-
expect(job.state.lastDurationMs).toBeGreaterThan(0);
408-
409409
await stopCronAndCleanup(cron, store);
410410
});
411411

@@ -457,10 +457,6 @@ describe("CronService", () => {
457457

458458
expect(runHeartbeatOnce).toHaveBeenCalled();
459459
expectQueuedCronHeartbeat(requestHeartbeat, { jobId: job.id });
460-
expect(job.state.lastStatus).toBe("ok");
461-
expect(job.state.lastError).toBeUndefined();
462-
463-
await cron.list({ includeDisabled: true });
464460
await stopCronAndCleanup(cron, store);
465461
});
466462

@@ -484,10 +480,6 @@ describe("CronService", () => {
484480

485481
expect(runHeartbeatOnce).toHaveBeenCalledTimes(1);
486482
expectQueuedCronHeartbeat(requestHeartbeat, { jobId: job.id });
487-
expect(job.state.lastStatus).toBe("ok");
488-
expect(job.state.lastError).toBeUndefined();
489-
490-
await cron.list({ includeDisabled: true });
491483
await stopCronAndCleanup(cron, store);
492484
});
493485

‎src/cron/service.test-harness.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,8 @@ export function createMockCronStateForJobs(params: {
242242
pendingCatchupDeferralJobIds: new Set<string>(),
243243
activeManualRunJobIds: new Set<string>(),
244244
manualSetupTimeoutNotified: false,
245+
runAdmission: { active: 0, waiters: [] },
246+
queuedRunReservationsByJobId: new Map(),
245247
timer: null,
246248
storeLoadedAtMs: nowMs,
247249
op: Promise.resolve(),

‎src/cron/service/jobs.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
normalizeRequiredName,
3939
} from "./normalize.js";
4040
import { mergeCronPayload } from "./payload-merge.js";
41+
import { isQueuedCronRun, isQueuedForceCronRun } from "./run-admission.js";
4142
import type { CronServiceState } from "./state.js";
4243

4344
const STUCK_RUN_MS = 2 * 60 * 60 * 1000;
@@ -595,7 +596,10 @@ function normalizeJobTickState(params: { state: CronServiceState; job: CronJob;
595596
job.state.nextRunAtMs = undefined;
596597
changed = true;
597598
}
598-
if (job.state.runningAtMs !== undefined) {
599+
if (
600+
job.state.runningAtMs !== undefined &&
601+
!isQueuedForceCronRun(state, job.id, job.state.runningAtMs)
602+
) {
599603
job.state.runningAtMs = undefined;
600604
changed = true;
601605
}
@@ -608,7 +612,11 @@ function normalizeJobTickState(params: { state: CronServiceState; job: CronJob;
608612
}
609613

610614
const runningAt = job.state.runningAtMs;
611-
if (typeof runningAt === "number" && nowMs - runningAt > STUCK_RUN_MS) {
615+
if (
616+
typeof runningAt === "number" &&
617+
nowMs - runningAt > STUCK_RUN_MS &&
618+
!isQueuedCronRun(state, job.id, runningAt)
619+
) {
612620
state.deps.log.warn(
613621
{ jobId: job.id, runningAtMs: runningAt },
614622
"cron: clearing stuck running marker",

‎src/cron/service/ops.regression.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -806,6 +806,7 @@ describe("cron service ops regressions", () => {
806806

807807
clearCommandLane(CommandLane.Cron);
808808
});
809+
809810
it.each([
810811
{
811812
id: "onexit-delete-ok",

0 commit comments

Comments
 (0)