Skip to content

Corrupt auto-prepared statements after rollback. #6391

Open

Description

@AVee

After two days of pulling my hair out over this:

using System.Data;
using Npgsql;

var connectionString = new NpgsqlConnectionStringBuilder()
{
    Host = "/var/run/postgresql/",
    Port = 5433,
    Database = "test",
    MaxPoolSize = 1, // To ensure everything happens on the same connection
    MinPoolSize = 1,
    MaxAutoPrepare = 10,
    AutoPrepareMinUsages = 1,
    IncludeErrorDetail = true
}.ConnectionString;

await CreateTestTable(connectionString);

await using (var con = new NpgsqlConnection(connectionString))
{
    await con.OpenAsync();
    var transaction = await con.BeginTransactionAsync(IsolationLevel.ReadCommitted);
    try
    {
        await using var cmd = con.CreateCommand();
        cmd.CommandText = "INSERT INTO test (value) VALUES (@value) RETURNING id;";
        cmd.Parameters.AddWithValue("@value", "Too long, will error.");
        await cmd.ExecuteNonQueryAsync();
        await transaction.CommitAsync();
    }
    catch (Exception e)
    {
        await transaction.RollbackAsync();
        Console.WriteLine(e);
    }
}

await using (var con = new NpgsqlConnection(connectionString))
{
    await con.OpenAsync();
    await using var cmd = con.CreateCommand();
    cmd.CommandText = "INSERT INTO test (value) VALUES (@value) RETURNING id;";
    cmd.Parameters.AddWithValue("@value", "It's fine.");
    await cmd.ExecuteNonQueryAsync();
}

async Task CreateTestTable(string connectionString)
{
    await using (var con = new NpgsqlConnection(connectionString))
    {
        await con.OpenAsync();
        await using var cmd = con.CreateCommand();
        cmd.CommandText =
            "CREATE TABLE IF NOT EXISTS test (id bigint GENERATED ALWAYS AS IDENTITY, value varchar(10));";
        await cmd.ExecuteNonQueryAsync();
    }
}

What appears to happen here is that when a query is ran and added (or replaced) into the auto prepared statements list, but fails on first execution and the transaction is rolled back, it doesn't get/store a RowDescription with the prepared statement. When the the same query is later executed again it gets a result from the server which Npgsql doesn't expect resulting in System.Exception: Received unexpected backend message DataRow. Please file a bug. So here is the bug.

This bug occurs at least with Postgresql 15 and 16, and Npgsql 8.0.3, 9.0.4, 10.0.1.

I tested 8.0.3 because this might also be the cause of #5803 although I don't think there is any way to be sure about that. What I can be sure about is that it's hard to reproduce.

Activity

  1. vonzshik commented on Dec 24, 2025

    @vonzshik
    Contributor

    Huh. This indeed looks promising and might be the answer as to the reason of that annoying error. I'll take a look.

  2. AVee commented on Dec 24, 2025

    @AVee
    Author

    I took a network capture of the a single run of the above code:
    pgbug.pcapng.gz

    What I think it show is that the first run of the query never sends a sends a RowDescription, just a ParseCompletion followed by an error. So it's not that Npgsql didn't store the RowDescription, it never got it in the first place. But checking pg_prepared_statements after the rollback shows that the prepared statement was created. So now there is a prepared statement in Postgresql for wich Npgsql cannot know the RowDescription, and a second execution of the same prepared statement doesn't send the RowDescription either (because that supposed to be known at that point).

    This also means that the transaction I used in the repro isn't needed, this error happens whenever the first execution fails.

    Now I'm looking at the Postgres protocol for the first time, so I may miss some subtleties here, but the first query issues Parse, Bind, Describe, Execute, in that order. I guess the Bind triggers the error which means the Describe is never executed. Perhaps issuing Describe before Bind is all that's needed to fix this.

  3. vonzshik commented on Dec 24, 2025

    @vonzshik
    Contributor

    We probably can try something like this, but according to docs in simple query protocol (which we mimic while using extended query protocol) the flow is:

    The simple Query message is approximately equivalent to the series Parse, Bind, portal Describe, Execute, Close, Sync, using the unnamed prepared statement and portal objects and no parameters.

    Wonder if it's a postgres bug...

  4. self-assigned this
    on Dec 25, 2025
  5. added theissue type on Dec 25, 2025
  6. added this to the 10.0.2 milestone on Dec 25, 2025
  7. AVee commented on Dec 27, 2025

    @AVee
    Author

    Ok, after some study of the protocol I've got a few conclusions.

    Firstly, the Describe as used describes the portal, not the prepared statement, and therefore needs to be done after Bind. It's also possible to perform Describe for a prepared statement, however that does not take into account any output settings made on the Bind command. And Npgsql sets output to binary during Bind, so the RowDescription returned from Describe on a prepared statement is different and not what's needed.

    So the way things work right now Describe must happen after Bind. And (internally in Npgsql) Describe needs to have happened for a prepared statement to be fully usable, but NpgsqlDataReader marks the statement as 'Prepared' as soon as ParseComplete is received which seems to be the root of this issue. Because at that point, even though on the server side the statement is fully prepared, the internal state in Npgsql is not yet complete.

    I think there are three ways to resolve this:

    1. The crude way would be to always send Describe after Bind, that way there always is a valid RowDescription (or NoData) and Npgsql can always know what to expect next. This is the most robust, but also has the highest performance impact. Not calling Describe every time seems a conscious decision to avoid the extra message.
    2. Npgsql could catch the error on the first Bind and roll back the whole preparation done before. This would involve Closing the prepared statement on the server so it would introduce extra I/O, but only in this very specific case. It would also mean discarding a prepared statement on the server which otherwise could have been used.
    3. Npgsql could properly track the state of the Prepared statement so it's known if Describe has succeeded and when executing a statement send Describe (again) if the response isn't know yet. This might add an extra check every read, but the impact of that should be really minor. And it might even disappear completely if it's added to the current PreparedState enum.

    The way I look at it right now 3 seems the most sensible option. It basically just accepts that an in-between state where a statement is Parsed on the server but not Described yet can exist and deals with it when it happens. Regardless of how it happens. That is assuming there isn't some concurrency issue that could bite there. I don't think there is, but someone with deeper knowledge of Npgsql might know better then me. Option 1 is a more robust, but seems wasteful in terms of performance. And option 2 seems like it has the most potential to create messy code and weird new edge cases.

  8. modified the milestones: 10.0.2, 10.0.3 on Mar 12, 2026
  9. modified the milestones: 10.0.3, 10.0.4 on May 27, 2026
  10. jmbryan4 commented on Aug 3, 2026

    @jmbryan4

    We're hitting what looks like the same corruption on Npgsql 10.0.3 (also 10.0.2) against PostgreSQL 18, .NET 10

    Scenario: a multi-tenant API running sql INSERT ... RETURNING and a unique index preventing duplicates.
    Auto-prepare is on (Max Auto Prepare=20, Auto Prepare Min Usages=5). When two concurrent requests race on the same idempotency key:

    1. The losing request's INSERT fails with 23505 unique_violation. This appears to be the statement's first execution on that particular pooled connection, i.e. the execution that was also preparing it — matching @AVee's capture where the error arrives instead of a RowDescription.
    2. That connection returns to the pool looking healthy.
    3. A later, completely unrelated request that draws the same connection and runs the same (now corrupt) auto-prepared INSERT throws:
    System.Exception: Received unexpected backend message DataRow. Please file a bug.
    at Npgsql.Internal.NpgsqlConnector.UnexpectedMessageReceived(BackendMessageCode received)
    at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
    at Npgsql.NpgsqlCommand.ExecuteReader(Boolean async, CommandBehavior behavior, CancellationToken cancellationToken)
    at Npgsql.NpgsqlCommand.ExecuteScalar(Boolean async, CancellationToken cancellationToken) ...
    

    Setting Max Auto Prepare=0 fixes the issue.

    Happy to provide a trimmed repro if useful.

  11. modified the milestones: 10.0.4, 10.0.5 on Nov 20, 2026
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

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions