Skip to content

Hold the migration lock for the whole migration run - #4163

Open
PieterjanDeClippel wants to merge 1 commit into
npgsql:mainfrom
PieterjanDeClippel:fix/4162-migration-lock-whole-run
Open

PieterjanDeClippel wants to merge 1 commit into
npgsql:mainfrom
PieterjanDeClippel:fix/4162-migration-lock-whole-run

Conversation

@PieterjanDeClippel

Copy link
Copy Markdown

Fixes #4162

Concurrent Migrate() calls could apply the same migration twice.

Cause:

  • NpgsqlHistoryRepository takes LOCK TABLE "__EFMigrationsHistory" IN ACCESS EXCLUSIVE MODE with LockReleaseBehavior.Transaction, so the lock ends with each migration's transaction.
  • EF's migrator plans the run from the history it reads under the first lock.
  • It reacquires the lock for each later migration without re-reading the history.
  • Another instance waiting on the lock can apply the next migration in between, and the first instance then applies that migration again.

Change:

  • The repository takes a session-level pg_advisory_lock with LockReleaseBehavior.Connection, so the migrator takes it once, before reading the history, and holds it for the whole run. This is how SQL Server works with sp_getapplock.
  • The lock key is a 64-bit FNV-1a hash of the history table's schema-qualified name, so different history tables (or schemas) don't block each other.
  • Disposing the lock runs pg_advisory_unlock while the connection is open. If the connection closes, PostgreSQL releases the lock.
  • AcquiringMigrationLock is now logged on the async path as well.

Test: MigrationsInfrastructureNpgsqlTest.Can_apply_several_migrations_in_parallel (sync and async) runs four Migrate() calls together over three migrations; the second migration sleeps one second.

  • On main without the change, both variants fail: 42701: column "Email" of relation "People" already exists and 42701: column "Phone" ....
  • With the change, they pass, along with the rest of MigrationsInfrastructureNpgsqlTest and NpgsqlHistoryRepositoryTest (56 of 56, PostgreSQL 18 Testcontainers image).

The existing parallel tests in MigrationsInfrastructureTestBase migrate a single migration at a time, so they never reached this race.

Standalone repro, plus the same change as a ReplaceService workaround for 11.0.0: https://github.com/PieterjanDeClippel/efcore-npgsql-migration-lock-race

Trade-off: a session-level lock does not hold through PgBouncer in transaction pooling mode, which LOCK TABLE inside a transaction does. If you would rather keep the transaction-scoped lock, the alternative is in EF Core's migrator: re-read the history after each reacquired lock, which would fix every provider that uses LockReleaseBehavior.Transaction.

🤖 Generated with Claude Code

NpgsqlHistoryRepository locked the history table with LOCK TABLE ... ACCESS EXCLUSIVE and
LockReleaseBehavior.Transaction, so the lock ended with each migration's transaction. The migrator
plans the whole run from the history it reads under the first lock, and reacquires the lock per
migration without re-reading it. Another instance could apply the next migration in between, and the
first instance then applied it again.

Take a session-level pg_advisory_lock with LockReleaseBehavior.Connection instead, keyed on the
history table's schema-qualified name, and release it with pg_advisory_unlock, as SQL Server does
with sp_getapplock.

Fixes npgsql#4162

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PieterjanDeClippel added a commit to MintPlayer/MintPlayer.Spark that referenced this pull request Nov 24, 2026
S3: synchronize scaffolds on the context that ran HasPendingModelChanges(), through
FreshSnapshotMigrationsAssembly in the design-time services (dotnet/efcore#36016, fix upstream in
dotnet/efcore#39784). Rerun: every version scaffolds the expected operations on both databases; the
trap still reproduces without the decorator.

S19: the PostgreSQL provider registers AdvisoryLockHistoryRepository, a session advisory lock held for
the whole Migrate() run (npgsql/efcore.pg#4162, fix upstream in npgsql/efcore.pg#4163). New scenario 1d:
three instances apply each migration once with EF's lock alone. D33's guard stays for CREATE DATABASE
and the data migrations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PieterjanDeClippel added a commit to MintPlayer/MintPlayer.Spark that referenced this pull request Nov 25, 2026
…tes them

- Framework schema (D24) in schema `spark` with its own history and hand-written migrations
  (SparkFrameworkDbContext, SparkFramework0001); SparkDbContext maps the same tables excluded from migrations.
- RelationalSchemaMigrator (ISparkSchemaMigrator, D33): the dialect's guard in the maintenance database
  (sp_getapplock / pg_advisory_lock), database creation, framework then app migrations, a refusal naming
  --spark-synchronize-model when the model has changes no migration covers, and the idempotent script.
  PostgreSQL registers AdvisoryLockHistoryRepository (S19, until npgsql/efcore.pg#4163).
- RelationalSchema: CreateFromModelAsync / ApplyDifferencesAsync for test databases; tests no longer use
  EnsureCreated.
- SparkMigrationsModelDiffer: a required collection column added to existing rows gets the empty collection as
  its SQL default (found by D16: PostgreSQL refused the column). D16 now passes on SQL Server and PostgreSQL.
- MintPlayer.Spark.Relational.Design (O17): RelationalSchemaScaffolder, found by core through
  SparkSchemaDesignAssembly + [assembly: SparkSchemaScaffolder]; --spark-synchronize-model writes the migration
  into Migrations/<Provider>. FreshSnapshotMigrationsAssembly (dotnet/efcore#36016) and the recreated-table
  refusal; DevelopmentDependency, EF Design PrivateAssets=none, buildTransitive Publish=false + SPARKDESIGN001.
- Relational suite 100/100 against SQL Server and PostgreSQL; Spark.Tests command and layering classes green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PieterjanDeClippel added a commit to MintPlayer/MintPlayer.Spark that referenced this pull request Nov 26, 2026
S3: synchronize scaffolds on the context that ran HasPendingModelChanges(), through
FreshSnapshotMigrationsAssembly in the design-time services (dotnet/efcore#36016, fix upstream in
dotnet/efcore#39784). Rerun: every version scaffolds the expected operations on both databases; the
trap still reproduces without the decorator.

S19: the PostgreSQL provider registers AdvisoryLockHistoryRepository, a session advisory lock held for
the whole Migrate() run (npgsql/efcore.pg#4162, fix upstream in npgsql/efcore.pg#4163). New scenario 1d:
three instances apply each migration once with EF's lock alone. D33's guard stays for CREATE DATABASE
and the data migrations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PieterjanDeClippel added a commit to MintPlayer/MintPlayer.Spark that referenced this pull request Nov 26, 2026
…tes them

- Framework schema (D24) in schema `spark` with its own history and hand-written migrations
  (SparkFrameworkDbContext, SparkFramework0001); SparkDbContext maps the same tables excluded from migrations.
- RelationalSchemaMigrator (ISparkSchemaMigrator, D33): the dialect's guard in the maintenance database
  (sp_getapplock / pg_advisory_lock), database creation, framework then app migrations, a refusal naming
  --spark-synchronize-model when the model has changes no migration covers, and the idempotent script.
  PostgreSQL registers AdvisoryLockHistoryRepository (S19, until npgsql/efcore.pg#4163).
- RelationalSchema: CreateFromModelAsync / ApplyDifferencesAsync for test databases; tests no longer use
  EnsureCreated.
- SparkMigrationsModelDiffer: a required collection column added to existing rows gets the empty collection as
  its SQL default (found by D16: PostgreSQL refused the column). D16 now passes on SQL Server and PostgreSQL.
- MintPlayer.Spark.Relational.Design (O17): RelationalSchemaScaffolder, found by core through
  SparkSchemaDesignAssembly + [assembly: SparkSchemaScaffolder]; --spark-synchronize-model writes the migration
  into Migrations/<Provider>. FreshSnapshotMigrationsAssembly (dotnet/efcore#36016) and the recreated-table
  refusal; DevelopmentDependency, EF Design PrivateAssets=none, buildTransitive Publish=false + SPARKDESIGN001.
- Relational suite 100/100 against SQL Server and PostgreSQL; Spark.Tests command and layering classes green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

Concurrent Migrate() applies the same migration twice: the migration lock ends with each migration's transaction

1 participant