Repository navigation
fix: add cron jobs to _modelenceCronJobs store - #279
Conversation
…s and sync test file
…s and sync test file
…s and sync test file
|
@omegascorp PR ready for review |
|
Thank you @AtulYadav25 , I'm checking PR, please remove |
|
After this update:
|
omegascorp
left a comment
There was a problem hiding this comment.
Thank you @AtulYadav25, I've added some comments
| return; | ||
| } | ||
|
|
||
| const hasLock = await acquireLock('cron-registration', { |
There was a problem hiding this comment.
I think we need to reuse the existing lock; having a second lock is not necessary, the call of registerNewCronJobs is already guarded by the lock
There was a problem hiding this comment.
I might be wrong 😅, but I didn't find any existing guard lock on call to registerNewCronJobs
In createIndexesAndMigrationsWithLock, I can see it holds a lock until that background index task completes, so if you meant that I should reuse this migration lock, I think I can move registerNewCronJobs inside createIndexesAndMigrationsWithLock
This aligns with your comment and I will remove the use of separate lock from registerNewCronJobs
| * This prevents duplicate entries and maintains an audit trail of when each | ||
| * cron job was first scheduled. | ||
| */ | ||
| export async function registerNewCronJobs() { |
There was a problem hiding this comment.
we need to cover the new function with tests
| } | ||
|
|
||
| const aliasSelector = { alias: { $in: aliasList } }; | ||
| const existingCronJobs = await cronJobsCollection.fetch(aliasSelector); |
There was a problem hiding this comment.
We need to make sure to add proper error handling here. What happens if one of those calls throws an error?
There was a problem hiding this comment.
I added try/catch in the function registerNewCronJobs()
try {
const aliasSelector = { alias: { $in: aliasList } };
const existingCronJobs = await cronJobsCollection.fetch(aliasSelector);
const existingCronJobAliases = new Set(existingCronJobs.map((job) => job.alias));
const insertItems = Object.values(cronJobs)
.filter((job) => !existingCronJobAliases.has(job.alias))
.map((job) => ({
alias: job.alias,
}));
if (insertItems.length > 0) {
await cronJobsCollection.insertMany(insertItems);
}
} catch (error) {
await releaseLock('cron-registration'); // Release lock so other instances (or a restart) can retry this .
throw error;
}Errors here will abort app startup.
…ted. Added Waiting function for other instances to wait untill the cron jobs are registered, in startCronJobs
8688bf5 to
0c1e39a
Compare
|
Summary:: @omegascorp With this commit, Other instances now wait in And |
|
@AtulYadav25, sorry for the delay. I finally managed to take a look. Please check the bot's findings below the important part are issues number 1 and 2 |
modelence-ops
left a comment
There was a problem hiding this comment.
Thanks for this — the core fix is correct and well-targeted: cron rows were never inserted, so startCronJobs fetched nothing and timestamps never persisted. Registering rows up front under the migrations lock and switching to a blocking unique index is a sound approach, and the test coverage is solid.
A few things worth addressing before merge (left as inline comments):
waitForCronJobsRegisteredblocks paths where registration never runs (no-MongoDB-URI especially) — a 30s stall on what was previously instant.- The 30s timeout expires silently — no log when aliases are still unregistered, making the failure mode invisible in prod.
- Crash-startup severity — a transient DB error during
registerNewCronJobs()now aborts all ofstartAppand releases the migrations lock, inconsistent with how index-creation failures are tolerated right next to it. Worth confirming that's intended. - Nit: the
try/catchinregisterNewCronJobsonly re-throws — it can be removed.
Nice touches: updateOne → upsertOne with $setOnInsert is the right defensive move, the blocking-then-background index ordering is correctly reasoned, and the vi.useFakeTimers({ toFake: ['setTimeout'] }) test changes correctly keep the new poll loop from hanging tests.
(Findings #1 and #2 are both new in this PR — waitForCronJobsRegistered doesn't exist on main.)
| } | ||
|
|
||
| export async function startCronJobs() { | ||
| if (cronJobsInterval) { |
There was a problem hiding this comment.
This blocking wait runs on paths where registration never happens. startCronJobs() is called unconditionally at the end of startApp, including:
- No MongoDB URI:
connect()andregisterNewCronJobs()are skipped entirely, so this polls a never-populated store for the full 30s before proceeding (regression — previously this path did a singlefetchand returned immediately). - Instances that don't hold the migrations lock: waiting for the lock-holder to register is the intended behavior here and is a real improvement — the only risk is the 30s ceiling if the lock-holder is slow or dies.
Consider skipping the wait when there's no Mongo URI (e.g. only wait when registration is actually expected to run).
| } | ||
| } catch (error) { | ||
| throw error; | ||
| } |
There was a problem hiding this comment.
The timeout expires silently. When the deadline passes without all aliases registered, this returns void with no log or error. startCronJobs then proceeds, the follow-up fetch returns fewer records, and those jobs silently fall back to scheduledRunTs = now. In production this failure mode would be invisible.
Suggest logging a warning when the deadline is hit, listing the aliases still missing — e.g.:
console.warn(
`Timed out after ${timeout}ms waiting for cron jobs to be registered: ${missing.join(', ')}`
);| return; | ||
| } | ||
|
|
||
| try { | ||
| const aliasSelector = { alias: { $in: aliasList } }; | ||
| const existingCronJobs = await cronJobsCollection.fetch(aliasSelector); | ||
| const existingCronJobAliases = new Set(existingCronJobs.map((job) => job.alias)); | ||
|
|
||
| const insertItems = Object.values(cronJobs) | ||
| .filter((job) => !existingCronJobAliases.has(job.alias)) | ||
| .map((job) => ({ | ||
| alias: job.alias, | ||
| })); | ||
|
|
||
| if (insertItems.length > 0) { |
There was a problem hiding this comment.
The try/catch here is a no-op — it only re-throws, which is identical to not catching at all. You can drop the try/catch wrapper entirely and let the body run directly.
Separately, since registerNewCronJobs only runs under the migrations lock, the read-then-insertMany is safe from concurrent inserts — worth a one-line comment noting it relies on that lock for mutual exclusion, since an ordered insertMany would abort on a duplicate-key error if that assumption ever changed.
| } | ||
| // registerNewCronJobs runs here — after the unique alias index is guaranteed | ||
| // to exist (cronJobsCollection is now blocking!) | ||
| await registerNewCronJobs(); |
There was a problem hiding this comment.
Design question on severity: because this await is inside the try block, a transient DB hiccup during cron registration now aborts the entire startApp (and releases the migrations lock, so other instances may proceed without migrations finished).
That's inconsistent with index creation right above/below it — createStoreIndexes catches failures via warnIndexCreationFailure and startup continues. Is crashing the whole app the intended severity for cron registration specifically? If not, consider catching + warning here to match the "continue startup on index failure" philosophy.
…added console warn when timeout of waitForCronJobsRegistered expires
…instances waiting for cron jobs registeration, the lock holder instances creates a doc of cron in _modelenceCronJobs with alias '_registration_status' with status and other instances verify as this flag to move on or keep polling
…ocs, to store current migrations lock acquiredAt as sessionToken. With this, other instances don't fetch the stale doc of _registration_status document
…itial lock acquisitions and stale locks.
modelence-ops
left a comment
There was a problem hiding this comment.
Following up on my earlier review (posting at Hayk's request). Two items to weigh before this merges — neither disputes the core fix, which is sound:
- An architectural-complexity question on the
waitForCronJobsRegisteredstartup barrier (inline oncron/jobs.ts). - A minor schema/back-compat nit on the new
_modelenceLocks.statusfield (inline onlock/db.ts).
…c, updated test cases
|
Thank you @modelence-ops & @omegascorp Good point The PR now has cleaner code:
|
modelence-ops
left a comment
There was a problem hiding this comment.
Re-reviewed at bb7acdd. This is exactly the simplification I was hoping for — dropping waitForCronJobsRegistered and the status-on-lock / sessionToken / _registration_status machinery collapses the whole race surface that drove most of the Bugbot findings, and (as traced in my earlier comment) it does so with no observable behavior change:
- New aliases insert
{ alias }with nolastStartDate, sostartCronJobsschedules them atnow— same as the no-record fallback. - Existing aliases already carry
lastStartDatefrom a prior boot; thegetMongodbUri()-gated fetch picks them up. - Cross-instance double-runs stay prevented by
acquireLock('cron', …)intickCronJobs, independent of scheduling skew.
That also resolves @omegascorp's "feels like a hack" concern about storing status on the lock doc, and my _modelenceLocks.status back-compat nit is moot now that lock/db.ts is untouched. The forEach(async …) → for…of await change in tickCronJobs is a real correctness win (the old form fired unawaited handlers and swallowed rejections), and the new coverage on registerNewCronJobs / isDuplicateKeyError / the no-Mongo path is solid. I've resolved my two prior threads.
Two minor things, neither blocking:
- The comment above
insertManysays an "ordered insertMany would abort on a duplicate-key error," but the call passes{ ordered: false }. Withordered: falsethe driver keeps going and surfaces dups viawriteErrors(whichisDuplicateKeyErrornow handles) — worth aligning the comment with the code. - Bugbot's "cron writes without unique index" edge (blocking index build fails → registration skipped, but
runCronJobstill upserts): in practice the singleacquireLock('cron')holder serializes those upserts, so duplicate alias docs shouldn't actually occur, and it self-heals once the index lands. Fine to leave as-is — just noting it's a conscious call.
Core fix is sound and the architecture is now where it should be. Leaving the merge call to @omegascorp / @eduard-piliposyan. Thanks @AtulYadav25 for pushing this through the cleanup.
There was a problem hiding this comment.
@AtulYadav25 the real bug here is the updateOne no-op in runCronJob - your upsertOne + $setOnInsert change should fix it completely. I don't think registerNewCronJobs is needed: a row without lastStartDate behaves the same as no row, so all the registration + blocking index + duplicate-key machinery has zero effect.
Can we please revert the tick loop change to sequential await - a slow job would block all others, and it's unrelated to this fix.
As for the getMongodbUri() guard, we don't really want to support a use case of running apps without a db, it's just not a Modelence priority. But if that's somehow the case, cron jobs should still not be supported, they require locks and persistence to properly run - let's switch to simply not start any cron jobs if there's no db.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 96543bb. Configure here.
| modules: [createTestModule({ name: '_System.evil' })], | ||
| }) | ||
| ).rejects.toThrow("Invalid module name: '_System.evil'"); | ||
| }); |
There was a problem hiding this comment.
Test expects missing module validation
Medium Severity
This test expects startApp to reject user modules whose names start with _system. (case-insensitive), but that check is never implemented — index.ts still only has a TODO. The test will fail in CI.
Reviewed by Cursor Bugbot for commit 96543bb. Configure here.
…nd unrelated test
|
Thanks @artahian ,catching this I pulled out all the extra stuff Tested locally in a Modelence app and confirmed jobs get added to I pushed the clean version commit |
omegascorp
left a comment
There was a problem hiding this comment.
@AtulYadav25 it finally looks.
Considering as done, the latest change looks good


Added a new
registerNewCronJobs()function that initializes cron job records in the MongoDB store when the application starts.Problem
Previously, when modelence app is started and
startCronJobs()executed frommodelence/src/cron/jobs.ts, it attempted to fetch cron job records from the database.But, these records were never inserted into the database, so these resulted the fetch operation to fail silently and preventing proper initialization of job scheduling timestamps.
Before:
Solution
Added
registerNewCronJobs()which:aliasThe function is called during
startApp()initialization after MongoDB connects.Testing
Note
Medium Risk
Touches cron scheduling and Mongo persistence; wrong upsert or scheduling logic could duplicate runs or skip jobs in multi-instance deployments.
Overview
Cron job persistence now uses
upsertOneinstead ofupdateOnewhen a job starts, settinglastStartDateand insertingaliason first run via$setOnInsert, so_modelenceCronJobsrows are created on execution rather than requiring a separate registration step.startCronJobsbails out early whengetMongodbUri()is empty (logs and does not fetch or start the interval). After loading existing records, any job still missingscheduledRunTsis scheduled fromnow, so first runs work even when the DB has no row yet.Tests mock
getMongodbUri, expectupsertOne, and cover the no-URI skip andlastStartDate-based scheduling paths.Reviewed by Cursor Bugbot for commit a0e4dfd. Bugbot is set up for automated code reviews on this repo. Configure here.