Skip to content

Multiplexing bugs #4683

Closed as not planned
Closed as not planned

Description

@NinoFloris

For a bit of code like this (note the connection string, multiplexing enabled, and a pool of 1)

public class Benchmark
{
    const string EndPoint = "127.0.0.1:5432";
    const string Username = "postgres";
    const string Password = "postgres123";
    const string Database = "postgres";

    const string ConnectionString = $"Server={EndPoint};User ID={Username};Password={Password};Database=postgres;SSL Mode=Disable;Pooling=true;MaxPoolSize=1;Max Auto Prepare=0;Multiplexing=true";
    const int PipelinedCommands = 1000;

    [Test]
    [Benchmark(Baseline = true, OperationsPerInvoke = PipelinedCommands)]
    public async ValueTask Pipelining()
    {
        await using var conn = new NpgsqlConnection(ConnectionString);
        await conn.OpenAsync();
        var commandText = $"SELECT true";

        var readerTasks = new Task<NpgsqlDataReader>[PipelinedCommands];
        for (var i = 0; i < readerTasks.Length; i++)
        {
            readerTasks[i] = new NpgsqlCommand(commandText, conn).ExecuteReaderAsync();
        }

        for (var i = 0; i < readerTasks.Length; i++)
        {
            //await Task.Delay(1); // uncomment in benchmark to 'fix' the 'Fetching' race
            await using var reader = await readerTasks[i];
            while (await reader.ReadAsync()) // put a breakpoint here and run test in the debugger
            {

            }
        }
    }
}

Running this as a benchmark you'll almost always get this exception - at random indices - this is clearly some race.

 ---> Npgsql.NpgsqlOperationInProgressException (0x80004005): The connection is already in state 'Fetching'
   at Npgsql.Internal.NpgsqlConnector.<StartUserAction>g__DoStartUserAction|272_0(ConnectorState newState, NpgsqlCommand command, <>c__DisplayClass272_0&)
   at Npgsql.Internal.NpgsqlConnector.StartUserAction(ConnectorState newState, NpgsqlCommand command, CancellationToken cancellationToken, Boolean attemptPgCancellation)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)

Then when suppressing this exception by try catching inside the second loop, the next one to show up is:

 ---> System.InvalidOperationException: The reader is closed
   at Npgsql.NpgsqlDataReader.ReadAsync(CancellationToken cancellationToken)

And suppressing that one shows the next one:

 ---> Npgsql.NpgsqlException (0x80004005): Unknown message code: 0
   at Npgsql.Util.PGUtil.ValidateBackendMessageCode(BackendMessageCode code)
   at Npgsql.Internal.NpgsqlConnector.ReadMessage(Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications)
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)

And the next one:

 ---> Npgsql.NpgsqlException (0x80004005): Received backend message ReadyForQuery while expecting ParseCompleteMessage. Please file a bug.
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)

And the next one:

 ---> Npgsql.NpgsqlException (0x80004005): Received backend message CommandComplete while expecting ParseCompleteMessage. Please file a bug.
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Pipelines.Benchmark.Benchmarks.Pipelines()
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Pipelines.Benchmark.Benchmarks.Pipelines()
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at BenchmarkDotNet.Autogenerated.Runnable_0.<.ctor>b__3_4()
   at BenchmarkDotNet.Autogenerated.Runnable_0.WorkloadActionNoUnroll(Int64 invokeCount) 
   at BenchmarkDotNet.Engines.Engine.RunIteration(IterationData data)
   at BenchmarkDotNet.Engines.EngineStage.RunIteration(IterationMode mode, IterationStage stage, Int32 index, Int64 invokeCount, Int32 unrollFactor)
   at BenchmarkDotNet.Engines.EnginePilotStage.RunAuto()
   at BenchmarkDotNet.Engines.EnginePilotStage.Run()
   at BenchmarkDotNet.Engines.Engine.Run()
   at BenchmarkDotNet.Autogenerated.Runnable_0.Run(IHost host, String benchmarkName)
--- End of stack trace from previous location ---
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)
--- End of stack trace from previous location ---
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Util.ManualResetValueTaskSource`1.GetResult(Int16 token)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
#snip#
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

And finally

 ---> System.InvalidOperationException: Connection is not open
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.Pipelines.Benchmark.Benchmarks.ReadNpgsql() in /Users/nfloris/Projects/Misc/Npgsql.Pipelines/Npgsql.Pipelines.Benchmark/Benchmarks.cs:line 72
   at Npgsql.Pipelines.Benchmark.Benchmarks.ReadNpgsql() in /Users/nfloris/Projects/Misc/Npgsql.Pipelines/Npgsql.Pipelines.Benchmark/Benchmarks.cs:line 66

The exception filter looks like this at the end 🤣

when (ex.Message.Contains("'Fetching'") || ex.Message.Contains("closed")  || ex.Message.Contains("message code: ") || ex.Message.Contains("ReadyForQuery") || ex.Message.Contains("CommandComplete")  || ex.Message.Contains("not open"))

The next one is also interesting, putting a breakpoint where marked, and running the code as a nunit test I consistently get:

Npgsql.NpgsqlException : Received backend message BindComplete while expecting ParseCompleteMessage. Please file a bug.
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)

This one only seems to occur under the debugger, always at index 0 and only when the number of pipelined commands is big enough.

Part of: #3991

EDIT:

Additionally, not making a new command everytime deadlocks the app, as every additional call to ExecuteReaderAsync resets the ExecutionCompletion tcs without checking if it's actually in use.

Activity

  1. vonzshik commented on Sep 28, 2022

    @vonzshik
    Contributor

    Tried to reproduce with the latest preview and 6.0.7 - no dice. Just to check, were you running this on ARM or x86?

  2. vonzshik commented on Sep 28, 2022

    @vonzshik
    Contributor

    Though that doesn't matter, I already see where the problem might come from.

    Here we bind a connector to a connection.

    connector = await new ValueTask<NpgsqlConnector>(ExecutionCompletion, ExecutionCompletion.Version);
    // TODO: Overload of StartBindingScope?
    conn.Connector = connector;
    connector.Connection = conn;
    conn.ConnectorBindingScope = ConnectorBindingScope.Reader;

    But before that we try to get a bound connector.

    Debug.Assert(conn is not null);
    conn.TryGetBoundConnector(out connector);

    If we're unlucky, at that point the connector is bound to the connection, and as such we'll try to use concurrently with the aforementioned results.

  3. added this to the Backlog milestone on Mar 9, 2023
  4. NinoFloris commented on Mar 14, 2026

    @NinoFloris
    MemberAuthor

    Multiplexing is no more.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions