Repository navigation
Description
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
vonzshik commentedon Dec 24, 2025
Huh. This indeed looks promising and might be the answer as to the reason of that annoying error. I'll take a look.
AVee commentedon Dec 24, 2025
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.
vonzshik commentedon Dec 24, 2025
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:
Wonder if it's a postgres bug...
AVee commentedon Dec 27, 2025
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:
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.
jmbryan4 commentedon Aug 3, 2026
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:
Setting Max Auto Prepare=0 fixes the issue.
Happy to provide a trimmed repro if useful.
fix(db): drop a backend's auto-prepared statements after a server error