From 45676b8f73fb01504a248f5cdc0c8a8bdd17b02a Mon Sep 17 00:00:00 2001
From: Stepan Neretin <slpmcf@gmail.com>
Date: Tue, 17 Nov 2026 14:21:11 +0700
Subject: [PATCH v2 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.

Discussion: https://postgr.es/m/CA+Yyo5S_n3ZcZh-3LXNj2-rxqXnbGd8901Yres0LPUS=tTLjaQ@mail.gmail.com
---
 .../libpqwalreceiver/libpqwalreceiver.c         | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index dcc738f4e38..bb02236c6c5 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;
+	/* True if 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);
 
+	/* receive() may have set this for a prior non-streaming COPY */
+	conn->copyEnded = false;
+
 	initStringInfo(&cmd);
 
 	/* Build the command. */
@@ -709,6 +714,17 @@ libpqrcv_endstreaming(WalReceiverConn *conn, TimeLineID *next_tli)
 {
 	PGresult   *res;
 
+	/*
+	 * If receive() already saw CommandComplete, the COPY is finished and
+	 * there is nothing to end.
+	 */
+	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 +903,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,
-- 
2.56.0

