Skip to content

fix: add cron jobs to _modelenceCronJobs store - #279

Merged
omegascorp merged 29 commits into
modelence:mainfrom
AtulYadav25:feat/add-cron-job-in-db
Jul 24, 2026
Merged

omegascorp merged 29 commits into
modelence:mainfrom
AtulYadav25:feat/add-cron-job-in-db

Conversation

@AtulYadav25

@AtulYadav25 AtulYadav25 commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

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 from modelence/src/cron/jobs.ts, it attempted to fetch cron job records from the database.

Screenshot (752)

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:

Screenshot (743)

Solution

Added registerNewCronJobs() which:

  • Queries the database for existing cron job records
  • Inserts only new jobs that haven't been registered yet
  • Prevents duplicate records with a database unique index on alias

The function is called during startApp() initialization after MongoDB connects.

Testing

  • Verified new cron jobs are inserted on first run
Screenshot (745)
  • Verified existing jobs are not duplicated on multiple runs

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 upsertOne instead of updateOne when a job starts, setting lastStartDate and inserting alias on first run via $setOnInsert, so _modelenceCronJobs rows are created on execution rather than requiring a separate registration step.

startCronJobs bails out early when getMongodbUri() is empty (logs and does not fetch or start the interval). After loading existing records, any job still missing scheduledRunTs is scheduled from now, so first runs work even when the DB has no row yet.

Tests mock getMongodbUri, expect upsertOne, and cover the no-URI skip and lastStartDate-based scheduling paths.

Reviewed by Cursor Bugbot for commit a0e4dfd. Bugbot is set up for automated code reviews on this repo. Configure here.

Comment thread packages/modelence/src/cron/jobs.ts Resolved
Comment thread packages/modelence/src/cron/jobs.ts Resolved
Comment thread packages/modelence/src/cron/jobs.ts Resolved
@AtulYadav25

Copy link
Copy Markdown
Contributor Author

@omegascorp PR ready for review

@omegascorp

omegascorp commented Jun 3, 2026 •

Copy link
Copy Markdown
Collaborator

Thank you @AtulYadav25 , I'm checking PR, please remove pnpm-lock.yaml

@AtulYadav25

Copy link
Copy Markdown
Contributor Author

After this update:

  • The cron jobs are added to _modelenceCronJobs collection.
  • Use AcquireLock to allow only one instance register new cron jobs in _modelenceCronJobs .

@omegascorp omegascorp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @AtulYadav25, I've added some comments

Comment thread packages/modelence/src/cron/jobs.ts Outdated
return;
}

const hasLock = await acquireLock('cron-registration', {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread packages/modelence/src/cron/jobs.ts Outdated
* This prevents duplicate entries and maintains an audit trail of when each
* cron job was first scheduled.
*/
export async function registerNewCronJobs() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to cover the new function with tests

Comment thread packages/modelence/src/cron/jobs.ts Outdated
}

const aliasSelector = { alias: { $in: aliasList } };
const existingCronJobs = await cronJobsCollection.fetch(aliasSelector);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to make sure to add proper error handling here. What happens if one of those calls throws an error?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread packages/modelence/src/app/index.ts Resolved
Comment thread packages/modelence/src/app/index.ts Resolved
…ted. Added Waiting function for other instances to wait untill the cron jobs are registered, in startCronJobs
@AtulYadav25
AtulYadav25 force-pushed the feat/add-cron-job-in-db branch from 8688bf5 to 0c1e39a Compare June 15, 2026 05:40
Comment thread packages/modelence/src/cron/jobs.ts Resolved
@AtulYadav25

Copy link
Copy Markdown
Contributor Author

Summary:: @omegascorp

With this commit, registerNewCronJobs() function is not using any extra lock, instead it is handled by the instance which holds the 'migration' lock.

Other instances now wait in startCronJobs() until all cron jobs have been registered.

And '_modelenceCronJobs' has been changed to use indexCreationMode: 'blocking'.

@omegascorp

omegascorp commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

@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 modelence-ops left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

  • waitForCronJobsRegistered blocks 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 of startApp and releases the migrations lock, inconsistent with how index-creation failures are tolerated right next to it. Worth confirming that's intended.
  • Nit: the try/catch in registerNewCronJobs only 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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This blocking wait runs on paths where registration never happens. startCronJobs() is called unconditionally at the end of startApp, including:

  • No MongoDB URI: connect() and registerNewCronJobs() are skipped entirely, so this polls a never-populated store for the full 30s before proceeding (regression — previously this path did a single fetch and 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).

Comment thread packages/modelence/src/cron/jobs.ts Outdated
}
} catch (error) {
throw error;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(', ')}`
);

Comment thread packages/modelence/src/cron/jobs.ts Outdated
Comment on lines +73 to +87
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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread packages/modelence/src/app/index.ts Outdated
}
// registerNewCronJobs runs here — after the unique alias index is guaranteed
// to exist (cronJobsCollection is now blocking!)
await registerNewCronJobs();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Comment thread packages/modelence/src/cron/jobs.ts Resolved
…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
Comment thread packages/modelence/src/cron/jobs.ts Resolved
…ocs, to store current migrations lock acquiredAt as sessionToken. With this, other instances don't fetch the stale doc of _registration_status document
Comment thread packages/modelence/src/lock/helpers.ts Resolved
Comment thread packages/modelence/src/cron/jobs.ts Resolved
Comment thread packages/modelence/src/cron/jobs.ts Resolved
Comment thread packages/modelence/src/cron/jobs.ts Resolved
Comment thread packages/modelence/src/cron/jobs.ts Resolved
Comment thread packages/modelence/src/lock/helpers.ts Resolved
Comment thread packages/modelence/src/lock/helpers.ts Resolved
Comment thread packages/modelence/src/cron/jobs.ts Resolved

@modelence-ops modelence-ops left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. An architectural-complexity question on the waitForCronJobsRegistered startup barrier (inline on cron/jobs.ts).
  2. A minor schema/back-compat nit on the new _modelenceLocks.status field (inline on lock/db.ts).

Comment thread packages/modelence/src/cron/jobs.ts Resolved
Comment thread packages/modelence/src/lock/db.ts Resolved
Comment thread packages/modelence/src/cron/jobs.ts Resolved
Comment thread packages/modelence/src/app/index.ts Resolved
Comment thread packages/modelence/src/cron/jobs.ts Resolved
@AtulYadav25

Copy link
Copy Markdown
Contributor Author

Thank you @modelence-ops & @omegascorp

Good point waitForCronJobsRegistered function was redundant. I initially planned for problem of limiting the number of cron jobs running concurrently, but this can be done more cleanly without the waitForCronJobsRegistered function.

The PR now has cleaner code:

  • It has only the registerNewCronJobs function, which runs only when it has _modelenceCronJobs store
  • In startCronJobs, the function queries the database only when MongoDB is configured
  • Added test cases for all the changes.

@modelence-ops modelence-ops left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 no lastStartDate, so startCronJobs schedules them at now — same as the no-record fallback.
  • Existing aliases already carry lastStartDate from a prior boot; the getMongodbUri()-gated fetch picks them up.
  • Cross-instance double-runs stay prevented by acquireLock('cron', …) in tickCronJobs, 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:

  1. The comment above insertMany says an "ordered insertMany would abort on a duplicate-key error," but the call passes { ordered: false }. With ordered: false the driver keeps going and surfaces dups via writeErrors (which isDuplicateKeyError now handles) — worth aligning the comment with the code.
  2. Bugbot's "cron writes without unique index" edge (blocking index build fails → registration skipped, but runCronJob still upserts): in practice the single acquireLock('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.

@artahian artahian left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ 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'");
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 96543bb. Configure here.

@AtulYadav25

Copy link
Copy Markdown
Contributor Author

Thanks @artahian ,catching this
I was again overengineering this way more than it needed, upsertOne fix alone handles everything

I pulled out all the extra stuff

Tested locally in a Modelence app and confirmed jobs get added to _modelenceCronJobs.

I pushed the clean version commit

@omegascorp omegascorp changed the title feat: Adds cron jobs to _modelenceCronJobs store fix: add cron jobs to _modelenceCronJobs store Jul 24, 2026

@omegascorp omegascorp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AtulYadav25 it finally looks.

@omegascorp
omegascorp dismissed artahian’s stale review July 24, 2026 15:06

Considering as done, the latest change looks good

@omegascorp
omegascorp merged commit ba7a070 into modelence:main Jul 24, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants