Skip to content

fix(database): cannot overwrite view bug#1464

Draft
ChrisPdgn wants to merge 1 commit into
mainfrom
overwrite-view-bug
Draft

fix(database): cannot overwrite view bug#1464
ChrisPdgn wants to merge 1 commit into
mainfrom
overwrite-view-bug

Conversation

@ChrisPdgn
Copy link
Copy Markdown
Contributor

This is my attempt to fix the "Cannot overwrite ... model" race condition

Concurrent calls to createView with the same viewName caused intermittent failures:

[ERROR] /database.DatabaseProvider/createView INTERNAL: Cannot overwrite … model once compiled.

This is a check-then-act race. Two calls both see this.views[viewName] as unset, then both try to register the same Mongoose model and create the same MongoDB view. The second fails because:

  • mongoose.model(name, schema) throws OverwriteModelError if the name is already registered.
  • createCollection({ viewOn }) can fail with NamespaceExists if the view already exists in MongoDB.

Typical triggers:

  • Concurrent CreateResourceAccessList calls that resolve to the same hashed viewName.
  • Multiple database instances handling database:create:view bus events.
  • recoverViewsFromDatabase running many createView calls in parallel.

Solution

Two complementary mechanisms in the Mongoose adapter:

1. Promise coalescing (same process)

A pendingViewCreations map tracks in-flight work per viewName. A second caller awaits the same promise instead of starting duplicate registration / createCollection.

2. Catch-and-recover (multi-instance and leftovers)

  • MongooseSchema constructor: catch OverwriteModelError and use the existing mongoose.model(name).
  • createCollection: ignore NamespaceExists / “already exists” style errors (aligned with how SQL adapters tolerate duplicate view creation).

Testing results

I have observed that this error is always thrown when 2 database instances are deployed and tested this fix in that case. The error wasn't thrown successfully.

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update
  • Refactor
  • Build-related changes
  • Other (please describe)

Does this PR introduce a breaking change?

  • Yes
  • No

The PR fulfills these requirements:

  • It's submitted to the main branch
  • When resolving a specific issue, it's referenced in the PR's description (e.g. fix #xxx, where "xxx" is the issue number)

If adding a new feature, the PR's description includes:

  • A convincing reason for adding this feature

Other information:

@ChrisPdgn ChrisPdgn marked this pull request as draft May 6, 2026 13:04
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.

2 participants