Skip to content

Pooled connections broken by EnsureDeleted() stay in the pool if using a data source #3326

Closed

Description

@MaceWindu

We have a set of tests that use different contexts with following setup:

  • all tests run sequentially (no parallel execution)
  • there are several database contexts used by tests
  • if context is not initialized yet during current test run, it will ensure test database is ready using
context.Database.EnsureDeleted();
context.Database.EnsureCreated();

This works fine for different db providers (we test sqlite, sqlserver, mysql and npgsql) and versions (3.1, 6, 8). But in v9 now it fails to create database for Npgsql on second call to snippet above. Basically only 1 context being initialized per test run, second initialization fails with:

System.InvalidOperationException
  HResult=0x80131509
  Message=An exception has been raised that is likely due to a transient failure.
  Source=Npgsql.EntityFrameworkCore.PostgreSQL
  StackTrace:
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded) in Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal\NpgsqlExecutionStrategy.cs:line 28
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IReadOnlyList`1 migrationCommands, IRelationalConnection connection, MigrationExecutionState executionState, Boolean commitTransaction, Nullable`1 isolationLevel)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.CreateTables() in Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal\NpgsqlDatabaseCreator.cs:line 210
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated()
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()
   at LinqToDB.EntityFrameworkCore.Tests.ContextTestBase`1.InitializeDatabase(TContext context, String provider, String connectionString) in C:\GitHub\linq2db\Tests\EntityFrameworkCore\ContextTestBase.cs:line 119
   at LinqToDB.EntityFrameworkCore.Tests.ContextTestBase`1.CreateContext(String provider, Func`2 optionsSetter, Func`2 optionsBuilderSetter) in C:\GitHub\linq2db\Tests\EntityFrameworkCore\ContextTestBase.cs:line 159
   at LinqToDB.EntityFrameworkCore.Tests.InterceptorTests.TestEfCoreSideOfComboInterceptor(String provider) in C:\GitHub\linq2db\Tests\EntityFrameworkCore\Tests\InterceptorTests.cs:line 109
   at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)

  This exception was originally thrown at this call stack:
    System.Net.Sockets.NetworkStream.Read(byte[], int, int)

Inner Exception 1:
NpgsqlException: Exception while reading from stream

Inner Exception 2:
IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine..

Inner Exception 3:
SocketException: An established connection was aborted by the software in your host machine.

Currently looking into providing isolated repro code

Activity

  1. MaceWindu commented on Oct 23, 2024

    @MaceWindu
    Author

    Reproduced.

    Note use of UseNodaTime option. Without it it works fine.

    This is actually a workaround for another issue in v8 we hit and I didn't reported yet: only one of test contexts need nodatime integration, but starting from v8 release it UseNodaTime was ignored if not called on first UseNpgsql call in tests (3.1 and 6 versions respected this call for specific context)

    using Microsoft.EntityFrameworkCore;
    
    internal class Program
    {
        private static void Main(string[] args)
        {
            var connectionString = "<connection_string_here>";
    
            for (var i = 0; i < 2; i++)
            {
                var optionsBuilder = new DbContextOptionsBuilder<TestContext>();
                optionsBuilder.UseNpgsql(connectionString, o => o.UseNodaTime());
    
                using (var ctx = new TestContext(optionsBuilder.Options))
                {
                    ctx.Database.EnsureDeleted();
                    ctx.Database.EnsureCreated();
                }
            }
        }
    }
    
    public class TestTable
    {
        public int Id { get; set; }
    }
    
    public sealed class TestContext(DbContextOptions options) : DbContext(options)
    {
        public DbSet<TestTable> Test { get; set; } = null!;
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TestTable>();
        }
    }
  2. MaceWindu commented on Oct 24, 2024

    @MaceWindu
    Author

    BTW, running from linux gives a bit different error:

    System.InvalidOperationException : An exception has been raised that is likely due to a transient failure.
    ----> Npgsql.PostgresException : 57P01: terminating connection due to administrator command
    Data:
    Severity: FATAL
    InvariantSeverity: FATAL
    SqlState: 57P01
    MessageText: terminating connection due to administrator command
    File: postgres.c
    Line: 3222
    Routine: ProcessInterrupts
    
       at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
       at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IReadOnlyList`1 migrationCommands, IRelationalConnection connection, MigrationExecutionState executionState, Boolean commitTransaction, Nullable`1 isolationLevel)
       at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
       at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.CreateTables()
       at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated()
       at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()
       at LinqToDB.EntityFrameworkCore.Tests.ContextTestBase`1.InitializeDatabase(TContext context, String provider, String connectionString)
       at LinqToDB.EntityFrameworkCore.Tests.ContextTestBase`1.CreateContext(String provider, Func`2 optionsSetter, Func`2 optionsBuilderSetter)
       at LinqToDB.EntityFrameworkCore.Tests.PomeloMySqlTests.SimpleProviderTest(String provider)
       at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
       at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
    --PostgresException
       at Npgsql.Internal.NpgsqlConnector.ReadMessageLong(Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
       at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
       at Npgsql.Internal.NpgsqlConnector.ReadMessageLong(Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
       at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
       at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
       at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
       at Npgsql.NpgsqlDataReader.NextResult()
       at Npgsql.NpgsqlCommand.ExecuteReader(Boolean async, CommandBehavior behavior, CancellationToken cancellationToken)
       at Npgsql.NpgsqlCommand.ExecuteReader(Boolean async, CommandBehavior behavior, CancellationToken cancellationToken)
       at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
       at Npgsql.NpgsqlCommand.ExecuteNonQuery()
       at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
       at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
       at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.Execute(IReadOnlyList`1 migrationCommands, IRelationalConnection connection, MigrationExecutionState executionState, Boolean beginTransaction, Boolean commitTransaction, Nullable`1 isolationLevel)
       at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.<>c.<ExecuteNonQuery>b__3_1(DbContext _, ValueTuple`6 s)
       at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
    
  3. self-assigned this
    on Oct 27, 2024
  4. added this to the 9.0.0 milestone on Oct 27, 2024
  5. changed the title [-]Migrations behavior change in 9.0.0[/-] [+]Pooled connections broken by EnsureDeleted() stay in the pool if using a data source[/+] on Oct 27, 2024
  6. roji commented on Oct 27, 2024

    @roji
    Member

    @MaceWindu thanks for the repro, I can see the error happening (I wish everyone submitted such minimal repros...).

    What's going on is a bit complex...

    Starting with EFCore.PG 9, UseNodaTime() (and MapEnum(), and some other things) cause the provider to build and use an NpgsqlDataSource internally; this is done so that EFCore.PG can be in control of the lower-level Npgsql configuration, and so that the EF-level UseNodaTime() can also configure NodaTime at the Npgsql data source level. Solves the bad user experience up to 9.0, where users had to configure NodaTime twice - once in Npgsql, once in EFCore.PG.

    Now, when you perform EnsureDeleted, EFCore.PG calls NpgsqlConnection.ClearAllPools() (code); this immediately clears all "legacy" pools of all idle connections (legacy = without a data source), since they're all broken. However, if a data source is in use, ClearAllPools() does not take effect on it (this is by design). Unfortunately, we're missing an API to clear an NpgsqlDataSource: opened npgsql/npgsql#5902 on the Npgsql side to discuss this.

    Slightly simplified repro with logging
    var connectionString = "Host=localhost;Username=test;Password=test";
    
    for (var i = 0; i < 2; i++)
    {
        var optionsBuilder = new DbContextOptionsBuilder<TestContext>();
        optionsBuilder
            .UseNpgsql(connectionString, o => o.UseNodaTime())
            // .UseNpgsql(connectionString)
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();
    
        using (var ctx = new TestContext(optionsBuilder.Options))
        {
            ctx.Database.EnsureDeleted();
            ctx.Database.EnsureCreated();
        }
    }
    
    public sealed class TestContext(DbContextOptions options) : DbContext(options)
    {
        public DbSet<TestTable> Test { get; set; } = null!;
    }
    
    public class TestTable
    {
        public int Id { get; set; }
    }
  7. added a commit that references this issue on Oct 28, 2024
    00ed302
  8. added a commit that references this issue on Oct 29, 2024
    72cb52e
  9. added a commit that references this issue on Dec 18, 2024
    89476a7
  10. added theissue type on Jun 19, 2025
  11. MaceWindu commented on Nov 23, 2025

    @MaceWindu
    Author

    @roji we see this error again with v10. rc2 was fine.

  12. MaceWindu commented on Nov 23, 2025

    @MaceWindu
    Author

    Ok, while error is the same, repro case is different. I will create new repro and open new issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions