Using TransactionScope and EF together with raw connection might trigger idle-in-transaction timeout

Abierto
#3,602 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
25/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Estancado
Stack tecnológico
csharp, postgresql
Área
databases

Línea de trabajo

Start by locating and running the Ambient_transaction_bug test in the TransactionNpgsqlTest class. Trace how the test combines TransactionScope, DbContext, and a raw NpgsqlConnection, then compare behavior with the commented-out context usage and ping. Done when the test reliably demonstrates the reported timeout and the transaction behavior is corrected without using a prepared transaction.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

I have a piece of code where I use both DbContext and data source to get raw sql connection, and in together with TransactionScope, it triggers idle-in-transaction timeout.
Here's a unit test that I put in TransactionNpgsqlTest class to reproduce it. If we "ping" DbContext every now and then this test passes. If we comment out the first context usage, it also passes, but if we leave it in current state, you should experience the timeout (mine is set to 5 seconds).
My expectation would be that no matter in which connection, the transaction is the same and no timeout should be triggered.
Also, prepared transaction count check is there to ensure that no distributed transaction is being used.
P.S. I am not sure if this is more of Npgsql problem or EF itself, but trying to start here.

  [ConditionalFact]
  public async Task Ambient_transaction_bug()
  {
      await using var context = CreateContext();
      var timeoutInMilliseconds = await context.Database.SqlQueryRaw<int>("SELECT setting::INTEGER AS \"Value\"  FROM pg_settings WHERE name = 'idle_in_transaction_session_timeout'").Order().FirstAsync();
      Assert.True(timeoutInMilliseconds > 0);

      timeoutInMilliseconds /= 2;

      using var transactionScope = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled);
      // Adding this line causes "terminating connection due to idle-in-transaction timeout" error at the bottom. Feels like transactions are not scoped.
      _ = context.Set<TransactionCustomer>().Any();

      await using (var conn = new NpgsqlConnection(TestStore.ConnectionString))
      {
          conn.Open();
          for (var i = 0; i < 3; i++) // A loop to show that this does not invoke transaction session timeout when doing some "work" in the same connection
          {
              await using var cmd = new NpgsqlCommand("SELECT 1", conn);
              cmd.ExecuteNonQuery();

              // Uncommenting this Assert would NOT cause the idle-in-transaction timeout anymore, because it "pings" EF transaction.
              //Assert.Equal(0, GetNumberOfPreparedTransactions(context));
              await Task.Delay(timeoutInMilliseconds);
          }
      }

      _ = context.Set<TransactionCustomer>().Any();
      Assert.Equal(0, GetNumberOfPreparedTransactions(context));
  }

  int GetNumberOfPreparedTransactions(DbContext context)
      => context.Database.SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM pg_prepared_xacts WHERE database = 'postgres'").Order().First();
Lenguaje dominante
C#
Estrellas
1.8k
Forks
268
Merge medio
2 h 35 min
PR fusionados (30 d)
136

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de npgsql/efcore.pg

Todos los issues de npgsql/efcore.pg

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.