Repository navigation
Description
Summary
Sometimes an error arrives while NpgsqlDataReader.Read/ReadAsync is reading a statement's rows, for example a runtime error on row 3, or the 57014 that a cancelled CancellationToken produces. When that happens, later statements in the same batch that were being auto-prepared on this execution stay in PreparedState.BeingPrepared, although PostgreSQL skipped their Parse. From then on, that physical connection sends only a Bind to _autoN for that SQL, and every use fails with 26000: prepared statement "_autoN" does not exist until the connection is closed.
Two earlier issues had the same symptom: #2665 (a Parse that failed) and #3002 (replacing a prepared statement with a bad one). This is the path neither of them covered.
Repro (Npgsql 10.0.3, PostgreSQL 16.15, .NET 10)
using Npgsql;
await using var ds = NpgsqlDataSource.Create(
"Host=localhost;Username=test;Password=test;Max Pool Size=1;Max Auto Prepare=50");
const string B = "SELECT $1::int + 7 AS x";
async Task RunB()
{
await using var c = await ds.OpenConnectionAsync();
await using var cmd = new NpgsqlCommand(B, c);
cmd.Parameters.Add(new NpgsqlParameter<int> { TypedValue = 1 });
await cmd.ExecuteScalarAsync();
}
for (var i = 0; i < 4; i++) await RunB(); // 4 usages; the 5th prepares it
try
{
await using var c = await ds.OpenConnectionAsync();
await using var batch = new NpgsqlBatch(c);
// Fails on its third row, after rows 1 and 2 were read.
batch.BatchCommands.Add(new NpgsqlBatchCommand("SELECT 1 / (x - 3) FROM generate_series(1, 5) x"));
var b = new NpgsqlBatchCommand(B); // 5th usage: chosen for auto-preparation
b.Parameters.Add(new NpgsqlParameter<int> { TypedValue = 1 });
batch.BatchCommands.Add(b);
await using var r = await batch.ExecuteReaderAsync();
while (await r.ReadAsync()) { }
}
catch (PostgresException e) { Console.WriteLine($"batch: {e.SqlState}"); } // 22012, expected
await RunB(); // 26000: prepared statement "_auto0" does not exist; same on every later callThe same thing happens without a server error. Make statement 1 stream wide rows slowly, for example SELECT repeat('x', 100000), pg_sleep(0.05) FROM generate_series(1, 40), and cancel the token passed to ReadAsync part way through. The batch throws OperationCanceledException, and then B fails 26000 on every later use. We hit this variant in production: requests the client abandoned left one pooled connection failing every read of one query.
Cause
When NextResult fails, its catch runs the clean-up loop for the remaining statements:
for (; StatementIndex < _statements.Count; StatementIndex++)
if (statement.IsPreparing) { statement.IsPreparing = false; statement.PreparedStatement!.AbortPrepare(); }Read(bool async, ...) has its own catch, and that one only sets State = ReaderState.Consumed and rethrows. Because the reader is now Consumed, Close/Consume skip NextResult, so the loop above never runs for statements after the current one. The statement stays BeingPrepared in its AutoPrepared slot and in BySql.
On its next use, TryGetAutoPreparedSlow takes the case PreparedState.BeingPrepared: branch and returns the statement as if it were prepared. TryAutoPrepare leaves IsPreparing false, so WriteExecute sends a Bind with no Parse. On main the Read catch looks unchanged.
The fix seems to be to run the same AbortPrepare loop from StatementIndex + 1 in Read's catch, and in ConsumeRow/ConsumeResultSet failures, before the reader is marked Consumed.
Workaround
Cancellation Timeout=-1 makes a user cancellation break the connector (which calls ClearAll), so a cancelled read can no longer leave the state behind. A row-level server error with no cancellation can still trigger it.
Activity
vonzshik commentedon Nov 11, 2026
Thanks for the reports, that's indeed a quite nasty bug. Agree with the proposed fix.