From de4335f0217f8b39fab906f2467b1c3b11caef1b Mon Sep 17 00:00:00 2001
From: Stepan Neretin <slpmcf@gmail.com>
Date: Wed, 18 Nov 2026 11:17:03 +0700
Subject: [PATCH v5 1/2] Fix FATAL when primary ends streaming with COPY 0

If the primary shuts down cleanly, walsender ends the COPY with
CommandComplete ("COPY 0") and exits without waiting for CopyDone.
libpqrcv_receive() already consumes that result, then
libpqrcv_endstreaming() still calls PQputCopyEnd() and fails with "no
COPY in progress", which becomes a FATAL in the walreceiver.

Remember that CommandComplete already ended the COPY and skip
PQputCopyEnd() in that case.  Clear the flag in
libpqrcv_startstreaming(), because receive() is also used for tablesync
COPY TO STDOUT and that must not cause a later replication stream on the
same connection to skip CopyDone.

After COPY 0 both receivers leave the inner receive loop and can still
attempt status feedback before endstreaming.  Skip those sends when the
stream has already ended, so PQputCopyData does not fail with "no COPY
in progress".

If endstreaming reports no next timeline, exit with proc_exit(0)
instead of falling into waiting mode, so the dead connection is not
reused and an incomplete segment is not archived.

Discussion: https://postgr.es/m/CA+Yyo5S_n3ZcZh-3LXNj2-rxqXnbGd8901Yres0LPUS=tTLjaQ@mail.gmail.com
---
 .../libpqwalreceiver/libpqwalreceiver.c       | 21 ++++++++++++++++
 src/backend/replication/logical/worker.c      |  8 ++++--
 src/backend/replication/walreceiver.c         | 25 ++++++++++++++++---
 3 files changed, 48 insertions(+), 6 deletions(-)

diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index dcc738f4e38..c5bb1b2b392 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -52,6 +52,8 @@ struct WalReceiverConn
 	bool		logical;
 	/* Buffer for currently read records */
 	char	   *recvBuf;
+	/* set when CommandComplete already ended the COPY */
+	bool		copyEnded;
 };
 
 /* Prototypes for interface functions */
@@ -618,6 +620,9 @@ libpqrcv_startstreaming(WalReceiverConn *conn,
 	Assert(options->logical == conn->logical);
 	Assert(options->slotname || !options->logical);
 
+	/* may be left set by a prior non streaming COPY */
+	conn->copyEnded = false;
+
 	initStringInfo(&cmd);
 
 	/* Build the command. */
@@ -709,6 +714,21 @@ libpqrcv_endstreaming(WalReceiverConn *conn, TimeLineID *next_tli)
 {
 	PGresult   *res;
 
+	/*
+	 * If CommandComplete already ended the COPY (COPY 0 on clean shutdown),
+	 * PQputCopyEnd() would fail with "no COPY in progress".  PQstatus() may
+	 * still be CONNECTION_OK in that case, so copyEnded is the signal we use.
+	 * Do not treat CONNECTION_BAD the same way: an unexpected disconnect
+	 * should still ERROR from PQputCopyEnd() rather than look like a clean
+	 * end of streaming.
+	 */
+	if (conn->copyEnded)
+	{
+		conn->copyEnded = false;
+		*next_tli = 0;
+		return;
+	}
+
 	/*
 	 * Send copy-end message.  As in libpqsrv_exec, this could theoretically
 	 * block, but the risk seems small.
@@ -887,6 +907,7 @@ libpqrcv_receive(WalReceiverConn *conn, char **buffer,
 		if (PQresultStatus(res) == PGRES_COMMAND_OK)
 		{
 			PQclear(res);
+			conn->copyEnded = true;
 
 			/* Verify that there are no more results. */
 			res = libpqsrv_get_result(conn->streamConn,
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index 95044620e68..c63298458c9 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -4212,8 +4212,12 @@ LogicalRepApplyLoop(XLogRecPtr last_received)
 			}
 		}
 
-		/* confirm all writes so far */
-		send_feedback(last_received, false, false);
+		/*
+		 * Confirm all writes so far.  Skip once the publisher has ended the
+		 * COPY; PQputCopyData would fail with "no COPY in progress".
+		 */
+		if (!endofstream)
+			send_feedback(last_received, false, false);
 
 		/* Reset the timestamp if no message was received */
 		rdt_data.last_recv_time = 0;
diff --git a/src/backend/replication/walreceiver.c b/src/backend/replication/walreceiver.c
index ef9f8718834..eb494ca7ac1 100644
--- a/src/backend/replication/walreceiver.c
+++ b/src/backend/replication/walreceiver.c
@@ -29,6 +29,10 @@
  * nudge the existing walreceiver process that's waiting, instead of launching
  * a new one.
  *
+ * A clean primary shutdown is different. There is no next timeline to follow
+ * on this connection, so walreceiver exits and a fresh process is started
+ * when streaming is requested again.
+ *
  * Normal termination is by SIGTERM, which instructs the walreceiver to
  * ereport(FATAL). Emergency termination is by SIGQUIT; like any postmaster
  * child process, the walreceiver will simply abort and exit on SIGQUIT. A
@@ -579,15 +583,21 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 						len = walrcv_receive(wrconn, &buf, &wait_fd);
 					}
 
-					/* Let the primary know that we received some data. */
-					XLogWalRcvSendReply(false, false, false);
+					/*
+					 * Let the primary know that we received some data.  Skip
+					 * once the remote side has ended the COPY; PQputCopyData
+					 * would fail with "no COPY in progress".
+					 */
+					if (!endofwal)
+						XLogWalRcvSendReply(false, false, false);
 
 					/*
 					 * If we've written some records, flush them to disk and
 					 * let the startup process and primary server know about
-					 * them.
+					 * them.  Pass endofwal as dying so flush does not try to
+					 * send after the COPY has ended.
 					 */
-					XLogWalRcvFlush(false, startpointTLI);
+					XLogWalRcvFlush(endofwal, startpointTLI);
 				}
 
 				/* Check if we need to exit the streaming loop. */
@@ -693,6 +703,13 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 			 */
 			walrcv_endstreaming(wrconn, &primaryTLI);
 
+			/*
+			 * Clean remote shutdown. Exit instead of waiting mode, which would
+			 * reuse a dead connection and archive an incomplete segment.
+			 */
+			if (primaryTLI == 0)
+				proc_exit(0);
+
 			/*
 			 * If the server had switched to a new timeline that we didn't
 			 * know about when we began streaming, fetch its timeline history
-- 
2.56.0

