Skip to content

fix(mongoose): tolerate same-name index conflicts at boot so migrations can repair them - #4005

Merged
PierreBrisorgueil merged 2 commits into
masterfrom
fix/index-conflict-boot
Jul 29, 2026
Merged

fix(mongoose): tolerate same-name index conflicts at boot so migrations can repair them#4005
PierreBrisorgueil merged 2 commits into
masterfrom
fix/index-conflict-boot

Conversation

@PierreBrisorgueil

@PierreBrisorgueil PierreBrisorgueil commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Summary

  • What changed: awaitIndexBuilds() now tolerates a same-name index build rejection from the driver (MongoDB codes 85 IndexOptionsConflict / 86 IndexKeySpecsConflict) instead of propagating it. On a tolerated conflict it logs at error level — model name, the raw driver error, and (best-effort) both the schema-declared and live collection index specs — then lets boot continue. Every other rejection (invalid declarations, unsupported operators, etc.) still propagates exactly as before.
  • Why: this is a deliberate narrowing of the fail-fast contract introduced in 🐛 startMongoose resolves before index builds — unique-index idempotency can double-apply on a fresh database #3990. Codes 85/86 describe environment state — a legacy same-name index already present on a deployed database with different options/keys than the current schema declaration — not a code defect. The repair for that state is a migration, and the migration runner executes right after awaitIndexBuilds() in bootstrap(). Propagating the rejection therefore gated the repair behind the very defect it exists to repair: the app could never boot far enough to run the migration that would fix it, with no recovery path short of manual index surgery on the database. Tolerating the conflict lets boot reach the migration runner; the app serves with the stale live index (writes keep obeying the old constraint) until the migration reconciles it.
  • Related issues: Closes 🐛 Boot: same-name index conflict crashes startup before the migration that repairs it can run #4004

Scope

  • Module(s) impacted: lib/services/mongoose.js (index-build tolerance) only. No downstream/module code changed.
  • Cross-module impact: none
  • Risk level: low — the change only widens what boot tolerates (two specific, well-identified driver error codes); every other error path is unchanged and still fails fast.

Alternative considered

Running migrations before index builds would also unblock this case, but it was rejected: it inverts the #3990 invariant that unique-index idempotency guards exist before anything writes, and it silently invalidates the ordering assumptions already codified in shipped migrations (e.g. modules/billing/migrations/20260727120000-fix-usage-month-index-partial-filter.js, which assumes the boot-time index build has already run). Narrowing the fail-fast contract to exclude only same-name conflicts (85/86) preserves that ordering while removing the boot-blocking trap.

Regression tests

4 new unit tests in lib/tests/mongoose.awaitIndexBuilds.unit.tests.js cover:

  • a same-name conflict (code 85) is tolerated and logged, boot proceeds
  • a same-name conflict by codeName (IndexKeySpecsConflict, code 86) is tolerated and logged, boot proceeds
  • a non-conflict rejection still propagates and fails boot
  • the error-level log includes the model name and, best-effort, the declared vs live index specs

Validation

  • npm run lint
  • npm test
  • Manual checks done (if applicable)

Guardrails check

  • No secrets or credentials introduced (.env*, secrets/**, keys, tokens)
  • 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: none — no new external input surface; the change only affects how a specific pair of driver error codes is handled during boot.
  • Mergeability considerations: none — additive change to a single stack file, no schema/contract change for downstream projects.
  • Follow-up tasks (optional): none identified.

Summary by CodeRabbit

  • Bug Fixes

    • Startup now continues when MongoDB reports same-name index conflicts.
    • Index conflict details, including model and index specifications, are logged for troubleshooting.
    • Other index-building errors continue to surface normally.
  • Tests

    • Added coverage for tolerated MongoDB index conflicts and propagation of unrelated errors.

…ns can repair them

A schema index change that alters the options of an existing same-name
index (e.g. adding a partialFilterExpression) made the app unable to boot
against an already-deployed database: awaitIndexBuilds() propagated the
MongoDB conflict rejection (code 85 IndexOptionsConflict / 86
IndexKeySpecsConflict) before the migration runner — which runs right
after it in bootstrap and owns the drop/recreate repair — could execute.
The repair was gated behind the very defect it repairs.

This deliberately narrows the #3990 fail-fast contract: conflict codes
85/86 describe environment state (a legacy index on a deployed database),
not a code bug. They are now logged at error level — model, driver error,
and best-effort declared (schema) vs live (collection) specs — and boot
continues serving on the stale live index so the migration can reconcile.
Every other rejection (e.g. an invalid index declaration) still
propagates and fails boot exactly as before.

Closes #4004
@PierreBrisorgueil PierreBrisorgueil added the Fix A bug fix label Jul 29, 2026
@PierreBrisorgueil PierreBrisorgueil self-assigned this Jul 29, 2026
@PierreBrisorgueil
PierreBrisorgueil marked this pull request as ready for review July 29, 2026 14:15
@codecov

codecov Bot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.52%. Comparing base (fb771a8) to head (b545bb2).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4005      +/-   ##
==========================================
+ Coverage   93.50%   93.52%   +0.01%     
==========================================
  Files         170      170              
  Lines        5727     5744      +17     
  Branches     1839     1843       +4     
==========================================
+ Hits         5355     5372      +17     
  Misses        302      302              
  Partials       70       70              
Flag Coverage Δ
integration 61.68% <23.52%> (-0.12%) ⬇️
unit 76.06% <100.00%> (+0.07%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.


Continue to review full report in Codecov by Harness.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update fb771a8...b545bb2. Read the comment docs.

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

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@PierreBrisorgueil, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 47 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: ad7ac526-b655-47f7-9f66-5d802ccaffc4

📥 Commits

Reviewing files that changed from the base of the PR and between d8a047b and b545bb2.

📒 Files selected for processing (2)
  • lib/services/mongoose.js
  • lib/services/tests/mongoose.awaitIndexBuilds.unit.tests.js

Walkthrough

awaitIndexBuilds() now tolerates MongoDB same-name index conflicts, logs declared and live index details, and continues startup. Other model initialization errors still propagate. Unit tests cover conflict variants, index enumeration failures, and non-conflict rejection.

Changes

MongoDB index conflict tolerance

Layer / File(s) Summary
Conflict detection and startup handling
lib/services/mongoose.js
Detects MongoDB conflict codes 85/86 and related names, logs model and index specifications, tolerates matching initialization failures, and preserves propagation for other errors.
Conflict handling regression coverage
lib/services/tests/mongoose.awaitIndexBuilds.unit.tests.js
Tests tolerated conflict variants, logging when live-index enumeration fails, and rejection of unrelated initialization errors.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Startup
  participant awaitIndexBuilds
  participant MongooseModel
  participant Logger
  Startup->>awaitIndexBuilds: wait for model index initialization
  awaitIndexBuilds->>MongooseModel: call init()
  MongooseModel-->>awaitIndexBuilds: return conflict 85/86
  awaitIndexBuilds->>Logger: log model and declared/live index details
  awaitIndexBuilds-->>Startup: continue boot
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The code and tests satisfy #4004 by tolerating only codes 85/86, logging details, and letting boot continue.
Out of Scope Changes check ✅ Passed The changes stay scoped to mongoose boot/index handling and its tests, with no unrelated code paths introduced.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly summarizes the main change: allowing same-name index conflicts at boot so migrations can fix them.
Description check ✅ Passed The description covers summary, scope, risk, validation, guardrails, tests, and review notes, matching the template well.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/index-conflict-boot

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

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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 `@lib/services/mongoose.js`:
- Around line 63-80: Update logIndexConflict to pass the raw err as the second
argument to the primary logger.error call while retaining the model context in
the message. Log the declared schema indexes immediately after
model.schema.indexes() succeeds, before awaiting listIndexes().toArray(), then
log the live indexes separately; preserve the existing best-effort catch logging
for enumeration failures.

In `@lib/services/tests/mongoose.awaitIndexBuilds.unit.tests.js`:
- Around line 236-248: Add JSDoc annotations to the setupWithConflictingModel
helper, documenting its initError and listIndexes parameters and the
Promise-based return value. Keep the existing explanatory context and helper
behavior unchanged.
🪄 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 Plus

Run ID: 68ffc814-8185-47bc-8ae1-0791178d1727

📥 Commits

Reviewing files that changed from the base of the PR and between fb771a8 and d8a047b.

📒 Files selected for processing (2)
  • lib/services/mongoose.js
  • lib/services/tests/mongoose.awaitIndexBuilds.unit.tests.js

Comment thread lib/services/mongoose.js
Comment thread lib/services/tests/mongoose.awaitIndexBuilds.unit.tests.js
…failure

Addresses CodeRabbit review on PR #4005:
- logIndexConflict now passes the raw driver error as logger.error's
  second arg (matches this file's own convention at the timeout log
  a few lines below, and the codebase-wide two-arg pattern)
- log the declared (schema) spec immediately after computing it,
  before awaiting listIndexes(), so a live-fetch failure doesn't
  discard an already-available declared spec
- JSDoc for the new setupWithConflictingModel test helper
@PierreBrisorgueil
PierreBrisorgueil merged commit f85f49a into master Jul 29, 2026
8 checks passed
@PierreBrisorgueil
PierreBrisorgueil deleted the fix/index-conflict-boot branch July 29, 2026 17:42
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.

🐛 Boot: same-name index conflict crashes startup before the migration that repairs it can run

1 participant