Skip to content

fix(core): cache the Model class in isModelStatic to avoid repeated require() - #18234

Merged
SippieCup merged 8 commits into
sequelize:mainfrom
Svehla:fix/cache-model-class-in-is-model-static
Oct 19, 2026
Merged

SippieCup merged 8 commits into
sequelize:mainfrom
Svehla:fix/cache-model-class-in-is-model-static

Conversation

@Svehla

@Svehla Svehla commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Pull Request Checklist

  • Have you added new tests to prevent regressions?
  • If a documentation update is necessary, have you opened a PR to the documentation repository? — not applicable, no behavior/API change
  • Did you update the typescript typings accordingly (if applicable)? — not applicable
  • Does the description below contain a link to an existing issue (Closes #[issue]) or a description of the issue you are solving?
  • Does the name of your PR follow our conventions?

Closes #18233

Description of Changes

The problem we hit

isModelStatic() calls require('../model') on every invocation:

export function isModelStatic<M extends Model>(val: any): val is ModelStatic<M> {
  // TODO: temporary workaround due to cyclic import.
  const { Model: TmpModel } = require('../model');

  return typeof val === 'function' && val.prototype instanceof TmpModel;
}

isModelStatic is on a hot path — it runs (directly, and via isSameInitialModel / extractModelDefinition) once per association while building queries. Although Node caches the loaded module, the require() call itself still funnels through Module._load and re-resolves the request every time.

We ran into this in production: under our Node module-resolution setup, that per-call require('../model') repeatedly walked trySelf → findParentPackageJSON → fs.stat, and on include-heavy queries (many associations) the resolution overhead showed up at the top of our CPU profiles. We were running this fix as a patch-package patch against @sequelize/[email protected] and wanted to upstream it.

Even on a plain Node setup where each resolution is cheaper, the work is pure waste: the resolved Model class never changes once the module graph is initialized.

The fix

Cache the resolved Model class in a module-level variable and reuse it on subsequent calls. The lazy require (the cyclic-import workaround) is preserved for the first call, so module-load ordering is unchanged; only the redundant re-resolution on later calls is removed.

let cachedModelClass: ModelStatic | undefined;

export function isModelStatic<M extends Model>(val: any): val is ModelStatic<M> {
  // TODO: temporary workaround due to cyclic import. ...
  cachedModelClass ??= require('../model').Model as ModelStatic;

  return typeof val === 'function' && val.prototype instanceof cachedModelClass;
}

Tests

Added a unit test that spies on Module._load and asserts the Model module is not re-resolved across 50 isModelStatic calls after warm-up.

I verified locally that the test passes with the fix and fails without it (the uncached version resolves the module once per call — 50 times). Behavior is unchanged and remains covered by the existing isModelStatic / isSameInitialModel tests; yarn eslint and yarn lerna run test-typings --scope=@sequelize/core both pass.

List of Breaking Changes

None. This is an internal, behavior-preserving performance optimization.

Summary by CodeRabbit

  • Refactor

    • Repeated model checks now reuse cached model information instead of resolving it again each time.
  • Tests

    • Added coverage to verify repeated checks reuse the cached information without triggering another module load. This confirms the updated behavior across successive checks.

@Svehla
Svehla requested a review from a team as a code owner June 5, 2026 11:27
@Svehla
Svehla requested review from ephys and sdepold June 5, 2026 11:27
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 511b8448-eece-4afe-8e60-8e931f8d5b22
📥 Commits

Reviewing files that changed from the base of the PR and between c079195 and ef0f0c6.

📒 Files selected for processing: 1
  • packages/core/src/utils/model-utils.ts
🚧 Files skipped from review as they are similar to previous changes: 1
  • packages/core/src/utils/model-utils.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

📝 Walkthrough

isModelStatic() now caches the Model class after its first lazy module load. A unit test verifies that repeated calls do not load the model module again.

Changes: isModelStatic Module Cache Optimization

Layer / File(s) Summary
Module-level cache implementation
packages/core/src/utils/model-utils.ts
isModelStatic() lazily stores the Model class in a module-level variable and uses it for subclass checks on later calls.
Cache behavior verification test
packages/core/test/unit/utils/model-utils.test.ts
The test primes the cache, spies on Module._load, and checks that repeated calls to isModelStatic() do not load ../model again.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Refactor · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to ef0f0

The cache and its regression test align with the intended performance improvement; no merge-blocking issue is established.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: caching the Model class in isModelStatic to avoid repeated require() calls.
Linked Issues check Passed Active direct issue [#18233] requires one lazy Model resolution and no additional resolutions after warm-up. packages/core/src/utils/model-utils.ts stores the required Model class in module-leve…
Out of Scope Changes check Passed The changes are limited to the isModelStatic cache and its regression test. The implementation preserves lazy loading for the cyclic-import workaround. The test directly supports issue [#18233]. No …
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 1 files.
Full details: Linked Issues check

Explanation

Active direct issue [#18233] requires one lazy Model resolution and no additional resolutions after warm-up. packages/core/src/utils/model-utils.ts stores the required Model class in module-level cachedModelClass and reuses it. packages/core/test/unit/utils/model-utils.test.ts verifies zero Module._load calls for later isModelStatic calls.

Full details: Out of Scope Changes check

Explanation

The changes are limited to the isModelStatic cache and its regression test. The implementation preserves lazy loading for the cyclic-import workaround. The test directly supports issue [#18233]. No unrelated change is shown.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/test/unit/utils/model-utils.test.ts`:
- Around line 14-37: This test mutates Sequelize model state but the file lacks
per-test lifecycle hooks; add a beforeEach that calls sequelize.sync({ force:
true }) (or equivalent reset) and an afterEach that closes the Sequelize
instance (sequelize.close()) to ensure isolation between tests, and update any
tests referencing MyModel or calling isModelStatic to rely on those hooks so
Sequelize instances and models are reset between tests.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d67f9ece-e460-46b8-9dc8-197179d3c1cb

📥 Commits

Reviewing files that changed from the base of the PR and between 8260c29 and 1ef312e.

📒 Files selected for processing (2)
  • packages/core/src/utils/model-utils.ts
  • packages/core/test/unit/utils/model-utils.test.ts

Comment thread packages/core/src/utils/model-utils.ts Resolved
Comment thread packages/core/src/utils/model-utils.ts Resolved
@SippieCup
SippieCup self-requested a review October 19, 2026 20:55

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

I just made the small change for you so we can get this merged.

In addition, I updated the assignment to work on older versions of node that we (unforunately) still support.

SippieCup and others added 3 commits October 19, 2026 21:04
…test

Filtering Module._load calls on requests ending in '/model' let the test
pass if the require were spelled differently (e.g. '../model.js').
isModelStatic should not load anything once the cache is warm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
model-typescript.ts already imports Model statically, so the per-call
require('./model.js') in addAttributeGetterAndSetters was not needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@wikirik-agent

Copy link
Copy Markdown
Contributor

@SippieCup about the ??= → if change: ??= is ES2021 and supported natively since Node 15. main requires ^22.18.0 || >=24.0.0, esbuild targets node22, and packages/core/src already uses ??= in several places (model.js, model-definition.ts, model-repository.ts, associations/belongs-to.ts, …). The only Node versions too old for it are the ones v6 supports (>=10), and v6 doesn't have this code. So cachedModelClass ??= require('../model').Model as ModelStatic; would be fine here. Not blocking, though, since both versions do the same thing.

Also, since your approval I pushed two small commits:

  • The cache test now asserts that Module._load is never called once the cache is warm. Before, it only counted requests ending in /model, so it would have kept passing if the require were spelled ../model.js. I checked that it fails when the cache is removed.
  • I removed the redundant per-call require('./model.js') in model-typescript.ts (addAttributeGetterAndSetters), because that file already imports Model statically.

(A static import in model-utils.ts itself doesn't work: it breaks module load order with Cannot access 'MultiAssociation' before initialization. So the lazy require plus the cache is the right approach there.)

@SippieCup
SippieCup merged commit cfba176 into sequelize:main Oct 19, 2026
WikiRik pushed a commit that referenced this pull request Oct 20, 2026
papandreou added a commit to papandreou/sequelize that referenced this pull request Oct 23, 2026
* origin/main: (54 commits)
  fix: use bind parameters in the Oracle catalog queries (sequelize#18498)
  meta: update mysql docker tag to v8.4.13 (sequelize#18577)
  meta: update dependency eslint-plugin-jsdoc to v65.4.0 (sequelize#18575)
  meta: update dependency node to v24.22.1 (sequelize#18574)
  meta: update dependency @oclif/core to ^5.1.9 (sequelize#18573)
  fix(core): skip removing foreign keys in dropAllTables when dropping with cascade (sequelize#18497)
  fix(core): drop each model only once in Sequelize#drop (sequelize#18572)
  fix(postgres): drop the enum types of a model when its table is dropped (sequelize#18554)
  fix(core): avoid lodash omit in the Model constructor (sequelize#18556)
  meta(core): support async functions in expectPerDialect (sequelize#18569)
  meta: update dependency ibm_db to ^4.1.0 (sequelize#18571)
  fix(core): make rejectInvalidOptions iterate supportable options and accept undefined (sequelize#18557)
  fix(core): respect the omitNull option of calls and models, fix query generator typings (sequelize#18565)
  meta(core): convert unit/model tests to TypeScript (sequelize#18564)
  meta(core): convert unit/instance tests to TypeScript (sequelize#18563)
  meta: update sequelize AUTHORS (sequelize#18549)
  feat(mssql): add useUnicodeStrings dialect option (sequelize#18548)
  meta: retry image pulls in the database start scripts (sequelize#18340)
  meta(core): follow-ups to the isModelStatic cache from sequelize#18234 (sequelize#18559)
  meta: update dependency uuid to v14 (sequelize#18544)
  ...

# Conflicts:
#	packages/postgres/src/query-interface.js
papandreou added a commit to papandreou/sequelize that referenced this pull request Oct 23, 2026
* origin/main: (26 commits)
  fix: use bind parameters in the Oracle catalog queries (sequelize#18498)
  meta: update mysql docker tag to v8.4.13 (sequelize#18577)
  meta: update dependency eslint-plugin-jsdoc to v65.4.0 (sequelize#18575)
  meta: update dependency node to v24.22.1 (sequelize#18574)
  meta: update dependency @oclif/core to ^5.1.9 (sequelize#18573)
  fix(core): skip removing foreign keys in dropAllTables when dropping with cascade (sequelize#18497)
  fix(core): drop each model only once in Sequelize#drop (sequelize#18572)
  fix(postgres): drop the enum types of a model when its table is dropped (sequelize#18554)
  fix(core): avoid lodash omit in the Model constructor (sequelize#18556)
  meta(core): support async functions in expectPerDialect (sequelize#18569)
  meta: update dependency ibm_db to ^4.1.0 (sequelize#18571)
  fix(core): make rejectInvalidOptions iterate supportable options and accept undefined (sequelize#18557)
  fix(core): respect the omitNull option of calls and models, fix query generator typings (sequelize#18565)
  meta(core): convert unit/model tests to TypeScript (sequelize#18564)
  meta(core): convert unit/instance tests to TypeScript (sequelize#18563)
  meta: update sequelize AUTHORS (sequelize#18549)
  feat(mssql): add useUnicodeStrings dialect option (sequelize#18548)
  meta: retry image pulls in the database start scripts (sequelize#18340)
  meta(core): follow-ups to the isModelStatic cache from sequelize#18234 (sequelize#18559)
  meta: update dependency uuid to v14 (sequelize#18544)
  ...

# Conflicts:
#	packages/core/src/abstract-dialect/query-generator.js
#	packages/core/src/abstract-dialect/query-interface-typescript.ts
#	packages/core/test/unit/model/bulk-create.test.js
#	packages/core/test/unit/sql/insert.test.js
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.

isModelStatic re-runs require('../model') on every call (redundant module resolution on a hot path)

3 participants