Skip to content

Received unexpected backend message DataRow #2913

Closed

Description

@meum

Steps to reproduce

    class Program
    {
        const string connectionString = "Server=127.0.0.1;Port=5432;Database=postgres;User Id=postgres;Password=postgres;";
        const int numThreads = 5;
        static SemaphoreSlim s = new SemaphoreSlim(0);
        static CountdownEvent c = new CountdownEvent(numThreads);

        static void Main(string[] args)
        {

            try
            {
                CreateTable();

                var tasks = new List<Task>();
                var synchronizer = Task.Run(() =>
                {
                    while (true)
                    {
                        s.Release(numThreads);
                        while (c.CurrentCount > 0)
                        {
                            c.Wait();
                        }

                        c.Reset();
                    }
                });
                tasks.Add(synchronizer);

                for (int i = 0; i < numThreads; i++)
                {
                    tasks.Add(Task.Run(RunQueries));
                }
                Task.WaitAll(tasks.ToArray());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        static IDbConnection GetDbConnection()
        {
            return new NpgsqlConnection(connectionString);
        }

        static void CreateTable()
        {
            using (var db = GetDbConnection())
            {
                string script = "CREATE TABLE IF NOT EXISTS testbug(id TEXT PRIMARY KEY, value int)";
                db.Execute(script);
            }
        }

        static void RunQueries()
        {
            string script1 = @"
                    SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;

                    INSERT INTO testbug (id, value)
                    VALUES ('abc', 1)
                    ON CONFLICT (id) DO UPDATE 
                    SET value = testbug.value + 1
                    RETURNING value;";

            while (true)
            {
                s.Wait();

                using (var db = GetDbConnection())
                {
                    try
                    {
                        var result = db.QuerySingle<int>(script1);
                        Console.WriteLine($"Got result {result} inside try");
                    }
                    catch (Exception e) when (e.Message.Contains("Please file a bug"))
                    {
                        Console.WriteLine("Got the bug in the try");
                        Console.WriteLine(e);
                        Environment.Exit(1);
                    }
                    catch (Exception e) when (e.Message.Contains("could not serialize access"))
                    {
                        try
                        {
                            var result = db.QuerySingle<int>("SELECT 1234");
                            Console.WriteLine($"Got result {result} inside catch");
                        }
                        catch (Exception ex) when (ex.Message.Contains("Please file a bug"))
                        {
                            Console.WriteLine("Got the bug in the catch");
                            Console.WriteLine(ex);
                            Environment.Exit(1);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }

                c.Signal();
            }
        }
    }

The issue

When running any query shortly after a "could not serialize access" error I sometimes get this exception:

System.Exception: Received unexpected backend message DataRow. Please file a bug.
   at Npgsql.NpgsqlDataReader.ProcessDataRowMessage(DataRowMessage msg)
   at Npgsql.NpgsqlDataReader.ProcessMessage(IBackendMessage msg)
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)
   at Npgsql.NpgsqlDataReader.NextResult()
   at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior)
   at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
   at Dapper.SqlMapper.ExecuteReaderWithFlagsFallback(IDbCommand cmd, Boolean wasClosed, CommandBehavior behavior) in C:\projects\dapper\Dapper\SqlMapper.cs:line 1051
   at Dapper.SqlMapper.QueryRowImpl[T](IDbConnection cnn, Row row, CommandDefinition& command, Type effectiveType) in C:\projects\dapper\Dapper\SqlMapper.cs:line 1177
   at Dapper.SqlMapper.QuerySingle[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType) in C:\projects\dapper\Dapper\SqlMapper.cs:line 781
   at NpgsqlBug.Program.RunQueries() in C:\Work\Code\NpgsqlBug\Program.cs:line 98

Further technical details

Npgsql version: 4.1.3.1
PostgreSQL version: 11.2
Operating system: Windows 10

Other details about my project setup:
Dapper version: 2.0.30
netcoreapp3.1

Activity

  1. roji commented on Apr 3, 2020

    @roji
    Member

    Where is the "could not serialize access" coming from? Could you please post a stack trace for that exception as well?

  2. meum commented on Apr 3, 2020

    @meum
    Author

    It comes from doing concurrent upserts on the same row with isolation level REPEATABLE READ, so that is expected I think.

    Here is the stack trace:

    Npgsql.PostgresException (0x80004005): 40001: could not serialize access due to concurrent update
       at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at Npgsql.NpgsqlDataReader.<>c__DisplayClass41_0.<<ReadMessage>g__ReadMessageSequential|0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)
       at Npgsql.NpgsqlDataReader.NextResult()
       at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
       at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior)
       at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
       at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
       at Dapper.SqlMapper.ExecuteReaderWithFlagsFallback(IDbCommand cmd, Boolean wasClosed, CommandBehavior behavior) in C:\projects\dapper\Dapper\SqlMapper.cs:line 1051
       at Dapper.SqlMapper.QueryRowImpl[T](IDbConnection cnn, Row row, CommandDefinition& command, Type effectiveType) in C:\projects\dapper\Dapper\SqlMapper.cs:line 1177
       at Dapper.SqlMapper.QuerySingle[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType) in C:\projects\dapper\Dapper\SqlMapper.cs:line 781
       at NpgsqlBug.Program.RunQueries() in C:\Work\Code\NpgsqlBug\Program.cs:line 86
      Exception data:
        Severity: ERROR
        SqlState: 40001
        MessageText: could not serialize access due to concurrent update
        File: d:\pginstaller.auto\postgres.windows-x64\src\backend\executor\nodemodifytable.c
        Line: 225
        Routine: ExecCheckHeapTupleVisible
    
  3. roji commented on Apr 3, 2020

    @roji
    Member

    Thanks for the additional info, I'll take a look at this soon.

  4. roji commented on Apr 3, 2020

    @roji
    Member

    (@YohDeadfall are you interested in taking a look?)

  5. roji commented on Apr 10, 2020

    @roji
    Member
  6. phillip-haydon commented on May 2, 2020

    @phillip-haydon

    I just upgraded from 4.1.2 to 4.1.3.1 and started getting this error too :(

    Message: Received unexpected backend message DataRow. Please file a bug.

    
    Npgsql.NpgsqlDataReader.ProcessDataRowMessage(DataRowMessage msg) in C:\projects\npgsql\src\Npgsql\NpgsqlDataReader.cs:699
    Npgsql.NpgsqlDataReader.ProcessMessage(IBackendMessage msg) in C:\projects\npgsql\src\Npgsql\NpgsqlDataReader.cs:620
    Npgsql.NpgsqlDataReader+<NextResult>d__44.MoveNext() in C:\projects\npgsql\src\Npgsql\NpgsqlDataReader.cs:500
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw():12
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task):55
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task):40
     
    Npgsql.NpgsqlDataReader.NextResult() in C:\projects\npgsql\src\Npgsql\NpgsqlDataReader.cs:298
    Npgsql.NpgsqlCommand+<ExecuteReaderAsync>d__102.MoveNext() in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:1206
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw():12
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task):55
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task):40
     
    Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior) in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:1076
    Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior) in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:1052
    System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
    Dapper.SqlMapper.ExecuteReaderWithFlagsFallback(IDbCommand cmd, Boolean wasClosed, CommandBehavior behavior) in /_/Dapper/SqlMapper.cs:1051
    Dapper.SqlMapper+<QueryImpl>d__140`1.MoveNext() in /_/Dapper/SqlMapper.cs:1079
    System.Collections.Generic.List`1..ctor(IEnumerable`1 collection):119
    System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source):14
     
    Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in /_/Dapper/SqlMapper.cs:721
    
  7. self-assigned this
    on May 14, 2020
  8. added this to the 4.1.4 milestone on May 14, 2020
  9. modified the milestones: 4.1.4, 4.1.5 on Jul 19, 2020
  10. vonzshik commented on Sep 2, 2020

    @vonzshik
    Contributor

    Hello @YohDeadfall, I've managed to identify the issue. It's kind of similar to the one I've described here #2964.

    There are 2 requirements:

    1. When executing Reader, use CommandBehavior.CloseConnection.
    2. Use queries with multiple statement (not really a requirement, but it make it easier).

    So, it follows like this:

    1. First query fails with error from PG, so connection is not broken.
      // An ErrorResponse is (almost) always followed by a ReadyForQuery. Save the error
      // and throw it as an exception when the ReadyForQuery is received (next).
      error = PostgresException.Load(ReadBuffer, Settings.IncludeErrorDetails);
    2. Started to clean up reader.
      if (CurrentReader != null)
      {
      // The reader cleanup will call EndUserAction
      await CurrentReader.Cleanup(async);
      }
    3. While cleaning up reader, we close connection (which returns it to the pool).
      else if (_behavior.HasFlag(CommandBehavior.CloseConnection) && !connectionClosing)
      _connection.Close();
    4. We start second query, which uses connection from the first one (as it's already in the pool).
    5. Second query resets reader, StatementIndex = -1 .
      reader.Init(this, behavior, _statements, sendTask);
    6. Exception from first query bubbles up to NpgsqlDataReader (it's the same one second query just reset). There, we increment StatementIndex.
      catch (Exception e)
      {
      State = ReaderState.Consumed;
      // Reference the triggering statement from the exception (for batching)
      if (e is PostgresException postgresException &&
      StatementIndex >= 0 && StatementIndex < _statements.Count)
      {
      postgresException.Statement = _statements[StatementIndex];
      }
      // An error means all subsequent statements were skipped by PostgreSQL.
      // If any of them were being prepared, we need to update our bookkeeping to put
      // them back in unprepared state.
      for (; StatementIndex < _statements.Count; StatementIndex++)
      {
      var statement = _statements[StatementIndex];
      if (statement.IsPreparing)
      {
      statement.IsPreparing = false;
      statement.PreparedStatement!.CompleteUnprepare();
      }
      }
      throw;
      }
    7. Worst case scenario, first and second query increment StatementIndex and the same time. Because of this, there is a chance we can skip reading messages for some statements, so they are still in the buffer after everything is done.
    8. Some time later, third query begins to execute reader. As there are still some messages in the buffer, reading them most likely will break reader.

    I've managed to write a test for this issue (although, it's not ideal and can be finicky).

    [Test]
    public async Task ReaderStatementIndexBug()
    {
    	var firstMrs = new ManualResetEventSlim(false);
    	var secondMrs = new ManualResetEventSlim(false);
    
    	var secondQuery = Task.Run(() =>
    	{
    		firstMrs.Wait();
    		using var conn = OpenConnection();
    		using var cmd = new NpgsqlCommand(@"SELECT 1; SELECT 2;", conn);
    		using var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    
    		Assert.That(reader.StatementIndex, Is.EqualTo(0));
    		secondMrs.Wait();
    		// Already an error as it shouldn't change
    		Assert.That(reader.StatementIndex, Is.EqualTo(2));
    	});
    
    	using (var conn = OpenConnection())
    	{
    		try
    		{
    			using var cmd = new NpgsqlCommand(@"SELECT 1; SELECT * FROM NotExistingTable;", conn);
    			using var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    
    			Assert.That(reader.StatementIndex, Is.EqualTo(0));
    
    			reader.ReaderClosed += (s, e) =>
    			{
    				firstMrs.Set();
    				Thread.Sleep(100);
    			};
    		}
    		catch (NpgsqlException) { }
    
    		secondMrs.Set();
    	}
    
    	await secondQuery;
    
    	using var thirdConn = OpenConnection();
    	using var thirdCmd= new NpgsqlCommand(@"SELECT 1; SELECT 2;", thirdConn);
    	using var thirdReader = thirdCmd.ExecuteReader(CommandBehavior.CloseConnection);
    }
  11. roji commented on Sep 6, 2020

    @roji
    Member

    @vonzshik thanks for looking into this! That's very helpful.

  12. modified the milestones: 4.1.5, 4.1.6 on Sep 28, 2020
  13. YohDeadfall commented on Nov 14, 2020

    @YohDeadfall
    Contributor

    Was it fixed, @vonzshik? If so, is it possible to backport? If not, it would change the milestone and just close the issue.

  14. vonzshik commented on Nov 14, 2020

    @vonzshik
    Contributor

    @YohDeadfall was not yet fixed - hopefully, #3126 should be merged today.

  15. vonzshik commented on Nov 14, 2020

    @vonzshik
    Contributor

    And yes, it should be possible to backport.

  16. roji commented on Nov 14, 2020

    @roji
    Member

    The way #3126 is looking, I do not think this is a good candidate for backporting... The fix is quite complex and changes a lot of state, and while this is indeed a bug, not a lot of people seem to be running into it (plus 5.0 is right around the corner).

  17. modified the milestones: 4.1.6, 5.0.0 on Nov 14, 2020
  18. added a commit that references this issue on Nov 15, 2020
    7bb2617
  19. 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