Skip to content

Don't return the read buffer of a broken connector to the ArrayPool - #6717

Open
Brar wants to merge 4 commits into
npgsql:mainfrom
Brar:repl/pooled-buffer-on-break
Open

Brar wants to merge 4 commits into
npgsql:mainfrom
Brar:repl/pooled-buffer-on-break

Conversation

@Brar

@Brar Brar commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Depends on #6715 and #6716, which aren't merged yet; their commits show up here until they are.

After a backend message longer than the read buffer (e.g. a notice over 8 KB), the connector reads into a bigger buffer whose array comes from ArrayPool<byte>.Shared, and a replication stream reads from it for the rest of the session. When the connector broke while the consumer held a message (e.g. because a status update failed), disposing the buffer returned the array to the pool, but the consumer could still read the message's data from it. If something else rented the array meanwhile, the consumer silently got that renter's bytes instead.

The buffer of a broken connector now leaves its array to the GC instead of returning it to the pool. Closing a connector, resetting a pooled one and switching to an even bigger buffer still return it.

How a real server gets there

Three things have to come together:

  1. A pooled oversize buffer while a message is held. Mid-stream, through the notices that Read pgoutput messages from the connector's current read buffer #6721 describes (a publication row filter, the walsender's echo of the replication command). On main as well, through any message longer than the buffer on the same connection before START_REPLICATION, since the stream then starts on the bigger buffer: e.g. TIMELINE_HISTORY of a cluster with about 190 or more timelines, whose history file comes in one DataRow (walsender.c:609, :632 on REL_18_STABLE), or SHOW of a long setting. Clients that work like pg_receivewal run IDENTIFY_SYSTEM, TIMELINE_HISTORY and START_REPLICATION on one connection.
  2. A real break while the consumer holds the message: pg_terminate_backend, a restart, a failover or wal_sender_timeout. The feedback timer's next write then breaks the connector, and its cleanup disposes the read buffer.
  3. Other code in the process rents an array of that size before the consumer reads. That is plausible in a busy process, but nothing forces it.

Live, with a held XLogData message and pg_terminate_backend; an EventListener rented the returned array right when it went back to the pool and filled it with 0xEE, standing in for the other renter:

  • main on 13.23, after a TIMELINE_HISTORY of 8691 bytes (200 promotions), and main on 18.6, after a 20000-character SHOW result: the held message read EEEE…, silently wrong WAL bytes.
  • pgoutput rows, after a row-filter notice or the command echo, with Read pgoutput messages from the connector's current read buffer #6721 but without this change: the corrupted held row failed in the tuple enumerator.
  • With this change, the array was never returned, and the data stayed intact. Control: without an oversize message, nothing was returned, and the data stayed intact.

Tests

ReplicationStopMockTests.Held_message_keeps_its_data_after_a_break: an oversize notice, then a held XLogData; the test breaks the connector, rents an array of the buffer's size on the same thread (ArrayPool hands a thread the array it returned last), fills it and reads the held data.

  • Red first: the oversize case read 238 (0xEE) instead of 97 ('a'), in Debug and Release. The control without the notice (an unpooled buffer) passed.
  • Probes that weren't committed: an EventListener showed that without the fix the break returns the array, also on the timer's thread for a failed timer status update, and with it doesn't; after a break with the fix, the GC collected the array once the connection and its message were unreachable.

For the reviewer

  • A core change in NpgsqlReadBuffer, whose Dispose NpgsqlConnector calls when it breaks; no API change. It is needed because a broken replication connector can still have a consumer that reads a held message from that buffer.
  • Only NpgsqlConnector disposes read buffers, and nothing depends on the return. Regular connections only differ in that a broken connector's oversize array goes to the GC.
  • Not changed: a normal DisposeAsync while the consumer holds a message still returns the array; reading a held message after that is outside the API's contract.
  • Backport: planned for the 10.0 hotfix branch, since main has the bug through an oversize message before START_REPLICATION.

Dependencies and merge order

Part of #6699 (#6721 completes it).

Brar and others added 3 commits November 8, 2026 00:08
- 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]>
After a backend message bigger than the read buffer (e.g. a notice
longer than 8 KB), the connector reads into a bigger buffer whose array
comes from ArrayPool<byte>.Shared, and a replication stream follows it
there for the rest of the session. When the connector broke while the
consumer held a message (e.g. because a status update failed),
disposing the buffer returned the array to the pool, but the consumer
could still read the message's data from it. If something else rented
the array meanwhile, the consumer silently got that renter's bytes
instead.

The buffer of a broken connector now leaves its array to the GC instead
of returning it to the pool. Closing a connector, resetting a pooled
one and switching to an even bigger buffer still return it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brar
Brar force-pushed the repl/pooled-buffer-on-break branch from 8839374 to 5b75c12 Compare November 7, 2026 23:34
Copilot AI balanced review requested due to automatic review settings November 7, 2026 23:34

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical replication feedback races can acknowledge payloads before they are fully drained and allow stale timer callbacks to write concurrently with a new stream’s handshake.

3 open issues
What changed in this PR

This PR protects held replication messages from data corruption by leaving a broken connector’s pooled read buffer to garbage collection. It also includes dependency changes from #6715 and #6716 for replication stream shutdown and cleanup.

Changes:

  • Prevent broken connectors from returning read-buffer arrays to ArrayPool.
  • Improve replication termination, early disposal, feedback coordination, and received-position tracking.
  • Add regression tests, lifecycle logging, and replication API documentation.
File Description
test/​Npgsql.Tests/​Replication/​ReplicationStreamEndMockTests.cs Tests stream endings and reported WAL positions.
test/​Npgsql.Tests/​Replication/​ReplicationStopTests.cs Tests early stopping and connection reuse.
test/​Npgsql.Tests/​Replication/​ReplicationStopMockTests.cs Tests cleanup, cancellation, buffer switching, and held-message retention.
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 stream termination, cleanup, feedback, and buffer changes.
src/​Npgsql/​Replication/​PhysicalReplicationConnection.cs Disposes inner enumerators and documents timeline continuation.
src/​Npgsql/​Replication/​PgOutput/​PgOutputConnectionExtensions.cs Documents cancellation and connection-reuse limitations.
src/​Npgsql/​Replication/​Internal/​LogicalReplicationConnectionExtensions.cs Disposes inner enumerators and supplies starting WAL positions.
src/​Npgsql/​NpgsqlEventId.cs Adds replication lifecycle event identifiers.
src/​Npgsql/​LogMessages.cs Adds replication termination and cleanup logging.
src/​Npgsql/​Internal/​NpgsqlReadBuffer.cs Retains pooled arrays when connectors break.

Review effort: Balanced

The test that a held message keeps its data after a break relied on the
message's data being in the read buffer when the connection breaks, but
handing out the message only makes sure of its header. When the data
arrived after the header, the test read from the closed socket. It now
makes sure the data is buffered before it breaks the connection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 8, 2026 10:55

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Feedback can corrupt the protocol during replication startup, receive-position tracking can cause deadlocks or acknowledge bytes not yet received, and stopping can hang indefinitely on a partial payload.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Bound the timeout when stopping with a partially buffered message

src/​Npgsql/​Replication/​ReplicationConnection.cs:693

With WalReceiverTimeout set to infinite, stopping inside a partially buffered message can wait forever here if the server stops sending the remaining payload. The finite timeout in ReadStartReplicationEnd and logical cancellation are reached only after this skip finishes. Apply a finite stop timeout before either skip path, using 30 seconds when the configured timeout maps to infinity.

3 resolved since last review

Review effort: Balanced

@Brar

Brar commented Nov 8, 2026

Copy link
Copy Markdown
Member Author

The point in the summary of the latest review, stopping with a partly received message without a bound, is #6716's code, whose commits show up here until it's merged. It's fixed there in a4659cf and 3d29849.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants