Skip to content

fix(migrations): sync Migration indexes on boot to enforce unique name#3455

Merged
PierreBrisorgueil merged 2 commits intomasterfrom
fix/3454-migrations-unique-index
Apr 12, 2026
Merged

fix(migrations): sync Migration indexes on boot to enforce unique name#3455
PierreBrisorgueil merged 2 commits intomasterfrom
fix/3454-migrations-unique-index

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

@PierreBrisorgueil PierreBrisorgueil commented Apr 12, 2026

Summary

  • What changed: Call Migration.syncIndexes() at the start of migrations.run() so the unique-on-name index is created/re-created before any read or write against the migrations collection. Add a unit test asserting the schema declares unique: true on name.
  • Why: The Migration schema has unique: true on name, but the index is only built when Mongoose auto-creates it. Deployments whose migrations collection was created before the unique flag was added kept running without the index, silently allowing duplicate claims and causing the should reject duplicate migration names integration test to fail on clean boots. This also breaks the atomic claim guarantee used by claimMigration() to prevent concurrent runners from executing the same migration twice.
  • Related issues: Closes fix(migrations): duplicate name test fails — unique index missing #3454

Scope

  • Module(s) impacted: lib/services/migrations.js, modules/core/tests/migrations.unit.tests.js
  • Cross-module impact: none
  • Risk level: low

Validation

  • npm run lint
  • npm test (full suite with coverage — 766 tests, 64 suites, all green)
  • Manual checks done — reproduced the failing test on master, confirmed green after the fix, re-ran integration tests 3x to confirm stability

Guardrails check

  • No secrets or credentials introduced
  • No risky rename/move of core stack paths
  • Changes remain merge-friendly for downstream projects
  • Tests added or updated when behavior changed

Notes for reviewers

  • Security considerations: The unique index backs the atomic claim logic in claimMigration() that prevents two concurrent boot runners (e.g. rolling deploys) from executing the same migration twice. Without the index the claim is not actually atomic — this fix closes that gap for collections that pre-date the unique: true declaration.
  • Mergeability considerations: syncIndexes() is idempotent and cheap; it runs once per boot in migrations.run() before any claimMigration() / recordMigration() call, so there's no race. Safe on fresh collections (creates the index) and safe on collections that already have it (no-op).
  • Follow-up tasks (optional): none.

Summary by CodeRabbit

  • Chores

    • Migration system now synchronizes database indexes with schema on startup to ensure consistency.
  • Tests

    • Added test coverage verifying migration name field index configuration.

The Migration collection's unique-on-name index (which backs the atomic
claim logic in claimMigration) was only declared on the schema, not
actively enforced against existing collections. Deployments whose
`migrations` collection was created before the unique: true flag was
added kept running without the index, silently allowing duplicate
claims and causing the 'should reject duplicate migration names'
integration test to fail intermittently on clean boots.

Call Migration.syncIndexes() at the start of migrations.run() so the
unique index is created (or re-created) before any read/write against
the collection. Idempotent and cheap on every boot.

Add a unit test asserting the schema declares unique: true on name to
guard against accidental regressions.

Closes #3454
@PierreBrisorgueil PierreBrisorgueil added the Fix A bug fix label Apr 12, 2026
@PierreBrisorgueil PierreBrisorgueil self-assigned this Apr 12, 2026
@PierreBrisorgueil PierreBrisorgueil added the Fix A bug fix label Apr 12, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 12, 2026

Warning

Rate limit exceeded

@PierreBrisorgueil has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 22 minutes and 21 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 22 minutes and 21 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 31cd9fe5-3326-4879-b99d-29cfc3b68560

📥 Commits

Reviewing files that changed from the base of the PR and between bcb28c0 and de6c666.

📒 Files selected for processing (2)
  • lib/services/migrations.js
  • modules/core/repositories/migration.repository.js

Walkthrough

Added a new ensureMigrationIndexes() helper function to the migrations service that synchronizes the Migration model's collection indexes with its schema definition. This function is called during the migration initialization flow to ensure the unique name index exists before any migration operations occur.

Changes

Cohort / File(s) Summary
Migration Service Enhancement
lib/services/migrations.js
Added ensureMigrationIndexes() async helper that invokes Migration.syncIndexes() to reconcile collection indexes with schema. Integrated into the run() flow immediately after model registration and before migration discovery/execution. Extended default export to include the new function.
Migration Model Validation
modules/core/tests/migrations.unit.tests.js
Added unit test to verify the name field schema path includes unique: true index option, confirming the unique constraint is properly configured on the Migration model.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: calling Migration.syncIndexes() on boot to enforce the unique name index.
Description check ✅ Passed The PR description is comprehensive and follows the template with all required sections: summary, scope, validation, guardrails check, and notes for reviewers.
Linked Issues check ✅ Passed The PR fully addresses issue #3454 by ensuring the unique index on the name field is enforced via syncIndexes() at boot before any migration operations.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the unique index enforcement issue: adding ensureMigrationIndexes() to migrations.js and a schema validation test.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/3454-migrations-unique-index

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 and usage tips.

@codecov
Copy link
Copy Markdown

codecov bot commented Apr 12, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.81%. Comparing base (67acceb) to head (de6c666).
⚠️ Report is 3 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3455      +/-   ##
==========================================
+ Coverage   85.74%   85.81%   +0.06%     
==========================================
  Files         114      115       +1     
  Lines        2911     2911              
  Branches      805      805              
==========================================
+ Hits         2496     2498       +2     
+ Misses        329      327       -2     
  Partials       86       86              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@PierreBrisorgueil PierreBrisorgueil marked this pull request as ready for review April 12, 2026 20:10
Copilot AI review requested due to automatic review settings April 12, 2026 20:10
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Ensures the migrations collection enforces uniqueness on migration name by syncing indexes at startup, preventing duplicate migration claims and restoring the atomicity guarantee relied on by concurrent boot runners.

Changes:

  • Add ensureMigrationIndexes() and call it at the start of migrations.run() to syncIndexes() before any reads/writes.
  • Export ensureMigrationIndexes() from the migrations service.
  • Add a unit test asserting the Migration schema declares unique: true on name.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
lib/services/migrations.js Sync Migration indexes on boot (via syncIndexes()) to enforce the unique name constraint before claiming/recording migrations.
modules/core/tests/migrations.unit.tests.js Add a unit-level assertion that the name schema path declares unique: true.

coderabbitai[bot]
coderabbitai bot previously requested changes Apr 12, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

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 the current code and only fix it if needed.

Inline comments:
In `@lib/services/migrations.js`:
- Around line 132-134: The helper ensureMigrationIndexes directly accesses
mongoose.model('Migration') and calls Migration.syncIndexes(); move this
datastore access into a repository method (e.g., add a
MigrationRepository.syncIndexes or migrationRepo.ensureIndexes) that performs
the mongoose.model('Migration').syncIndexes() call, then update
ensureMigrationIndexes to call that repository method instead so the service
layer no longer imports/uses Mongoose directly.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 040682fd-eeb4-4f26-89db-fb4dc4716e01

📥 Commits

Reviewing files that changed from the base of the PR and between 67acceb and bcb28c0.

📒 Files selected for processing (2)
  • lib/services/migrations.js
  • modules/core/tests/migrations.unit.tests.js

Address CodeRabbit review: the migrations service was directly calling
mongoose.model('Migration') for every read/write, violating the layer
rule that Mongoose imports stay confined to repositories and models.

- Introduce modules/core/repositories/migration.repository.js with
  syncIndexes / listExecuted / create / deleteByName primitives.
- Refactor lib/services/migrations.js to delegate all data access to
  the repository; the service now only imports the repository and
  no longer touches Mongoose directly.

No behavioral change — all 766 tests still pass, coverage thresholds
still met.
@PierreBrisorgueil PierreBrisorgueil dismissed coderabbitai[bot]’s stale review April 12, 2026 20:23

Addressed in de6c666 — mongoose access moved into modules/core/repositories/migration.repository.js; CodeRabbit confirmed the fix in its follow-up review.

@PierreBrisorgueil PierreBrisorgueil merged commit 3cc434c into master Apr 12, 2026
5 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the fix/3454-migrations-unique-index branch April 12, 2026 20:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Fix A bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(migrations): duplicate name test fails — unique index missing

2 participants