Skip to content

Npgsql.NpgsqlException (0x80004005): Received backend message ParseComplete while expecting CommandCompleteMessage. Please file a bug. #3681

Closed as not planned

Description

@latop2604

The issue

Since we updated our app to Npgsql 5, we randomly get this exception. It not to often but at least once per day.

The error happen inside an Hangfire job. With Hangfire.PostgreSql 1.8.4

Exception message: Received backend message ParseComplete while expecting CommandCompleteMessage. Please file a bug.
Stack trace:
Npgsql.NpgsqlException (0x80004005): Received backend message ParseComplete while expecting CommandCompleteMessage. Please file a bug.
   at Npgsql.NpgsqlConnector.ExecuteInternalCommand(Byte[] data, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Rollback(Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlTransaction.Rollback()
   at Npgsql.NpgsqlTransaction.Dispose(Boolean disposing)
   at Front.Core.Storage.KeyDocument.Storages.NpgStorage.SetAsync[T](IEnumerable`1 docs, Func`2 keyFunctor)
...

Further technical details

Npgsql version: 5.0.4
PostgreSQL version: PostgreSQL 11.4
Operating system: (Ubuntu 11.4-1.pgdg16.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609, 64-bit

Steps to reproduce

// keyFunctor : () => typeof(T).Name
public async Task SetAsync<T>(IEnumerable<T> docs, Func<T, string> keyFunctor)
    where T : IDocument
{
    foreach (var doc in docs)
    {
        StorageHelpers.SetMeta(doc, _context.GetUserName(), _context.GetTenantId());
    }

    string query = $@"
                INSERT INTO {FullQualifiedTableName()} 
                    (key, content, creationdate, creationuser, modificationdate, modificationuser)
                VALUES 
                    (@key, @content::jsonb, @creationdate, @creationuser, @modificationdate, @modificationuser)
                ON CONFLICT (key) DO UPDATE 
                SET 
                    content = EXCLUDED.content,
                    modificationdate = @modificationdate,
                    modificationuser = @modificationuser";
    var param = docs.Select(doc => new
    {
        key = keyFunctor(doc),
        content = doc,
        creationdate = doc._metas.CreationDate,
        creationuser = doc._metas.CreationUser,
        modificationdate = doc._metas.ModificationDate,
        modificationuser = doc._metas.ModificationUser
    });
    using var cnx = new NpgsqlConnection(_masterConnectionString);

    await cnx.OpenAsync();
    cnx.TypeMapper.UseJsonNet(settings: NpgStructure.JsonSerializerSettings);

    using var trann = cnx.BeginTransaction();

    foreach (var d in param)
    {
        using (var cmd = new NpgsqlCommand(query, cnx, trann))
        {
            cmd.Parameters.Add(new NpgsqlParameter("key", NpgsqlDbType.Text) { Value = d.key });
            cmd.Parameters.Add(new NpgsqlParameter("content", NpgsqlDbType.Jsonb) { Value = d.content });
            cmd.Parameters.Add(new NpgsqlParameter("creationdate", NpgsqlDbType.Timestamp) { Value = d.creationdate });
            cmd.Parameters.Add(new NpgsqlParameter("creationuser", NpgsqlDbType.Text) { Value = d.creationuser });
            cmd.Parameters.Add(new NpgsqlParameter("modificationdate", NpgsqlDbType.Timestamp) { Value = d.modificationdate });
            cmd.Parameters.Add(new NpgsqlParameter("modificationuser", NpgsqlDbType.Text) { Value = d.modificationuser });
            await cmd.ExecuteNonQueryAsync();
        }
    }
    await trann.CommitAsync();
}

public interface IDocument
{
    string UniqueIdentifier { get; }
    PersistenceMetas _metas { get; set; }
}
public class PersistenceMetas
{
    public string TenantId { get; set; }
    public DateTime CreationDate { get; set; }
    public string CreationUser { get; set; }
    public DateTime ModificationDate { get; set; }
    public string ModificationUser { get; set; }
    public int ModificationsCount { get; set; } = 0;
}

/*
CREATE SCHEMA IF NOT EXISTS ""{schema}"";
CREATE TABLE IF NOT EXISTS ""{schema}"".""{tableName}""
(
    key text NOT NULL,
    content jsonb,
    creationdate timestamp without time zone,
    creationuser text,
    modificationdate timestamp without time zone,
    modificationuser text,
    CONSTRAINT ""{tableName}_pkey"" PRIMARY KEY(key)
);
*/

Activity

  1. vonzshik commented on Apr 23, 2021

    @vonzshik
    Contributor

    Hello! While I've been unable to reproduce the problem, it seems there is another exception happening while calling cmd.ExecuteNonQueryAsync (or trann.CommitAsync). Could you please catch it and post it here? Also, please check that you're using the latest version of Npgsql.Json.NET.

  2. latop2604 commented on Apr 23, 2021

    @latop2604
    Author

    Npgsql.Json.NET : 5.0.4

    I will try to find this other exception

  3. MirreJensen commented on Apr 27, 2021

    @MirreJensen

    Got the same on ef-core npgsql/efcore.pg#1826

  4. ytnn commented on Jul 23, 2021

    @ytnn

    Hello. I have the same issue on npgsql 5.0.7. Randomlly we are getting an error:

    Npgsql.NpgsqlException (0x80004005): Received backend message RowDescription while expecting ParseCompleteMessage. Please file a bug.
       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 Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
       at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
       at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
       at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
    
    Npgsql.NpgsqlException (0x80004005): Received backend message RowDescription while expecting ParseCompleteMessage. Please file a bug.
       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 Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
       at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
       at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
       at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
       at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
    

    This problem becomes more and more crytical for us, please make a fix.

  5. vonzshik commented on Jul 23, 2021

    @vonzshik
    Contributor

    @ytnn does this exception always happen on the exact same query, or is it always a different one?

  6. ytnn commented on Jul 23, 2021

    @ytnn

    @vonzshik it happens on different queries to different tables. Problem was detected at the begining of June without any changes in nuget packages, then I updated package Npgsql.EntityFrameworkCore.PostgreSQL from 3.1.2 to 5.0.6, but problem was not gone. Now we updated version to 5.0.7 but we don't really know will it helps or not, because it happens randomly only on our production environment and we can't waiting anymore for knowing that. If you need any information from our DBA about postgres configuration I can ask them.

  7. vonzshik commented on Jul 23, 2021

    @vonzshik
    Contributor

    @ytnn one more question: are there any other exceptions happening beside that one? Specifically, I'm interested whether there were any cancellations.

    One thing you can do right now is to enable npgsql's logging (you can find more info here) and post the results here.

  8. ytnn commented on Jul 23, 2021

    @ytnn

    @vonzshik I've checked logs and didn't see other exceptions. But I saw something interesting: different applications, which working with the same database, simultaneously registered this error accurate to milliseconds.

  9. vonzshik commented on Jul 23, 2021

    @vonzshik
    Contributor

    @ytnn that's very interesting indeed. Maybe there is something in the database logs at the time of this error? Also, is the database on-premise, or on-cloud (azure, amazon)?

    One more question: does the error always say 'Received backend message RowDescription while expecting ParseCompleteMessage', or maybe it differs from time to time (other backend message types)?

  10. ytnn commented on Jul 23, 2021

    @ytnn

    @vonzshik I agree with you about database. We will check logs. Now I think that something wrong going in the database and then your package just make an incorrect error message.
    Also I've check logs and detect another errors: "Received backend message CompletedResponse while expecting ParseCompleteMessage" and "Received backend message ReadyForQuery while expecting ParseCompleteMessage".

  11. roji commented on Jul 26, 2021

    @roji
    Member

    @tynn one additional question that may help us understand what's going on - are you using the keepalive feature? If you are, any chance you can try running without it, to see if that makes the problem go away?

  12. roji commented on Jul 26, 2021

    @roji
    Member

    Sorry @tynn, yes - the question above was addressed to @ytnn.

  13. ytnn commented on Jul 27, 2021

    @ytnn

    @roji no, we don't use keepalive, I have already checked this feature, when I was reading similar topics. Also we checked database logs and didn't see any errors at the time when our application raised an error. But we found in the database logs a lot of "could not send data to client: Broken pipe" error. Unfortunately it occurred in different time and too many times, while we had only one "while expecting ParseCompleteMessage" error at that day. So, we still don't know what exactly causes an error.

  14. vonzshik commented on Jul 27, 2021

    @vonzshik
    Contributor

    @ytnn I think the next thing you can do is to gather npgsql logs (you can find more info here).

  15. tpooch21 commented on Aug 17, 2021

    @tpooch21

    @vonzshik Thank you for your response on my duplicate issue filing. We have already enabled npgsql logging and are receiving the following exception:

    Npgsql.NpgsqlTransaction" Error: Unhandled postgres exception related to pg connection 159815383: "Received backend message BindComplete while expecting ReadyForQueryMessage. Please file a bug."

    It seems as though this is only happening with BindComplete backend messages. We are also running into the following Cancellation token exception occasionally, though not nearly as frequently:

    "Npgsql.NpgsqlTransaction" Error: Unhandled postgres exception related to pg connection 1042185957: "The CancellationTokenSource has been disposed."

    When we encounter this CancellationToken exception, it directly follows the BindComplete exception on the same connection, so it seems more so to be a product of the BindComplete issue we're running into.

    Please let me know if there are any additional logs that might be helpful for you. Thanks!

  16. vonzshik commented on Aug 17, 2021

    @vonzshik
    Contributor

    @tpooch21 what I'm really interested in, is what exactly the connection which throws the exception was doing beforehand. In my opinion that's a concurrency issue, so by analyzing the last actions of a connection we should be able to limit the scope.

    Also, could you please post the stack traces for both exceptions?

  17. vonzshik commented on Aug 17, 2021

    @vonzshik
    Contributor

    @tpooch21 the trace logs from npgsql should really help us here.

  18. tpooch21 commented on Aug 17, 2021

    @tpooch21

    @vonzshik Unfortunately, we don't have logging at the trace level enabled in our production environment, and the logs that we're seeing aren't producing stack traces. I know that makes it difficult for you to figure out what's going on. At the moment, we're not experiencing trouble, but if we do, we will consider lowering our minimum log level and get back to you with more details. Thank you.

  19. roji commented on Mar 9, 2023

    @roji
    Member

    Closing for age/inactivity. If the issue still occurs, we still need trace logs in order to investigate it further...

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

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions