From 24e64cf0e9fec3b677410bcb4dd8346c0bec11e2 Mon Sep 17 00:00:00 2001
From: Nazir Bilal Yavuz <byavuz81@gmail.com>
Date: Fri, 20 Nov 2026 11:05:14 +0300
Subject: [PATCH v1 6/7] Let the walreceiver report replay without receiving
 WAL

Give startup a way to request a feedback-only walreceiver. It opens a
START_FEEDBACK session and reports the end of the last replayed record
as its write, flush and apply positions. Status updates have no
timeline field, so read the replay position and timeline together and
exit if the timeline no longer matches the session.

The receiver leaves WAL and timeline history files to startup.
pg_stat_wal_receiver shows its status as "feedback", while
pg_last_wal_receive_lsn() still shows where streaming stopped. When
startup needs to stream again, it stops the feedback receiver and
starts a streaming receiver on a fresh connection.

Skip START_FEEDBACK on upstream servers older than PostgreSQL 20.
On newer servers, failure to enter bidirectional COPY is an error.
---
 doc/src/sgml/monitoring.sgml                  |   8 +
 src/backend/replication/README                |  16 ++
 .../libpqwalreceiver/libpqwalreceiver.c       |  44 ++++
 src/backend/replication/walreceiver.c         | 191 ++++++++++++++----
 src/backend/replication/walreceiverfuncs.c    |  95 +++++++--
 src/include/replication/walreceiver.h         |  10 +
 src/tools/pgindent/typedefs.list              |   1 +
 7 files changed, 315 insertions(+), 50 deletions(-)

diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 69a9aa060fd..af27bc20f90 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -1970,6 +1970,14 @@ description | Waiting for a newly initialized WAL file to reach durable storage
           <literal>streaming</literal>: WAL receiver is streaming WAL data.
          </para>
         </listitem>
+        <listitem>
+         <para>
+          <literal>feedback</literal>: WAL receiver is reporting replay
+          progress without receiving WAL.  The stream start, write, and
+          flush positions and their associated timelines are null during a
+          feedback-only connection.
+         </para>
+        </listitem>
         <listitem>
          <para>
           <literal>waiting</literal>: WAL receiver has stopped streaming and
diff --git a/src/backend/replication/README b/src/backend/replication/README
index f05d2aae5f9..3460e752c4b 100644
--- a/src/backend/replication/README
+++ b/src/backend/replication/README
@@ -36,6 +36,22 @@ Walreceiver sends information about replication progress to the primary server
 whenever it either writes or flushes new WAL, or the specified interval elapses.
 This is used for reporting purpose.
 
+After replay has started, startup can instead request a feedback-only receiver
+with RequestWalReceiverFeedback(). It reports the end of the last replayed
+record in all three standby status positions, without fetching or writing WAL.
+Feedback requires a named physical slot. The upstream validates the replay
+timeline against its history. Standby status updates carry LSNs but no
+timeline ID. Before each report the walreceiver checks the replay timeline
+and exits rather than send an LSN from a new timeline on the old session.
+The startup process can continue replay and request feedback on the new
+timeline. The walreceiver also exits if the upstream does not support
+START_FEEDBACK.
+If startup finds WAL in the archive or pg_wal after a stream has ended,
+it can request feedback in place of the waiting receiver. This starts a
+fresh connection with the requested settings.
+RequestXLogStreaming() stops a feedback-only receiver before launching a WAL
+writer; archive restoration and streaming must never both write the same file.
+
 Walsender IPC
 -------------
 
diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index dcc738f4e38..f71c0fd94ec 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -76,6 +76,8 @@ static void libpqrcv_readtimelinehistoryfile(WalReceiverConn *conn,
 											 char **content, size_t *len);
 static bool libpqrcv_startstreaming(WalReceiverConn *conn,
 									const WalRcvStreamOptions *options);
+static bool libpqrcv_startfeedback(WalReceiverConn *conn, const char *slotname,
+								   TimeLineID tli);
 static void libpqrcv_endstreaming(WalReceiverConn *conn,
 								  TimeLineID *next_tli);
 static int	libpqrcv_receive(WalReceiverConn *conn, char **buffer,
@@ -107,6 +109,7 @@ static WalReceiverFunctionsType PQWalReceiverFunctions = {
 	.walrcv_server_version = libpqrcv_server_version,
 	.walrcv_readtimelinehistoryfile = libpqrcv_readtimelinehistoryfile,
 	.walrcv_startstreaming = libpqrcv_startstreaming,
+	.walrcv_startfeedback = libpqrcv_startfeedback,
 	.walrcv_endstreaming = libpqrcv_endstreaming,
 	.walrcv_receive = libpqrcv_receive,
 	.walrcv_send = libpqrcv_send,
@@ -598,6 +601,47 @@ appendQuotedString(StringInfo buf, const char *str, char quote)
 #define appendQuotedIdentifier(b, s)	appendQuotedString(b, s, '"')
 #define appendQuotedLiteral(b, s)		appendQuotedString(b, s, '\'')
 
+/*
+ * Start a feedback-only session for the named physical slot.  tli is the
+ * timeline of the standby's last replayed record.
+ *
+ * Return true once the connection enters bidirectional COPY mode.  Return
+ * false if the upstream predates START_FEEDBACK; otherwise, failure to enter
+ * COPY mode is an error.
+ */
+static bool
+libpqrcv_startfeedback(WalReceiverConn *conn, const char *slotname,
+					   TimeLineID tli)
+{
+	StringInfoData cmd;
+	PGresult   *res;
+
+	Assert(!conn->logical);
+	Assert(slotname != NULL && slotname[0] != '\0' && tli != 0);
+
+	/* Don't send START_FEEDBACK to pre-20 servers; they don't recognize it. */
+	if (PQserverVersion(conn->streamConn) < 200000)
+		return false;
+
+	initStringInfo(&cmd);
+	appendStringInfoString(&cmd, "START_FEEDBACK SLOT ");
+	appendQuotedIdentifier(&cmd, slotname);
+	appendStringInfo(&cmd, " TIMELINE %u", tli);
+	res = libpqsrv_exec(conn->streamConn, cmd.data,
+						WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE);
+	pfree(cmd.data);
+	if (PQresultStatus(res) != PGRES_COPY_BOTH)
+	{
+		PQclear(res);
+		ereport(ERROR,
+				(errcode(ERRCODE_PROTOCOL_VIOLATION),
+				 errmsg("could not start WAL receiver feedback: %s",
+						pchomp(PQerrorMessage(conn->streamConn)))));
+	}
+	PQclear(res);
+	return true;
+}
+
 /*
  * Start streaming WAL data from given streaming options.
  *
diff --git a/src/backend/replication/walreceiver.c b/src/backend/replication/walreceiver.c
index ef9f8718834..1a63ab0ede7 100644
--- a/src/backend/replication/walreceiver.c
+++ b/src/backend/replication/walreceiver.c
@@ -21,6 +21,10 @@
  * This applies, for example, to the replication slot and the connection
  * string to be used for the connection with the primary.
  *
+ * A feedback-only receiver connects to report replay progress while startup
+ * owns the WAL files. It accepts keepalives, but never installs a segment or
+ * timeline history file. A streaming request starts a separate receiver.
+ *
  * If the primary server ends streaming, but doesn't disconnect, walreceiver
  * goes into "waiting" mode, and waits for the startup process to give new
  * instructions. The startup process will treat that the same as
@@ -96,6 +100,16 @@ bool		hot_standby_feedback;
 static WalReceiverConn *wrconn = NULL;
 WalReceiverFunctionsType *WalReceiverFunctions = NULL;
 
+/*
+ * This receiver's mode.  In feedback mode it must not write WAL files.
+ */
+static bool feedbackOnly;
+
+/*
+ * replay timeline at feedback session start.
+ */
+static TimeLineID feedbackTLI;
+
 /*
  * These variables are used similarly to openLogFile/SegNo,
  * but for walreceiver to write the XLOG. recvFileTLI is the TimeLineID
@@ -212,6 +226,7 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 		case WALRCV_CONNECTING:
 		case WALRCV_WAITING:
 		case WALRCV_STREAMING:
+		case WALRCV_FEEDBACK:
 		case WALRCV_RESTARTING:
 		default:
 			/* Shouldn't happen */
@@ -227,6 +242,7 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 	strlcpy(conninfo, walrcv->conninfo, MAXCONNINFO);
 	strlcpy(slotname, walrcv->slotname, NAMEDATALEN);
 	is_temp_slot = walrcv->is_temp_slot;
+	feedbackOnly = walrcv->feedbackOnly;
 	startpoint = walrcv->receiveStart;
 	startpointTLI = walrcv->receiveStartTLI;
 
@@ -235,9 +251,11 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 	 * RequestXLogStreaming messed up.
 	 */
 	Assert(!is_temp_slot || (slotname[0] == '\0'));
+	/* Feedback always uses a named physical slot. */
+	Assert(!feedbackOnly || slotname[0] != '\0');
 
-	/* Initialise to a sanish value */
-	now = GetCurrentTimestamp();
+	/* A feedback-only session has not yet heard from the sender. */
+	now = feedbackOnly ? 0 : GetCurrentTimestamp();
 	walrcv->lastMsgSendTime =
 		walrcv->lastMsgReceiptTime = walrcv->latestWalEndTime = now;
 
@@ -320,7 +338,7 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 		char	   *primary_sysid;
 		char		standby_sysid[32];
 		XLogRecPtr	primaryFlushPtr;
-		WalRcvStreamOptions options;
+		bool		started;
 
 		/*
 		 * Check that we're connected to a valid server using the
@@ -341,6 +359,16 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 		}
 		pfree(primary_sysid);
 
+		/* Bind feedback to the timeline of the last completed replay record. */
+		if (feedbackOnly)
+		{
+			if (!XLogRecPtrIsValid(GetXLogReplayRecPtr(&feedbackTLI)))
+				ereport(ERROR,
+						(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+						 errmsg("cannot start WAL receiver feedback without a valid replay position")));
+			startpointTLI = feedbackTLI;
+		}
+
 		/*
 		 * Confirm that the current timeline of the primary is the same or
 		 * ahead of ours.
@@ -379,7 +407,7 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 		 * indefinitely: if the upstream hasn't caught up within the timeout,
 		 * exit and let the startup process retry normally.
 		 */
-		if (startpointTLI == primaryTLI &&
+		if (!feedbackOnly && startpointTLI == primaryTLI &&
 			startpoint > primaryFlushPtr &&
 			startpoint - primaryFlushPtr <= wal_segment_size)
 		{
@@ -417,16 +445,18 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 		}
 
 		/*
-		 * Get any missing history files. We do this always, even when we're
-		 * not interested in that timeline, so that if we're promoted to
-		 * become the primary later on, we don't select the same timeline that
-		 * was already used in the current primary. This isn't bullet-proof -
+		 * For streaming, get any missing history files, even when we're not
+		 * interested in that timeline, so that if we're promoted to become
+		 * the primary later on, we don't select the same timeline that was
+		 * already used in the current primary. This isn't bullet-proof -
 		 * you'll need some external software to manage your cluster if you
 		 * need to ensure that a unique timeline id is chosen in every case,
 		 * but let's avoid the confusion of timeline id collisions where we
-		 * can.
+		 * can. In feedback mode only startup may install files from the
+		 * archive.
 		 */
-		WalRcvFetchTimeLineHistoryFiles(startpointTLI, primaryTLI);
+		if (!feedbackOnly)
+			WalRcvFetchTimeLineHistoryFiles(startpointTLI, primaryTLI);
 
 		/*
 		 * Create a temporary replication slot if requested.  This only needs
@@ -455,7 +485,7 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 		}
 
 		/*
-		 * Start streaming.
+		 * Start feedback or streaming.
 		 *
 		 * We'll try to start at the requested starting point and timeline,
 		 * even if it's different from the server's latest timeline. In case
@@ -466,13 +496,23 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 		 * history file, bump recovery target timeline, and ask us to restart
 		 * on the new timeline.
 		 */
-		options.logical = false;
-		options.startpoint = startpoint;
-		options.slotname = slotname[0] != '\0' ? slotname : NULL;
-		options.proto.physical.startpointTLI = startpointTLI;
-		if (walrcv_startstreaming(wrconn, &options))
+		if (feedbackOnly)
+			started = walrcv_startfeedback(wrconn, slotname, feedbackTLI);
+		else
 		{
-			if (first_stream)
+			WalRcvStreamOptions options;
+
+			options.logical = false;
+			options.startpoint = startpoint;
+			options.slotname = slotname[0] != '\0' ? slotname : NULL;
+			options.proto.physical.startpointTLI = startpointTLI;
+			started = walrcv_startstreaming(wrconn, &options);
+		}
+		if (started)
+		{
+			if (feedbackOnly)
+				set_ps_display("feedback");
+			else if (first_stream)
 				ereport(LOG,
 						errmsg("started streaming WAL from primary at %X/%08X on timeline %u",
 							   LSN_FORMAT_ARGS(startpoint), startpointTLI));
@@ -483,18 +523,19 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 			first_stream = false;
 
 			/*
-			 * Switch to STREAMING after a successful connection if current
-			 * state is CONNECTING.  This switch happens after an initial
+			 * Publish the active mode after a successful connection if the
+			 * state is still CONNECTING. This switch happens after an initial
 			 * startup, or after a restart as determined by
 			 * WalRcvWaitForStartPosition().
 			 */
 			SpinLockAcquire(&walrcv->mutex);
 			if (walrcv->walRcvState == WALRCV_CONNECTING)
-				walrcv->walRcvState = WALRCV_STREAMING;
+				walrcv->walRcvState = feedbackOnly ? WALRCV_FEEDBACK : WALRCV_STREAMING;
 			SpinLockRelease(&walrcv->mutex);
 
 			/* Initialize LogstreamResult for processing messages */
-			LogstreamResult.Write = LogstreamResult.Flush = GetXLogReplayRecPtr(NULL);
+			if (!feedbackOnly)
+				LogstreamResult.Write = LogstreamResult.Flush = GetXLogReplayRecPtr(NULL);
 
 			/* Initialize nap wakeup times. */
 			now = GetCurrentTimestamp();
@@ -502,7 +543,7 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 				WalRcvComputeNextWakeup(i, now);
 
 			/* Send initial reply/feedback messages. */
-			XLogWalRcvSendReply(true, false, false);
+			XLogWalRcvSendReply(true, feedbackOnly, false);
 			XLogWalRcvSendHSFeedback(true);
 
 			/* Loop until end-of-streaming or error */
@@ -568,6 +609,12 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 							break;
 						else if (len < 0)
 						{
+							/*
+							 * Only streaming has an end-of-timeline
+							 * handshake.
+							 */
+							if (feedbackOnly)
+								proc_exit(0);
 							ereport(LOG,
 									(errmsg("replication terminated by primary server"),
 									 errdetail("End of WAL reached on timeline %u at %X/%08X.",
@@ -583,11 +630,12 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 					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.
+					 * Flush received WAL and report progress to startup and
+					 * the upstream walsender.  Feedback mode writes nothing
+					 * to flush.
 					 */
-					XLogWalRcvFlush(false, startpointTLI);
+					if (!feedbackOnly)
+						XLogWalRcvFlush(false, startpointTLI);
 				}
 
 				/* Check if we need to exit the streaming loop. */
@@ -700,6 +748,12 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 			 */
 			WalRcvFetchTimeLineHistoryFiles(startpointTLI, primaryTLI);
 		}
+		else if (feedbackOnly)
+		{
+			/* An older upstream can still serve normal streaming requests. */
+			elog(DEBUG1, "upstream server does not support START_FEEDBACK");
+			proc_exit(0);
+		}
 		else
 			ereport(LOG,
 					(errmsg("primary server contains no more WAL on requested timeline %u",
@@ -883,14 +937,17 @@ WalRcvDie(int code, Datum arg)
 	WalRcvData *walrcv = WalRcv;
 	TimeLineID *startpointTLI_p = (TimeLineID *) DatumGetPointer(arg);
 
-	Assert(*startpointTLI_p != 0);
-
 	/* Ensure that all WAL records received are flushed to disk */
-	XLogWalRcvFlush(true, *startpointTLI_p);
+	if (!feedbackOnly)
+	{
+		Assert(*startpointTLI_p != 0);
+		XLogWalRcvFlush(true, *startpointTLI_p);
+	}
 
 	/* Mark ourselves inactive in shared memory */
 	SpinLockAcquire(&walrcv->mutex);
 	Assert(walrcv->walRcvState == WALRCV_STREAMING ||
+		   walrcv->walRcvState == WALRCV_FEEDBACK ||
 		   walrcv->walRcvState == WALRCV_CONNECTING ||
 		   walrcv->walRcvState == WALRCV_RESTARTING ||
 		   walrcv->walRcvState == WALRCV_STARTING ||
@@ -931,6 +988,11 @@ XLogWalRcvProcessMsg(unsigned char type, char *buf, Size len, TimeLineID tli)
 			{
 				StringInfoData incoming_message;
 
+				if (feedbackOnly)
+					ereport(ERROR,
+							(errcode(ERRCODE_PROTOCOL_VIOLATION),
+							 errmsg("received WAL data in a feedback-only session")));
+
 				hdrlen = sizeof(int64) + sizeof(int64) + sizeof(int64);
 				if (len < hdrlen)
 					ereport(ERROR,
@@ -1239,6 +1301,14 @@ XLogWalRcvSendReply(bool force, bool requestReply, bool checkApply)
 	 */
 	if (!force && now < wakeup[WALRCV_WAKEUP_REPLY])
 	{
+		/*
+		 * A feedback-only receiver has no writes or flushes to report, and
+		 * its apply position cannot release synchronous commits.  Wait for
+		 * the next periodic or forced reply.
+		 */
+		if (feedbackOnly)
+			return;
+
 		if (checkApply)
 			latestApplyPtr = GetXLogReplayRecPtr(NULL);
 
@@ -1252,10 +1322,31 @@ XLogWalRcvSendReply(bool force, bool requestReply, bool checkApply)
 	WalRcvComputeNextWakeup(WALRCV_WAKEUP_REPLY, now);
 
 	/* Construct a new message */
-	writePtr = LogstreamResult.Write;
-	flushPtr = LogstreamResult.Flush;
-	applyPtr = XLogRecPtrIsValid(latestApplyPtr) ?
-		latestApplyPtr : GetXLogReplayRecPtr(NULL);
+	if (feedbackOnly)
+	{
+		TimeLineID	replayTLI;
+
+		/*
+		 * Replayed WAL is already durable.  Sample the end of replay and its
+		 * timeline together; never report WAL from a new branch on a session
+		 * bound to the old one.  Startup can request a new receiver.
+		 */
+		applyPtr = GetXLogReplayRecPtr(&replayTLI);
+		if (replayTLI != feedbackTLI)
+		{
+			elog(DEBUG1, "ending WAL receiver feedback because replay switched from timeline %u to %u",
+				 feedbackTLI, replayTLI);
+			proc_exit(0);
+		}
+		writePtr = flushPtr = applyPtr;
+	}
+	else
+	{
+		writePtr = LogstreamResult.Write;
+		flushPtr = LogstreamResult.Flush;
+		applyPtr = XLogRecPtrIsValid(latestApplyPtr) ?
+			latestApplyPtr : GetXLogReplayRecPtr(NULL);
+	}
 
 	resetStringInfo(&reply_message);
 	pq_sendbyte(&reply_message, PqReplMsg_StandbyStatusUpdate);
@@ -1299,6 +1390,10 @@ XLogWalRcvSendHSFeedback(bool immed)
 	/* initially true so we always send at least one feedback message */
 	static bool primary_has_standby_xmin = true;
 
+	/* START_FEEDBACK currently accepts only standby status updates. */
+	if (feedbackOnly)
+		return;
+
 	/*
 	 * If the user doesn't want status to be reported to the primary, be sure
 	 * to exit before doing anything at all.
@@ -1451,7 +1546,13 @@ WalRcvComputeNextWakeup(WalRcvWakeupReason reason, TimestampTz now)
 				wakeup[reason] = TimestampTzPlusMilliseconds(now, wal_receiver_timeout / 2);
 			break;
 		case WALRCV_WAKEUP_HSFEEDBACK:
-			if (!hot_standby_feedback || wal_receiver_status_interval <= 0)
+
+			/*
+			 * START_FEEDBACK accepts replay reports, not xmin feedback.
+			 * XLogWalRcvSendHSFeedback() won't rearm this timer in feedback
+			 * mode, so an expired deadline would keep waking the receiver.
+			 */
+			if (feedbackOnly || !hot_standby_feedback || wal_receiver_status_interval <= 0)
 				wakeup[reason] = TIMESTAMP_INFINITY;
 			else
 				wakeup[reason] = TimestampTzPlusSeconds(now, wal_receiver_status_interval);
@@ -1479,9 +1580,14 @@ WalRcvRequestApplyReply(void)
 {
 	ProcNumber	procno;
 
-	WalRcv->apply_reply_requested = true;
-	/* fetching the proc number is probably atomic, but don't rely on it */
 	SpinLockAcquire(&WalRcv->mutex);
+	/* A feedback-only receiver cannot acknowledge a remote_apply commit. */
+	if (WalRcv->feedbackOnly)
+	{
+		SpinLockRelease(&WalRcv->mutex);
+		return;
+	}
+	WalRcv->apply_reply_requested = true;
 	procno = WalRcv->procno;
 	SpinLockRelease(&WalRcv->mutex);
 	if (procno != INVALID_PROC_NUMBER)
@@ -1505,6 +1611,8 @@ WalRcvGetStateString(WalRcvState state)
 			return "connecting";
 		case WALRCV_STREAMING:
 			return "streaming";
+		case WALRCV_FEEDBACK:
+			return "feedback";
 		case WALRCV_WAITING:
 			return "waiting";
 		case WALRCV_RESTARTING:
@@ -1527,6 +1635,7 @@ pg_stat_get_wal_receiver(PG_FUNCTION_ARGS)
 	bool	   *nulls;
 	int			pid;
 	bool		ready_to_display;
+	bool		feedback_only;
 	WalRcvState state;
 	XLogRecPtr	receive_start_lsn;
 	TimeLineID	receive_start_tli;
@@ -1547,6 +1656,7 @@ pg_stat_get_wal_receiver(PG_FUNCTION_ARGS)
 	pid = (int) WalRcv->pid;
 	ready_to_display = WalRcv->ready_to_display;
 	state = WalRcv->walRcvState;
+	feedback_only = WalRcv->feedbackOnly;
 	receive_start_lsn = WalRcv->receiveStart;
 	receive_start_tli = WalRcv->receiveStartTLI;
 	flushed_lsn = WalRcv->flushedUpto;
@@ -1645,6 +1755,15 @@ pg_stat_get_wal_receiver(PG_FUNCTION_ARGS)
 			nulls[14] = true;
 		else
 			values[14] = CStringGetTextDatum(conninfo);
+
+		/*
+		 * A feedback-only connection has no stream start, write or flush
+		 * positions or associated timelines; the shared values can be left
+		 * over from an earlier stream.  Keep latest_end_lsn, which the
+		 * upstream walsender reports in keepalives.
+		 */
+		if (feedback_only)
+			memset(&nulls[2], true, sizeof(bool) * 5);
 	}
 
 	/* Returns the record as Datum */
diff --git a/src/backend/replication/walreceiverfuncs.c b/src/backend/replication/walreceiverfuncs.c
index 4175e231ba4..e10758d28c0 100644
--- a/src/backend/replication/walreceiverfuncs.c
+++ b/src/backend/replication/walreceiverfuncs.c
@@ -24,6 +24,7 @@
 
 #include "access/xlog_internal.h"
 #include "access/xlogrecovery.h"
+#include "miscadmin.h"
 #include "pgstat.h"
 #include "replication/walreceiver.h"
 #include "storage/pmsignal.h"
@@ -37,6 +38,9 @@ WalRcvData *WalRcv = NULL;
 
 static void WalRcvShmemRequest(void *arg);
 static void WalRcvShmemInit(void *arg);
+static void RequestWalReceiver(bool feedbackOnly, TimeLineID tli, XLogRecPtr recptr,
+							   const char *conninfo, const char *slotname,
+							   bool create_temp_slot);
 
 const ShmemCallbacks WalRcvShmemCallbacks = {
 	.request_fn = WalRcvShmemRequest,
@@ -73,7 +77,7 @@ WalRcvShmemInit(void *arg)
 
 /* Return the walreceiver state after checking for a startup timeout. */
 static WalRcvState
-WalRcvGetStateWithTimeout(void)
+WalRcvGetStateWithTimeout(bool *feedbackOnly)
 {
 	WalRcvData *walrcv = WalRcv;
 	WalRcvState state;
@@ -83,6 +87,8 @@ WalRcvGetStateWithTimeout(void)
 
 	state = walrcv->walRcvState;
 	startTime = walrcv->startTime;
+	if (feedbackOnly)
+		*feedbackOnly = walrcv->feedbackOnly;
 
 	SpinLockRelease(&walrcv->mutex);
 
@@ -120,7 +126,7 @@ WalRcvGetStateWithTimeout(void)
 bool
 WalRcvRunning(void)
 {
-	return WalRcvGetStateWithTimeout() != WALRCV_STOPPED;
+	return WalRcvGetStateWithTimeout(NULL) != WALRCV_STOPPED;
 }
 
 /* Return the state of the walreceiver. */
@@ -144,10 +150,12 @@ WalRcvGetState(void)
 bool
 WalRcvStreaming(void)
 {
-	WalRcvState state = WalRcvGetStateWithTimeout();
+	bool		feedbackOnly;
+	WalRcvState state = WalRcvGetStateWithTimeout(&feedbackOnly);
 
-	return state == WALRCV_STREAMING || state == WALRCV_STARTING ||
-		state == WALRCV_CONNECTING || state == WALRCV_RESTARTING;
+	return !feedbackOnly &&
+		(state == WALRCV_STREAMING || state == WALRCV_STARTING ||
+		 state == WALRCV_CONNECTING || state == WALRCV_RESTARTING);
 }
 
 /*
@@ -178,6 +186,7 @@ ShutdownWalRcv(void)
 
 		case WALRCV_CONNECTING:
 		case WALRCV_STREAMING:
+		case WALRCV_FEEDBACK:
 		case WALRCV_WAITING:
 		case WALRCV_RESTARTING:
 			walrcv->walRcvState = WALRCV_STOPPING;
@@ -209,6 +218,33 @@ ShutdownWalRcv(void)
 	ConditionVariableCancelSleep();
 }
 
+/*
+ * Request a feedback-only receiver after startup has replayed a record and
+ * found more WAL in the archive or pg_wal.  Never interrupt an active or
+ * starting WAL stream.
+ */
+void
+RequestWalReceiverFeedback(const char *conninfo, const char *slotname)
+{
+	WalRcvState state;
+
+	Assert(AmStartupProcess() && StandbyMode);
+	Assert(slotname != NULL && slotname[0] != '\0');
+	state = WalRcvGetStateWithTimeout(NULL);
+
+	/*
+	 * Only startup can restart a receiver left waiting at the end of a
+	 * timeline.  Replace it so feedback uses the requested connection
+	 * settings.
+	 */
+	if (state == WALRCV_WAITING)
+		ShutdownWalRcv();
+	else if (state != WALRCV_STOPPED)
+		return;
+
+	RequestWalReceiver(true, 0, InvalidXLogRecPtr, conninfo, slotname, false);
+}
+
 /*
  * Request postmaster to start walreceiver.
  *
@@ -226,10 +262,11 @@ void
 RequestXLogStreaming(TimeLineID tli, XLogRecPtr recptr, const char *conninfo,
 					 const char *slotname, bool create_temp_slot)
 {
-	WalRcvData *walrcv = WalRcv;
-	bool		launch = false;
-	pg_time_t	now = (pg_time_t) time(NULL);
-	ProcNumber	walrcv_proc;
+	bool		feedbackOnly;
+
+	/* Streaming takes precedence, even if feedback is still connecting. */
+	if (WalRcvGetStateWithTimeout(&feedbackOnly) != WALRCV_STOPPED && feedbackOnly)
+		ShutdownWalRcv();
 
 	/*
 	 * We always start at the beginning of the segment. That prevents a broken
@@ -240,6 +277,24 @@ RequestXLogStreaming(TimeLineID tli, XLogRecPtr recptr, const char *conninfo,
 	if (XLogSegmentOffset(recptr, wal_segment_size) != 0)
 		recptr -= XLogSegmentOffset(recptr, wal_segment_size);
 
+	RequestWalReceiver(false, tli, recptr, conninfo, slotname, create_temp_slot);
+}
+
+/*
+ * Record startup's request for streaming or feedback in shared memory.
+ * Ask the postmaster to start a walreceiver if it is stopped; otherwise
+ * wake the existing receiver.  A feedback request leaves the last stream's
+ * receive position and timeline unchanged.
+ */
+static void
+RequestWalReceiver(bool feedbackOnly, TimeLineID tli, XLogRecPtr recptr,
+				   const char *conninfo, const char *slotname, bool create_temp_slot)
+{
+	WalRcvData *walrcv = WalRcv;
+	bool		launch = false;
+	pg_time_t	now = (pg_time_t) time(NULL);
+	ProcNumber	walrcv_proc;
+
 	SpinLockAcquire(&walrcv->mutex);
 
 	/* It better be stopped if we try to restart it */
@@ -279,13 +334,22 @@ RequestXLogStreaming(TimeLineID tli, XLogRecPtr recptr, const char *conninfo,
 	}
 	else
 		walrcv->walRcvState = WALRCV_RESTARTING;
+
+	/*
+	 * Clear the last reported upstream WAL end when starting or leaving
+	 * feedback mode.
+	 */
+	if (feedbackOnly || walrcv->feedbackOnly)
+		walrcv->latestWalEnd = InvalidXLogRecPtr;
+	walrcv->feedbackOnly = feedbackOnly;
 	walrcv->startTime = now;
 
 	/*
-	 * If this is the first startup of walreceiver (on this timeline),
-	 * initialize flushedUpto and latestChunkStart to the starting point.
+	 * Seed receipt positions on the first streaming request on a timeline. A
+	 * feedback-only request must preserve the last real stream's positions.
 	 */
-	if (!XLogRecPtrIsValid(walrcv->receiveStart) || walrcv->receivedTLI != tli)
+	if (!feedbackOnly &&
+		(!XLogRecPtrIsValid(walrcv->receiveStart) || walrcv->receivedTLI != tli))
 	{
 		walrcv->flushedUpto = recptr;
 		walrcv->receivedTLI = tli;
@@ -297,8 +361,11 @@ RequestXLogStreaming(TimeLineID tli, XLogRecPtr recptr, const char *conninfo,
 		 */
 		pg_atomic_write_membarrier_u64(&walrcv->writtenUpto, recptr);
 	}
-	walrcv->receiveStart = recptr;
-	walrcv->receiveStartTLI = tli;
+	if (!feedbackOnly)
+	{
+		walrcv->receiveStart = recptr;
+		walrcv->receiveStartTLI = tli;
+	}
 
 	walrcv_proc = walrcv->procno;
 
diff --git a/src/include/replication/walreceiver.h b/src/include/replication/walreceiver.h
index 5cfe90f9989..4ea9bcd1dc0 100644
--- a/src/include/replication/walreceiver.h
+++ b/src/include/replication/walreceiver.h
@@ -49,6 +49,7 @@ typedef enum
 								 * initialized yet */
 	WALRCV_CONNECTING,			/* connecting to upstream server */
 	WALRCV_STREAMING,			/* walreceiver is streaming */
+	WALRCV_FEEDBACK,			/* reporting replay without receiving WAL */
 	WALRCV_WAITING,				/* stopped streaming, waiting for orders */
 	WALRCV_RESTARTING,			/* asked to restart streaming */
 	WALRCV_STOPPING,			/* requested to stop, but still running */
@@ -70,6 +71,7 @@ typedef struct
 
 	/* Its current state */
 	WalRcvState walRcvState;
+	bool		feedbackOnly;
 	ConditionVariable walRcvStoppedCV;
 
 	/*
@@ -325,6 +327,10 @@ typedef void (*walrcv_readtimelinehistoryfile_fn) (WalReceiverConn *conn,
 typedef bool (*walrcv_startstreaming_fn) (WalReceiverConn *conn,
 										  const WalRcvStreamOptions *options);
 
+/* Start feedback for a named physical slot; return false for pre-20 servers. */
+typedef bool (*walrcv_startfeedback_fn) (WalReceiverConn *conn,
+										 const char *slotname, TimeLineID tli);
+
 /*
  * walrcv_endstreaming_fn
  *
@@ -424,6 +430,7 @@ typedef struct WalReceiverFunctionsType
 	walrcv_server_version_fn walrcv_server_version;
 	walrcv_readtimelinehistoryfile_fn walrcv_readtimelinehistoryfile;
 	walrcv_startstreaming_fn walrcv_startstreaming;
+	walrcv_startfeedback_fn walrcv_startfeedback;
 	walrcv_endstreaming_fn walrcv_endstreaming;
 	walrcv_receive_fn walrcv_receive;
 	walrcv_send_fn walrcv_send;
@@ -454,6 +461,8 @@ extern PGDLLIMPORT WalReceiverFunctionsType *WalReceiverFunctions;
 	WalReceiverFunctions->walrcv_readtimelinehistoryfile(conn, tli, filename, content, size)
 #define walrcv_startstreaming(conn, options) \
 	WalReceiverFunctions->walrcv_startstreaming(conn, options)
+#define walrcv_startfeedback(conn, slotname, tli) \
+	WalReceiverFunctions->walrcv_startfeedback(conn, slotname, tli)
 #define walrcv_endstreaming(conn, next_tli) \
 	WalReceiverFunctions->walrcv_endstreaming(conn, next_tli)
 #define walrcv_receive(conn, buffer, wait_fd) \
@@ -498,6 +507,7 @@ extern void ShutdownWalRcv(void);
 extern bool WalRcvStreaming(void);
 extern bool WalRcvRunning(void);
 extern WalRcvState WalRcvGetState(void);
+extern void RequestWalReceiverFeedback(const char *conninfo, const char *slotname);
 extern void RequestXLogStreaming(TimeLineID tli, XLogRecPtr recptr,
 								 const char *conninfo, const char *slotname,
 								 bool create_temp_slot);
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 0bd9a4f94c9..feb008bc54c 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -4445,6 +4445,7 @@ walrcv_readtimelinehistoryfile_fn
 walrcv_receive_fn
 walrcv_send_fn
 walrcv_server_version_fn
+walrcv_startfeedback_fn
 walrcv_startstreaming_fn
 wchar_t
 win32_deadchild_waitinfo
-- 
2.47.3

