Repository navigation
Description
runCronJob in packages/modelence/src/cron/jobs.ts sets state.isRunning = true and then writes lastStartDate to Mongo before entering its try/catch:
async function runCronJob(job: CronJob) {
const { alias, params, handler, state } = job;
state.isRunning = true;
state.startTs = Date.now();
await cronJobsCollection.upsertOne( // <-- outside the try
{ alias },
{ $set: { lastStartDate: new Date(state.startTs) }, $setOnInsert: { alias } }
);
const transaction = startTransaction('cron', cron:${alias});
try {
await handler();
handleCronJobCompletion(state, params);
// ...
} catch (err) {
handleCronJobCompletion(state, params);
// ...
}
}
upsertOne delegates to collection.updateOne, which rejects on write failure — primary stepdown, network blip, write concern timeout, auth expiry. When that happens, state.isRunning has already been set to true but handleCronJobCompletion never runs, so it is never reset.
Impact: the job is then skipped on every subsequent tick by the state.isRunning guard in tickCronJobs, until the timeout branch at jobs.ts:112 clears the flag. That takes up to params.timeout, which defaults to interval clamped to 1min–1day. For a job with a long interval, a single transient Mongo write failure silently stalls it for hours. It does eventually self-heal, and nothing crashes — server.ts:164 installs a global unhandledRejection handler, so the rejection is logged rather than terminating the process. But the stall is silent from the job's perspective: there's no indication the run was skipped rather than completed.
Suggested fix: move the upsertOne call inside the existing try/catch so that handleCronJobCompletion(state, params) runs on that path too.
Worth deciding explicitly whether a failed bookkeeping write should abort the run or just log and proceed to handler(). I'd lean toward proceeding — the handler is the actual work, and lastStartDate only affects scheduling after a restart. A missed write means the job may re-run sooner than intended on next boot, which is the milder failure.
Testing: a unit test mocking cronJobsCollection.upsertOne to reject, asserting that state.isRunning is back to false afterwards and that the job is picked up on the following tick.
Activity