Repository navigation
Conversation
- At the end of a historic timeline (e.g. after the standby we stream
from got promoted), the server ends copy mode with CopyDone. Npgsql
expected only CopyData and broke the connection ("Received backend
message CopyDone while expecting CopyDataMessage"). It now answers
with CopyDone, reads the next timeline the server sends, both
CommandCompletes and ReadyForQuery, and ends the enumeration normally,
leaving the connection usable. Status updates stop before our
CopyDone, since the protocol doesn't allow CopyData after it. The next
timeline is logged, and the StartReplication docs explain how to
continue: IDENTIFY_SYSTEM returns the current timeline and
TIMELINE_HISTORY the position where it branched off, which can be
before the end of the WAL received on the old timeline.
- Asked to start at the end of a historic timeline, the server doesn't
enter copy mode but sends the next timeline right away, which Npgsql
treated as an unexpected message. The enumeration now ends right away.
- A walsender that exits after everything has been replicated (e.g. at
server shutdown, npgsql#5752) sends CommandComplete, which also broke the
connection with a misleading error. It now throws an NpgsqlException
saying that the server ended the replication stream.
- In logical replication, unknown CopyData message types are skipped
instead of breaking the connection, like the logical replication
worker, which ignores them on purpose. Physical replication keeps
rejecting them, like walreceiver, since it must not lose WAL.
Keepalive fields that newer servers may add are skipped in both.
- In physical replication, the received position reported to the server
was the server's own WAL end, not the end of the WAL received, so
pg_stat_replication.write_lsn and synchronous_commit = remote_write
treated WAL as written before it arrived. It is now the end of the
data the consumer is done with, like walreceiver reports what it
wrote.
- LastReceivedLsn starts over at the start position of each stream
instead of keeping the maximum of all previous streams, which was
wrong when continuing on a new timeline at a lower position.
- The XLogData stream is disposed after each message instead of later in
cleanup, where it could skip data based on a stale position: a server
error that ended the stream after a keepalive (e.g. after
pg_cancel_backend) turned into a timeout and a broken connection.
The new cluster tests stream physically across a standby's promotion
and through a fast shutdown, using the throwaway clusters from
NPGSQL_TEST_PG_BIN.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Breaking out of a replication enumeration, or an exception in the consumer, left the inner enumerator undisposed. The connection stayed in replication mode with its feedback timers running, and every other command failed with NpgsqlOperationInProgressException. The enumerators are now disposed, which stops streaming: physical replication ends copy mode with CopyDone, which keeps the walsender ready for the next START_REPLICATION and keeps temporary slots; logical replication cancels the command, since a logical walsender can't stream again after CopyDone. Like any error, the cancellation drops the temporary slots of the session (documented on the logical StartReplication methods). Servers before PostgreSQL 10 ignore cancellation requests on replication connections, so with them the logical stop breaks the connection instead. A final status update reports the processed position first; for logical replication this is best effort, since the walsender may handle the cancellation before it reads the update. If stopping fails, the connection is broken; the exception that made the consumer stop is never replaced. On PostgreSQL 14-17, the server may not send pgoutput's Relation messages again in the next stream on the same connection after such a cancellation (on 14 after any error, on 15-17 if the connection created the slot with an exported snapshot; fixed in PostgreSQL 18 by 80b727eb9de). This is documented on the pgoutput StartReplication, and the test avoids it. - Status updates that were still on their way when a stream ended (e.g. from a timer or another thread) could be written after the end of the command, interleaved with the next one. They are now dropped. - Whatever the consumer didn't read of the message it held is skipped first, also when a plugin like pgoutput reads the data directly from the buffer. Reading beyond the end of a message breaks the connection. - After cancellation, messages that were already on their way were still handed out until the server's error arrived. They are now skipped. This makes the physical replication tests reliable, so they run again (some of them also used colliding slot names). - Starting a second stream while one was in progress overwrote the state of the first one before failing, so disposing the connection didn't stop the first stream anymore. It now fails before touching anything, and a start that fails leaves no state behind. - A message bigger than the read buffer (e.g. a long notice) made the connector switch to a bigger buffer while the stream kept reading from the old one. This is fixed for the replication stream itself; the pgoutput decoder still reads from the old buffer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A backend message bigger than the read buffer (e.g. a notice longer than 8 KB) makes the connector switch to a bigger buffer for the rest of the replication session. The replication stream follows the switch, but the pgoutput decoder kept the buffer it found when the enumeration started, and its tuples, column enumerators and values kept the one from when they were created. After such a message they read from the old buffer, bypassing what the connector had already buffered in the new one, and misread the stream from there, or waited for more data although the next message had already arrived. The stream's check whether a plugin read a message beyond its end measured the new buffer, so it didn't notice. The decoder now takes the connector's buffer for each message. The tuples take it when they are populated for a message and pass it on to their column enumerators and values. They don't look it up when the consumer reads a row, since a broken connector no longer has a buffer (e.g. after a failed status update while the consumer held the message). Co-Authored-By: Claude Opus 5.5 <[email protected]>
90b3c2d to
39cf119
Compare
There was a problem hiding this comment.
🟡 Changes recommended
The connection-reuse guarantee needs to be limited to PostgreSQL 10+ in both replication extensions, with callers on older servers advised to reconnect after stopping a stream early.
1 open issue
What changed in this PR
Fixes pgoutput decoding after an oversized backend message causes the connector to replace its read buffer, completing the decoder portion of #6699. The branch also includes the replication lifecycle changes from dependencies #6715 and #6716.
Changes:
- Refreshes the decoder’s buffer per message and passes it through tuples, column enumerators, and values.
- Handles stream termination, early disposal, cancellation, and received-position reporting.
- Adds regression tests, lifecycle logging, and replication API documentation.
| File | Description |
|---|---|
test/Npgsql.Tests/Replication/ReplicationStreamEndMockTests.cs |
Tests stream endings, protocol handling, and received positions. |
test/Npgsql.Tests/Replication/ReplicationStopTests.cs |
Tests early stopping and connection reuse against PostgreSQL. |
test/Npgsql.Tests/Replication/ReplicationStopMockTests.cs |
Tests disposal, cancellation, and oversized-message buffer switches. |
test/Npgsql.Tests/Replication/PhysicalReplicationTests.cs |
Re-enables tests and avoids slot-name collisions. |
test/Npgsql.Tests/Replication/PhysicalReplicationClusterTests.cs |
Tests standby promotion and server shutdown. |
src/Npgsql/Replication/TestDecoding/TestDecodingConnectionExtensions.cs |
Documents early-stop behavior. |
src/Npgsql/Replication/ReplicationConnection.cs |
Handles lifecycle cleanup, buffer switches, and position reporting. |
src/Npgsql/Replication/PhysicalReplicationConnection.cs |
Disposes inner enumerators and documents timeline continuation. |
src/Npgsql/Replication/PgOutput/TupleEnumerator.cs |
Receives the current tuple buffer and forwards it to values. |
src/Npgsql/Replication/PgOutput/ReplicationValue.cs |
Updates the buffer when each value is reset. |
src/Npgsql/Replication/PgOutput/ReplicationTuple.cs |
Captures the current buffer when populated. |
src/Npgsql/Replication/PgOutput/PgOutputConnectionExtensions.cs |
Documents early stopping and server-version reuse limitations. |
src/Npgsql/Replication/PgOutput/PgOutputAsyncEnumerable.cs |
Retrieves the connector’s buffer for each message. |
src/Npgsql/Replication/Internal/LogicalReplicationConnectionExtensions.cs |
Disposes inner enumerators and supplies the starting position. |
src/Npgsql/NpgsqlEventId.cs |
Adds replication lifecycle event identifiers. |
src/Npgsql/LogMessages.cs |
Adds stream-ending and early-stop log messages. |
Review effort: Balanced
| /// Ending the enumeration early (e.g. with <see langword="break"/>) stops replication by cancelling the command, after which | ||
| /// the connection can be used for other commands. Like any error, the cancellation drops the temporary replication slots of | ||
| /// the session. Npgsql sends a last status update before it, but the server may handle the cancellation first. |
There was a problem hiding this comment.
Npgsql's docs don't describe behavior on PostgreSQL versions that are out of support, and 10 has been for a while. The code keeps working with them as far as it can; there the logical stop breaks the connection, as #6716's description says.

Depends on #6715 and #6716, which aren't merged yet; their commits show up here until they are.
A backend message longer than the read buffer (8 KB by default), e.g. a long notice, makes the connector switch to a bigger buffer for the rest of the session. The pgoutput decoder kept the buffer it found when the enumeration started, and its tuples, column enumerators and values kept the one from when they were created. After such a message they read from the old, emptied buffer, i.e. directly from the socket, past what the connector had already received: the decoder misread the stream from there, or waited for data that had already arrived. The replication stream's check whether a plugin read a message beyond its end measured the new buffer, so it didn't notice.
The decoder now takes the connector's buffer for each message. A tuple takes it when it is populated for a message and passes it on to its column enumerator and values. It isn't looked up when the consumer reads the row, since a broken connector no longer has a buffer, so a row held across a break stays readable, as before.
How a real server gets there
Notices may come between CopyData messages (
protocol.sgml:1341-1345; PostgreSQL references are to REL_18_STABLE). A walsender sends one longer than the read buffer in these cases:websearch_to_tsqueryraises a NOTICE that contains the whole input (tsquery.c:883). WithWHERE (numnode(websearch_to_tsquery('simple', q)) > 0)and a row whoseqholds 20000 spaces, the walsender sends a 20 KB notice while it decodes, between two change messages, as in the mock test. Default settings are enough; the trigger is rare, but legal and data-driven.log_replication_commands = onandclient_min_messagesat LOG or lower, it sends "received replication command: …" as a notice (walsender.c:2134). A START_REPLICATION longer than the read buffer, e.g. with 140 publications with 63-character names, gets an oversize notice before CopyBothResponse.Live, in Release builds:
Read Buffer Size=4096).Tests
ReplicationStopMockTests.Oversize_message_during_pgoutput_streamingsends a Relation, a 20 KB notice, an Insert, an Update that the consumer reads, the same Update unread, an Insert with a 40000-byte value (bigger than the 32 KB buffer the connector switches to, so that a read from the old buffer gets bytes from its middle) and a Commit.For the reviewer
private protected.Reset, ends in NullReferenceException, where the old code still delivered the message.Dependencies and merge order
ReplicationStopMockTestsand uses its oversize notice); merge those first. Only the last commit is this PR's own; the others drop out when the branch is rebased onto main after they land.Fixes #6699