From 8e5aa285217fa5932b6b5e8102e604bafea5e70d Mon Sep 17 00:00:00 2001
From: Stepan Neretin <slpmcf@gmail.com>
Date: Tue, 17 Nov 2026 00:52:37 +0700
Subject: [PATCH 1/2] Avoid FATAL when primary ends streaming with COPY 0

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

Remember that CommandComplete already ended the COPY, and skip sending
CopyDone in that case.
---
 .../libpqwalreceiver/libpqwalreceiver.c           | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index dcc738f4e38..5be0d7e337e 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 by receive() when CommandComplete ended the COPY */
+	bool		copyEnded;
 };
 
 /* Prototypes for interface functions */
@@ -709,6 +711,18 @@ libpqrcv_endstreaming(WalReceiverConn *conn, TimeLineID *next_tli)
 {
 	PGresult   *res;
 
+	/*
+	 * Physical walsender can finish with CommandComplete ("COPY 0") and exit
+	 * without waiting for CopyDone.  receive() already consumed that result,
+	 * so there is no COPY left 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 +901,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

