From 0a20f28fb019020a9ed2e3186fb2373f85d8e0ef Mon Sep 17 00:00:00 2001
From: Stepan Neretin <slpmcf@gmail.com>
Date: Wed, 18 Nov 2026 11:17:03 +0700
Subject: [PATCH v3 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.  Also skip it when the connection is
already CONNECTION_BAD.  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.

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       | 19 +++++++++++++++++++
 src/backend/replication/walreceiver.c         | 11 +++++++++++
 2 files changed, 30 insertions(+)

diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index dcc738f4e38..27eb2fd5a40 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,19 @@ libpqrcv_endstreaming(WalReceiverConn *conn, TimeLineID *next_tli)
 {
 	PGresult   *res;
 
+	/*
+	 * Skip PQputCopyEnd() if CommandComplete already ended the COPY, or if
+	 * the connection is already gone. copyEnded is still required after
+	 * COPY 0 because PQstatus() may remain CONNECTION_OK.
+	 */
+	if (conn->copyEnded ||
+		PQstatus(conn->streamConn) == CONNECTION_BAD)
+	{
+		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 +905,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/walreceiver.c b/src/backend/replication/walreceiver.c
index 11b9a12c52c..28b96d9829f 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
@@ -691,6 +695,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

