Skip to content

Exception "In multiplexing mode, transactions must be started with BeginTransaction" without Multiplexing with 5.0.0-preview1 #3241

Closed

Description

@kae

Steps to reproduce

<Project Sdk="Microsoft.NET.Sdk">
	<PropertyGroup>
		<Authors>kae</Authors>
		<TargetFramework>net5.0</TargetFramework>
		<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
		<OutputType>Exe</OutputType>
	</PropertyGroup>
	<ItemGroup>
		<PackageReference Include="Npgsql" Version="5.0.0-preview1" />
		<PackageReference Include="Dapper" Version="2.0.35" />
	</ItemGroup>
</Project>
using System;
using System.Linq;
using System.Threading.Tasks;
using Dapper;

namespace pgTest {
	public class Program {
		private static readonly string connStr =
			"Server=db-host;Port=5432;Database=test_db;User id=test;Password=test";

		public static async Task Test(int i) {
			try {
				using var conn = new Npgsql.NpgsqlConnection(connStr);
				await conn.OpenAsync();
				using var tx = conn.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
				var rs = await conn.QueryFirstOrDefaultAsync<int>("select 1", transaction: tx);
				tx.Commit();
			}
			catch (Exception e) {
				Console.WriteLine(e);
			}
		}

		public static async Task Main() {
			try {
				await Task.WhenAll(Enumerable.Range(0, 1000).Select(i => Test(i)));
			}
			catch (Exception e) {
				Console.WriteLine(e);
			}
		}
	}
}

The issue

System.NotSupportedException: In multiplexing mode, transactions must be started with BeginTransaction
   at Npgsql.NpgsqlConnector.ProcessNewTransactionStatus(TransactionStatus newStatus)
   at Npgsql.NpgsqlConnector.ParseServerMessage(NpgsqlReadBuffer buf, BackendMessageCode code, Int32 len, Boolean isPrependedMessage)
   at Npgsql.NpgsqlConnector.DoReadMessage(Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, CancellationToken cancellationToken)
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
   at Npgsql.NpgsqlDataReader.Consume(Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlDataReader.Read(Boolean async, CancellationToken cancellationToken)
   at Dapper.SqlMapper.QueryRowAsync[T](IDbConnection cnn, Row row, Type effectiveType, CommandDefinition command) in /_/Dapper/SqlMapper.Async.cs:line 511
   at pgTest.Program.Test(Int32 i) in C:\Users\kae\Dump\dnx\pgTest\Program.cs:line 16

Count of exception is floating, so it looks like some race condition bug.

Further technical details

Npgsql version: 5.0.0-preview1
PostgreSQL version: 12.4 on x86_64-pc-linux-gnu
Operating system: Windows 10 (Build 19041.572)

There is another exception at actual system that wasn't reproduced still.
But it was mixed with reproduced. Not sure it has similar nature.

{
        "Message": "Exception while reading from stream",
        "InnerError": {
          "Message": "Timeout during reading attempt"
        },
        "StackTrace": [
          "at Npgsql.NpgsqlConnector.<>c__DisplayClass170_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()",
          "--- End of stack trace from previous location ---",
          "at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)",
          "at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)",
          "at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)",
          "at Dapper.SqlMapper.ExecuteImplAsync(IDbConnection cnn, CommandDefinition command, Object param) in /_/Dapper/SqlMapper.Async.cs:line 687",
          "at Service.MessageQueueProcessor.ReportHandler.Execute(DeliveredMessage dm) in C:\\Development\\RabbitMQ\\src\\Cron.Service\\MessageQueueProcessor.cs:line 169"
        ]
      }

Activity

  1. changed the title [-]Exception "In multiplexing mode, transactions must be started with BeginTransaction" without Multiplexing[/-] [+]Exception "In multiplexing mode, transactions must be started with BeginTransaction" without Multiplexing with 5.0.0-preview1[/+] on Oct 19, 2020
  2. kae commented on Oct 20, 2020

    @kae
    Author

    Interestingly, when adding "Multiplexing=true" to connection string then for Enumerable.Range(0, 100) it's throwing in 1 out of 5-6 runs

    Npgsql.NpgsqlOperationInProgressException (0x80004005): The connection is already in state 'Executing'
       at Npgsql.NpgsqlConnector.<StartUserAction>g__DoStartUserAction|205_0(<>c__DisplayClass205_0& )
       at Npgsql.NpgsqlConnector.StartUserAction(ConnectorState newState, NpgsqlCommand command)
       at Npgsql.NpgsqlConnection.BeginTransaction(IsolationLevel level, Boolean async, CancellationToken cancellationToken)
       at Npgsql.NpgsqlConnection.BeginTransaction(IsolationLevel level)
       at Npgsql.NpgsqlConnection.BeginTransactionAsync(IsolationLevel level, CancellationToken cancellationToken)
    --- End of stack trace from previous location ---
       at pgTest.Program.Test(Int32 i) in C:\Users\kae\Dump\dnx\pgTest\Program.cs:line 15
    

    And for Enumerable.Range(0, 1000) it hangs for a minutes and than gets multiple pool exhaustion exceptions like

    Npgsql.NpgsqlException (0x80004005): The connection pool has been exhausted, either raise MaxPoolSize (currently 100) or Timeout (currently 15 seconds)
       at Npgsql.ConnectorPool.<>c__DisplayClass38_0.<<Rent>g__RentAsync|0>d.MoveNext()
    --- End of stack trace from previous location ---
       at Npgsql.NpgsqlConnection.<>c__DisplayClass148_0.<<StartBindingScope>g__StartBindingScopeAsync|0>d.MoveNext()
    --- End of stack trace from previous location ---
       at Npgsql.ConnectorPool.BootstrapMultiplexing(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
       at Npgsql.NpgsqlConnection.<>c__DisplayClass41_0.<<Open>g__BootstrapMultiplexing|1>d.MoveNext()
    --- End of stack trace from previous location ---
       at pgTest.Program.Test(Int32 i) in C:\Users\kae\Dump\dnx\pgTest\Program.cs:line 14
    

    followed with

    Npgsql.NpgsqlOperationInProgressException (0x80004005): The connection is already in state 'Executing'
       at Npgsql.NpgsqlConnector.<StartUserAction>g__DoStartUserAction|205_0(<>c__DisplayClass205_0& )
       at Npgsql.NpgsqlConnector.StartUserAction(ConnectorState newState, NpgsqlCommand command)
       at Npgsql.NpgsqlConnector.Rollback(Boolean async, CancellationToken cancellationToken)
       at Npgsql.NpgsqlTransaction.Rollback()
       at Npgsql.NpgsqlTransaction.Dispose(Boolean disposing)
       at System.Data.Common.DbTransaction.Dispose()
       at pgTest.Program.Test(Int32 i) in C:\Users\kae\Dump\dnx\pgTest\Program.cs:line 17
    

    and

    Npgsql.NpgsqlException (0x80004005): Exception while reading from stream
     ---> System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine..
     ---> System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine.
       at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
       --- End of inner exception stack trace ---
       at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
       at Npgsql.NpgsqlReadBuffer.<>c__DisplayClass37_0.<<Ensure>g__EnsureLong|0>d.MoveNext()
       at Npgsql.NpgsqlReadBuffer.<>c__DisplayClass37_0.<<Ensure>g__EnsureLong|0>d.MoveNext()
    --- End of stack trace from previous location ---
       at Npgsql.NpgsqlConnector.<>c__DisplayClass170_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
    --- End of stack trace from previous location ---
       at Npgsql.NpgsqlConnector.<>c__DisplayClass170_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
    --- End of stack trace from previous location ---
       at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
       at Npgsql.NpgsqlDataReader.Consume(Boolean async, CancellationToken cancellationToken)
       at Npgsql.NpgsqlDataReader.Close(Boolean connectionClosing, Boolean async)
       at Npgsql.NpgsqlConnector.CloseOngoingOperations(Boolean async, CancellationToken cancellationToken)
       at Npgsql.NpgsqlTransaction.Dispose(Boolean disposing)
       at System.Data.Common.DbTransaction.Dispose()
       at pgTest.Program.Test(Int32 i) in C:\Users\kae\Dump\dnx\pgTest\Program.cs:line 17
    

    and

    System.NullReferenceException: Object reference not set to an instance of an object.
       at Npgsql.NpgsqlConnector.<>c__DisplayClass170_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
    --- End of stack trace from previous location ---
       at Npgsql.NpgsqlConnector.<>c__DisplayClass170_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
    --- End of stack trace from previous location ---
       at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
       at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
       at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
       at Dapper.SqlMapper.QueryRowAsync[T](IDbConnection cnn, Row row, Type effectiveType, CommandDefinition command) in /_/Dapper/SqlMapper.Async.cs:line 483
       at pgTest.Program.Test(Int32 i) in C:\Users\kae\Dump\dnx\pgTest\Program.cs:line 16
    
  3. vonzshik commented on Oct 20, 2020

    @vonzshik
    Contributor

    Hello!

    I was able to reproduce the first error. It seems to be because the connector is returned to the pool, and only after that we clear the reference to the connection.

    if (Settings.Multiplexing)
    {
    // We've already closed ongoing operations and rolled back any transaction, so we must be
    // unbound. Nothing to do.
    Debug.Assert(ConnectorBindingScope == ConnectorBindingScope.None);
    }
    else
    _pool.Return(connector);
    }
    }
    connector.Connection = null;

    The second error (Multiplexing with Enumerable.Range(0, 100)), I was unable to reproduce.

    The third error seems to be from the multiplex bootstrap, which is in no way, shape or form is threadsafe.

    await _pool!.BootstrapMultiplexing(this, timeout, async, cancellationToken2);

    What do you say, @roji?

  4. roji commented on Oct 21, 2020

    @roji
    Member

    For the first error, good analysis @vonzshik. I actually missed your comment and just tracked it down myself... 🤦 Should learn to read all the way to the bottom...

    So #3247 fixes this, adds various assertions to tighten things and simplifies a bit too. The PR has a test for reproducing the bug too. @vonzshik do you want to take a look to see if this bug also exists in 4.1?

  5. roji commented on Oct 21, 2020

    @roji
    Member

    The timeout exception is likely to be a totally unrelated environmental thing. @kae if you manage to put some sort of repro together, can you open another issue and we'll take a look?

    @vonzshik why do you say that multiplexing bootstrap isn't threadsafe? I agree it doesn't make sense to run it concurrently (we should put a simple lock there), but where do you see errors coming from it? Either way, am happy if you want to work on it and propose a fix :)

    ... and thanks for the bug report and the repro @kae!

  6. roji commented on Oct 21, 2020

    @roji
    Member

    One last thing... @kae can you please open a separate issue for the error when Multiplexing=true? We'll use this issue to track the original problem.

  7. vonzshik commented on Oct 21, 2020

    @vonzshik
    Contributor

    So #3247 fixes this, adds various assertions to tighten things and simplifies a bit too. The PR has a test for reproducing the bug too. @vonzshik do you want to take a look to see if this bug also exists in 4.1?

    Just checked - nope, it should be fine. It only happens if there is an open transaction.

    if (connection.EnlistedTransaction != null)
    {
    // Close the connection and disconnect it from the resource manager but leave the connector
    // in a enlisted pending list in the pool.
    if (connection.Settings.Pooling)
    connection._pool!.AddPendingEnlistedConnector(connector, connection.EnlistedTransaction);
    // If a non-pooled connection is being closed but is enlisted in an ongoing
    // TransactionScope, simply detach the connector from the connection and leave
    // it open. It will be closed when the TransactionScope is disposed.
    connector.Connection = null;
    connection.EnlistedTransaction = null;
    }

  8. kae commented on Oct 21, 2020

    @kae
    Author
  9. vonzshik commented on Oct 21, 2020

    @vonzshik
    Contributor

    @vonzshik why do you say that multiplexing bootstrap isn't threadsafe? I agree it doesn't make sense to run it concurrently (we should put a simple lock there), but where do you see errors coming from it? Either way, am happy if you want to work on it and propose a fix :)

    This is a tricky one. I'm still investigating the exact problem, but I do have a fix for the bootstrap. Also found a few other problems.

  10. roji commented on Oct 21, 2020

    @roji
    Member

    Just checked - nope, it should be fine. It only happens if there is an open transaction.

    I'd still fix that in 4.1. It's definitely much more of a corner case than the 5.0 bug discussed here, but we still should never be touching a connector after returning it to the pool in any way - it's very likely possible to trigger a similar bug with ambient transactions. Let me know if you want to submit a PR.

  11. added this to the 5.0.0 milestone on Oct 21, 2020
  12. vonzshik commented on Oct 21, 2020

    @vonzshik
    Contributor

    Just checked - nope, it should be fine. It only happens if there is an open transaction.

    I'd still fix that in 4.1. It's definitely much more of a corner case than the 5.0 bug discussed here, but we still should never be touching a connector after returning it to the pool in any way - it's very likely possible to trigger a similar bug with ambient transactions. Let me know if you want to submit a PR.

    Sure, why not.

  13. added a commit that references this issue on Oct 21, 2020
    ad88342
  14. added a commit that references this issue on Oct 21, 2020
    5c11766
  15. added theissue type on Jun 18, 2025
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