From 577ae4c420d9b5d5ab72da4b33135044079e94db Mon Sep 17 00:00:00 2001
From: Nazir Bilal Yavuz <byavuz81@gmail.com>
Date: Thu, 19 Nov 2026 15:20:16 +0300
Subject: [PATCH v1 4/7] Add START_FEEDBACK for named physical replication
 slots

A standby replaying WAL from the archive needs a way to report its
progress without asking the upstream to send the same WAL. Add a
physical replication command:

`START_FEEDBACK SLOT slot_name TIMELINE tli`

The slot must have already reserved WAL, and the timeline must be in
the upstream's history.

The walsender accepts standby status updates and sends keepalives, but
sends no WAL. It appears as "feedback" in pg_stat_replication. For now,
it records the reply time. The next patch uses the reported replay
position to advance the slot.
---
 doc/src/sgml/monitoring.sgml                  |   6 +
 doc/src/sgml/protocol.sgml                    |  31 +++
 src/backend/replication/repl_gram.y           |  24 +-
 src/backend/replication/repl_scanner.l        |   2 +
 src/backend/replication/walsender.c           | 198 ++++++++++++--
 src/include/nodes/replnodes.h                 |  11 +
 src/include/replication/walsender_private.h   |   1 +
 src/test/recovery/meson.build                 |   1 +
 src/test/recovery/t/062_walsender_feedback.pl | 245 ++++++++++++++++++
 src/tools/pgindent/typedefs.list              |   1 +
 10 files changed, 495 insertions(+), 25 deletions(-)
 create mode 100644 src/test/recovery/t/062_walsender_feedback.pl

diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 68803c58d1c..69a9aa060fd 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -1513,6 +1513,12 @@ description | Waiting for a newly initialized WAL file to reach durable storage
           after its connected standby server has caught up with the primary.
          </para>
         </listitem>
+        <listitem>
+         <para>
+          <literal>feedback</literal>: This WAL sender is receiving standby
+          status updates without sending WAL.
+         </para>
+        </listitem>
         <listitem>
          <para>
           <literal>backup</literal>: This WAL sender is sending a backup.
diff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml
index f785575ebba..13bab853cfc 100644
--- a/doc/src/sgml/protocol.sgml
+++ b/doc/src/sgml/protocol.sgml
@@ -3013,6 +3013,37 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;"
      </listitem>
     </varlistentry>
 
+    <varlistentry id="protocol-replication-start-feedback">
+     <term><literal>START_FEEDBACK</literal> <literal>SLOT</literal> <replaceable>slot_name</replaceable> <literal>TIMELINE</literal> <replaceable>tli</replaceable>
+      <indexterm><primary>START_FEEDBACK</primary></indexterm>
+     </term>
+     <listitem>
+      <para>
+       Starts a feedback-only session on a physical replication connection.
+       The server enters bidirectional COPY mode but sends no WAL data.
+       The client can send <link linkend="protocol-replication-standby-status-update">standby
+       status updates</link>; any other CopyData message type from the client
+       causes the server to close the connection.  A status update can request
+       a <link linkend="protocol-replication-primary-keepalive-message">keepalive</link>,
+       whose WAL location is the server's flush position.
+       The server records the reply time and ignores the reported WAL
+       locations.  The connection cannot act as a synchronous standby.
+      </para>
+      <para>
+       The named slot must be a physical slot that has already reserved
+       WAL.  The server acquires it for the duration of the command.
+       The client must specify a timeline in the server's history.  For any
+       timeline other than timeline 1, the server's timeline history must show
+       where it began.
+      </para>
+      <para>
+       To end the session, send CopyDone.  The server replies with CopyDone
+       and releases the slot before sending CommandComplete.  Wait for
+       ReadyForQuery before issuing another command on the same connection.
+      </para>
+     </listitem>
+    </varlistentry>
+
     <varlistentry id="protocol-replication-start-replication-slot-logical">
      <term><literal>START_REPLICATION</literal> <literal>SLOT</literal> <replaceable class="parameter">slot_name</replaceable> <literal>LOGICAL</literal> <replaceable class="parameter">XXX/XXX</replaceable> [ ( <replaceable>option_name</replaceable> [ <replaceable>option_value</replaceable> ] [, ...] ) ]</term>
      <listitem>
diff --git a/src/backend/replication/repl_gram.y b/src/backend/replication/repl_gram.y
index aa8a96a3a60..f13aafd27c6 100644
--- a/src/backend/replication/repl_gram.y
+++ b/src/backend/replication/repl_gram.y
@@ -64,6 +64,7 @@
 %token K_READ_REPLICATION_SLOT
 %token K_SHOW
 %token K_START_REPLICATION
+%token K_START_FEEDBACK
 %token K_CREATE_REPLICATION_SLOT
 %token K_DROP_REPLICATION_SLOT
 %token K_ALTER_REPLICATION_SLOT
@@ -85,10 +86,10 @@
 %type <node>	base_backup start_replication start_logical_replication
 				create_replication_slot drop_replication_slot
 				alter_replication_slot identify_system read_replication_slot
-				timeline_history show upload_manifest
+				timeline_history show upload_manifest start_feedback
 %type <list>	generic_option_list
 %type <defelt>	generic_option
-%type <uintval>	opt_timeline
+%type <uintval>	opt_timeline timeline
 %type <list>	plugin_options plugin_opt_list
 %type <defelt>	plugin_opt_elem
 %type <node>	plugin_opt_arg
@@ -116,6 +117,7 @@ command:
 			| base_backup
 			| start_replication
 			| start_logical_replication
+			| start_feedback
 			| create_replication_slot
 			| drop_replication_slot
 			| alter_replication_slot
@@ -295,6 +297,17 @@ start_replication:
 				}
 			;
 
+/* START_FEEDBACK SLOT slot TIMELINE tli */
+start_feedback:
+			K_START_FEEDBACK K_SLOT IDENT timeline
+				{
+					StartFeedbackCmd *cmd = makeNode(StartFeedbackCmd);
+					cmd->slotname = $3;
+					cmd->timeline = $4;
+					$$ = (Node *) cmd;
+				}
+			;
+
 /* START_REPLICATION SLOT slot LOGICAL %X/%08X options */
 start_logical_replication:
 			K_START_REPLICATION K_SLOT IDENT K_LOGICAL RECPTR plugin_options
@@ -355,6 +368,11 @@ opt_slot:
 			;
 
 opt_timeline:
+				timeline				{ $$ = $1; }
+				| /* EMPTY */			{ $$ = 0; }
+			;
+
+timeline:
 			K_TIMELINE UCONST
 				{
 					if ($2 <= 0)
@@ -363,7 +381,6 @@ opt_timeline:
 								 errmsg("invalid timeline %u", $2)));
 					$$ = $2;
 				}
-				| /* EMPTY */			{ $$ = 0; }
 			;
 
 
@@ -427,6 +444,7 @@ ident_or_keyword:
 			| K_IDENTIFY_SYSTEM				{ $$ = "identify_system"; }
 			| K_SHOW						{ $$ = "show"; }
 			| K_START_REPLICATION			{ $$ = "start_replication"; }
+			| K_START_FEEDBACK				{ $$ = "start_feedback"; }
 			| K_CREATE_REPLICATION_SLOT	{ $$ = "create_replication_slot"; }
 			| K_DROP_REPLICATION_SLOT		{ $$ = "drop_replication_slot"; }
 			| K_ALTER_REPLICATION_SLOT		{ $$ = "alter_replication_slot"; }
diff --git a/src/backend/replication/repl_scanner.l b/src/backend/replication/repl_scanner.l
index af1615f9dbf..b7b37f06d9c 100644
--- a/src/backend/replication/repl_scanner.l
+++ b/src/backend/replication/repl_scanner.l
@@ -130,6 +130,7 @@ READ_REPLICATION_SLOT	{ return K_READ_REPLICATION_SLOT; }
 SHOW		{ return K_SHOW; }
 TIMELINE			{ return K_TIMELINE; }
 START_REPLICATION	{ return K_START_REPLICATION; }
+START_FEEDBACK		{ return K_START_FEEDBACK; }
 CREATE_REPLICATION_SLOT		{ return K_CREATE_REPLICATION_SLOT; }
 DROP_REPLICATION_SLOT		{ return K_DROP_REPLICATION_SLOT; }
 ALTER_REPLICATION_SLOT		{ return K_ALTER_REPLICATION_SLOT; }
@@ -308,6 +309,7 @@ replication_scanner_is_replication_command(yyscan_t yyscanner)
 		case K_IDENTIFY_SYSTEM:
 		case K_BASE_BACKUP:
 		case K_START_REPLICATION:
+		case K_START_FEEDBACK:
 		case K_CREATE_REPLICATION_SLOT:
 		case K_DROP_REPLICATION_SLOT:
 		case K_ALTER_REPLICATION_SLOT:
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index 74f6e8613b8..e12fb226214 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -184,6 +184,10 @@ static TimeLineID sendTimeLineNextTLI = 0;
 static bool sendTimeLineIsHistoric = false;
 static XLogRecPtr sendTimeLineValidUpto = InvalidXLogRecPtr;
 
+/* Requested feedback timeline and the local timeline that supplied its bounds. */
+static TimeLineHistoryEntry feedbackTimeLine;
+static TimeLineID feedbackHistoryTLI;
+
 /*
  * How far have we sent WAL already? This is also advertised in
  * MyWalSnd->sentPtr.  (Actually, this is the next WAL location to send.)
@@ -284,6 +288,7 @@ typedef enum
 {
 	WALSND_LOOP_PHYSICAL,
 	WALSND_LOOP_LOGICAL,
+	WALSND_LOOP_FEEDBACK,
 } WalSndLoopMode;
 
 /* Signal handlers */
@@ -874,6 +879,115 @@ SendCopyBothResponse(void)
 	pq_flush();
 }
 
+/* Acquire a slot for either physical streaming or feedback. */
+static void
+AcquirePhysicalSlot(const char *slotname)
+{
+	ReplicationSlotAcquire(slotname, true, true);
+	if (SlotIsLogical(MyReplicationSlot))
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				 errmsg("cannot use a logical replication slot for physical replication")));
+}
+
+/* Find the part of our history for which this client may report progress. */
+static void
+SetFeedbackTimeLine(TimeLineID tli, TimeLineID currentTLI)
+{
+	List	   *history = readTimeLineHistory(currentTLI);
+
+	foreach_ptr(TimeLineHistoryEntry, entry, history)
+	{
+		if (entry->tli == tli)
+		{
+			/*
+			 * readTimeLineHistory() assumes a timeline has no parents if its
+			 * history file is missing.  Only timeline 1 is known to start at
+			 * the beginning of WAL without a recorded fork point.
+			 */
+			if (tli != 1 && !XLogRecPtrIsValid(entry->begin))
+				ereport(ERROR,
+						(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+						 errmsg("could not determine the start of timeline %u from timeline history", tli)));
+
+			feedbackTimeLine = *entry;
+			feedbackHistoryTLI = currentTLI;
+			list_free_deep(history);
+			return;
+		}
+	}
+
+	ereport(ERROR,
+			(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+			 errmsg("requested timeline %u is not in this server's history", tli)));
+}
+
+/* Handle START_FEEDBACK on a physical replication connection. */
+static void
+StartFeedback(StartFeedbackCmd *cmd)
+{
+	WalSnd	   *walsnd = MyWalSnd;
+	TimeLineID	currentTLI;
+
+	/*
+	 * Any previous stream must have cleared replication_active.  Leave it
+	 * false so HandleWalSndInitStopping() terminates this sender without
+	 * waiting to send the shutdown checkpoint.
+	 */
+	Assert(!replication_active);
+
+	/* Physical replication connections aren't bound to a database. */
+	if (MyDatabaseId != InvalidOid)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("START_FEEDBACK requires a physical replication connection")));
+
+	AcquirePhysicalSlot(cmd->slotname);
+
+	/*
+	 * Feedback can advance an existing restart_lsn, but must not set the
+	 * initial one.  WAL following the standby's reported replay position may
+	 * already have been recycled if the slot never reserved it.
+	 */
+	if (!XLogRecPtrIsValid(MyReplicationSlot->data.restart_lsn))
+		ereport(ERROR,
+				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+				 errmsg("replication slot \"%s\" cannot be advanced", cmd->slotname),
+				 errdetail("This slot has never previously reserved WAL.")));
+
+	if (RecoveryInProgress())
+		(void) GetXLogReplayRecPtr(&currentTLI);
+	else
+		currentTLI = GetWALInsertionTimeLine();
+	SetFeedbackTimeLine(cmd->timeline, currentTLI);
+
+	/*
+	 * Don't carry over statistics from a previous stream on this connection.
+	 * Publish the new state with invalid LSNs, -1 lags, and a zero reply
+	 * time, so pg_stat_replication shows NULL for each until there is
+	 * something to report.
+	 */
+	sentPtr = InvalidXLogRecPtr;
+	SpinLockAcquire(&walsnd->mutex);
+	walsnd->state = WALSNDSTATE_FEEDBACK;
+	walsnd->sentPtr = sentPtr;
+	walsnd->write = walsnd->flush = walsnd->apply = InvalidXLogRecPtr;
+	walsnd->writeLag = walsnd->flushLag = walsnd->applyLag = -1;
+	walsnd->replyTime = 0;
+	SpinLockRelease(&walsnd->mutex);
+
+	/* Both peers may have sent CopyDone to end the previous command. */
+	streamingDoneSending = streamingDoneReceiving = false;
+	SendCopyBothResponse();
+
+	WalSndLoop(WALSND_LOOP_FEEDBACK);
+
+	ReplicationSlotRelease();
+
+	/* CopyDone ends the command; the connection can accept another one. */
+	WalSndSetState(WALSNDSTATE_STARTUP);
+}
+
 /*
  * Handle START_REPLICATION command.
  *
@@ -910,17 +1024,12 @@ StartReplication(StartReplicationCmd *cmd)
 
 	if (cmd->slotname)
 	{
-		ReplicationSlotAcquire(cmd->slotname, true, true);
-		if (SlotIsLogical(MyReplicationSlot))
-			ereport(ERROR,
-					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
-					 errmsg("cannot use a logical replication slot for physical replication")));
-
 		/*
 		 * We don't need to verify the slot's restart_lsn here; instead we
 		 * rely on the caller requesting the starting point to use.  If the
 		 * WAL segment doesn't exist, we'll fail later.
 		 */
+		AcquirePhysicalSlot(cmd->slotname);
 	}
 
 	/*
@@ -2318,6 +2427,14 @@ exec_replication_command(const char *cmd_string)
 				break;
 			}
 
+		case T_StartFeedbackCmd:
+			cmdtag = "START_FEEDBACK";
+			set_ps_display(cmdtag);
+			PreventInTransactionBlock(true, cmdtag);
+			StartFeedback((StartFeedbackCmd *) cmd_node);
+			EndReplicationCommand(cmdtag);
+			break;
+
 		case T_TimeLineHistoryCmd:
 			cmdtag = "TIMELINE_HISTORY";
 			set_ps_display(cmdtag);
@@ -2506,22 +2623,27 @@ ProcessStandbyMessage(void)
 	{
 		case PqReplMsg_StandbyStatusUpdate:
 			ProcessStandbyReplyMessage();
-			break;
+			return;
 
 		case PqReplMsg_HotStandbyFeedback:
+			/* In feedback mode, only standby status updates are allowed. */
+			if (MyWalSnd->state == WALSNDSTATE_FEEDBACK)
+				break;
 			ProcessStandbyHSFeedbackMessage();
-			break;
+			return;
 
 		case PqReplMsg_PrimaryStatusRequest:
+			/* In feedback mode, only standby status updates are allowed. */
+			if (MyWalSnd->state == WALSNDSTATE_FEEDBACK)
+				break;
 			ProcessStandbyPSRequestMessage();
-			break;
-
-		default:
-			ereport(COMMERROR,
-					(errcode(ERRCODE_PROTOCOL_VIOLATION),
-					 errmsg("unexpected message type \"%c\"", msgtype)));
-			proc_exit(0);
+			return;
 	}
+
+	ereport(COMMERROR,
+			(errcode(ERRCODE_PROTOCOL_VIOLATION),
+			 errmsg("unexpected message type \"%c\"", msgtype)));
+	proc_exit(0);
 }
 
 /*
@@ -2585,6 +2707,18 @@ ProcessStandbyReplyMessage(void)
 	replyTime = pq_getmsgint64(&reply_message);
 	replyRequested = pq_getmsgbyte(&reply_message);
 
+	/* Feedback-only sessions report liveness, not streaming acknowledgments. */
+	if (MyWalSnd->state == WALSNDSTATE_FEEDBACK)
+	{
+		pq_getmsgend(&reply_message);
+		SpinLockAcquire(&MyWalSnd->mutex);
+		MyWalSnd->replyTime = replyTime;
+		SpinLockRelease(&MyWalSnd->mutex);
+		if (replyRequested)
+			WalSndKeepalive(false, InvalidXLogRecPtr);
+		return;
+	}
+
 	if (message_level_is_interesting(DEBUG2))
 	{
 		char	   *replyTimeStr;
@@ -3096,7 +3230,7 @@ WalSndSendData(WalSndLoopMode mode)
 		XLogSendLogical();
 }
 
-/* Main loop of walsender process that streams the WAL over Copy messages. */
+/* Main COPY loop for streaming WAL or exchanging feedback. */
 static void
 WalSndLoop(WalSndLoopMode mode)
 {
@@ -3138,8 +3272,11 @@ WalSndLoop(WalSndLoopMode mode)
 		/*
 		 * Call WalSndSendData() only when the output buffer is empty.  While
 		 * output is pending, assume we are not caught up.
+		 *
+		 * A feedback-only sender never sends WAL, so leave WalSndCaughtUp
+		 * false even when its output buffer is empty.
 		 */
-		if (!pq_is_send_pending())
+		if (mode != WALSND_LOOP_FEEDBACK && !pq_is_send_pending())
 			WalSndSendData(mode);
 		else
 			WalSndCaughtUp = false;
@@ -3195,13 +3332,15 @@ WalSndLoop(WalSndLoopMode mode)
 		 * Block if we have unsent data.  XXX For logical replication, let
 		 * WalSndWaitForWal() handle any other blocking; idle receivers need
 		 * its additional actions.  For physical replication, also block if
-		 * caught up, since XLogSendPhysical() does not block.
+		 * caught up, since XLogSendPhysical() does not block. Feedback-only
+		 * senders can always wait for client input.
 		 *
 		 * The IO statistics are reported in WalSndWaitForWal() for the
 		 * logical WAL senders.
 		 */
-		if ((WalSndCaughtUp && mode == WALSND_LOOP_PHYSICAL &&
-			 !streamingDoneSending) ||
+		if ((!streamingDoneSending &&
+			 (mode == WALSND_LOOP_FEEDBACK ||
+			  (mode == WALSND_LOOP_PHYSICAL && WalSndCaughtUp))) ||
 			pq_is_send_pending())
 		{
 			long		sleeptime;
@@ -4155,6 +4294,7 @@ WalSndWait(uint32 socket_events, long timeout, uint32 wait_event,
 	 *
 	 * And, we use separate shared memory CVs for physical and logical
 	 * walsenders for selective wake ups, see WalSndWakeup() for more details.
+	 * A feedback-only sender need not wake up when WAL becomes available.
 	 *
 	 * If the wait event is WAIT_FOR_STANDBY_CONFIRMATION, wait on another CV
 	 * until awakened by physical walsenders after the walreceiver confirms
@@ -4162,7 +4302,8 @@ WalSndWait(uint32 socket_events, long timeout, uint32 wait_event,
 	 */
 	if (wait_event == WAIT_EVENT_WAIT_FOR_STANDBY_CONFIRMATION)
 		ConditionVariablePrepareToSleep(&WalSndCtl->wal_confirm_rcv_cv);
-	else if (MyWalSnd->kind == REPLICATION_KIND_PHYSICAL)
+	else if (MyWalSnd->kind == REPLICATION_KIND_PHYSICAL &&
+			 MyWalSnd->state != WALSNDSTATE_FEEDBACK)
 	{
 		ConditionVariablePrepareToSleep(&WalSndCtl->wal_flush_cv);
 
@@ -4344,6 +4485,8 @@ WalSndGetStateString(WalSndState state)
 			return "catchup";
 		case WALSNDSTATE_STREAMING:
 			return "streaming";
+		case WALSNDSTATE_FEEDBACK:
+			return "feedback";
 		case WALSNDSTATE_STOPPING:
 			return "stopping";
 	}
@@ -4542,10 +4685,21 @@ WalSndKeepalive(bool requestReply, XLogRecPtr writePtr)
 {
 	elog(DEBUG2, "sending replication keepalive");
 
+	/*
+	 * A feedback-only session sends no WAL, so sentPtr is invalid.  Report
+	 * the upstream's flush position as the end of WAL in the keepalive; it
+	 * says nothing about how far the standby has received or replayed.
+	 */
+	if (MyWalSnd->state == WALSNDSTATE_FEEDBACK)
+		writePtr = RecoveryInProgress() ?
+			GetStandbyFlushRecPtr(NULL) : GetFlushRecPtr(NULL);
+	else if (!XLogRecPtrIsValid(writePtr))
+		writePtr = sentPtr;
+
 	/* construct the message... */
 	resetStringInfo(&output_message);
 	pq_sendbyte(&output_message, PqReplMsg_Keepalive);
-	pq_sendint64(&output_message, XLogRecPtrIsValid(writePtr) ? writePtr : sentPtr);
+	pq_sendint64(&output_message, writePtr);
 	pq_sendint64(&output_message, GetCurrentTimestamp());
 	pq_sendbyte(&output_message, requestReply ? 1 : 0);
 
diff --git a/src/include/nodes/replnodes.h b/src/include/nodes/replnodes.h
index 74c6e129fda..a00f7bbf892 100644
--- a/src/include/nodes/replnodes.h
+++ b/src/include/nodes/replnodes.h
@@ -98,6 +98,17 @@ typedef struct StartReplicationCmd
 	List	   *options;
 } StartReplicationCmd;
 
+/* ----------------------
+ *		START_FEEDBACK command
+ * ----------------------
+ */
+typedef struct StartFeedbackCmd
+{
+	NodeTag		type;
+	char	   *slotname;
+	TimeLineID	timeline;
+} StartFeedbackCmd;
+
 
 /* ----------------------
  *		READ_REPLICATION_SLOT command
diff --git a/src/include/replication/walsender_private.h b/src/include/replication/walsender_private.h
index b0c80deeb24..9c7de99901b 100644
--- a/src/include/replication/walsender_private.h
+++ b/src/include/replication/walsender_private.h
@@ -27,6 +27,7 @@ typedef enum WalSndState
 	WALSNDSTATE_BACKUP,
 	WALSNDSTATE_CATCHUP,
 	WALSNDSTATE_STREAMING,
+	WALSNDSTATE_FEEDBACK,
 	WALSNDSTATE_STOPPING,
 } WalSndState;
 
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index cb3df6ed895..7c81d08dedb 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -70,6 +70,7 @@ tests += {
       't/059_remote_apply_status_interval.pl',
       't/060_multixact_crashed_updater.pl',
       't/061_recovery_target_prefetch.pl',
+      't/062_walsender_feedback.pl',
     ],
   },
 }
diff --git a/src/test/recovery/t/062_walsender_feedback.pl b/src/test/recovery/t/062_walsender_feedback.pl
new file mode 100644
index 00000000000..776f73f5dbd
--- /dev/null
+++ b/src/test/recovery/t/062_walsender_feedback.pl
@@ -0,0 +1,245 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# A feedback-only walsender can report the end of WAL in a keepalive, but
+# must not send WAL or release a commit waiting for a synchronous standby.
+# Act as the standby so we can choose which messages the walsender receives.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IO::Select;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+use Time::HiRes qw(time);
+
+# The wire client below relies on local authentication without a password.
+plan skip_all =>
+  'raw replication connection requires local socket authentication'
+  unless $PostgreSQL::Test::Utils::use_unix_sockets;
+
+# Enable logical decoding so we can check that feedback rejects a logical slot.
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 'logical');
+
+# Use the same name for synchronous_standby_names and the feedback client:
+# a streaming standby with that name could release the writer.  Disable
+# timed keepalives (0) so we only see the one requested by the client.  Use
+# local commits for setup; only the writer below should wait for a standby.
+my $standby_name = 'feedback_standby';
+$primary->append_conf(
+	'postgresql.conf', qq(
+synchronous_standby_names = '$standby_name'
+synchronous_commit = local
+wal_sender_timeout = 0
+));
+$primary->start;
+plan skip_all => 'this test requires working raw_connect()'
+  unless $primary->raw_connect_works();
+
+# Of the two physical slots, only feedback_slot reserves WAL at creation.
+# Use test_decoding to create a logical slot for the wrong-slot-type check.
+$primary->safe_psql(
+	'postgres', q[
+	SELECT pg_create_physical_replication_slot('feedback_slot', immediately_reserve => true);
+	SELECT pg_create_physical_replication_slot('unreserved');
+	SELECT pg_create_logical_replication_slot('decode_slot', 'test_decoding', failover => true);
+]);
+
+# Feedback requires both a slot and a timeline.  This primary is on timeline
+# 1 and has never been promoted, so timeline 2 is not in its history.
+for my $case (
+	[ 'START_FEEDBACK', qr/syntax error/ ],
+	[ 'START_FEEDBACK SLOT feedback_slot', qr/syntax error/ ],
+	[
+		'START_FEEDBACK SLOT unreserved TIMELINE 1',
+		qr/has never previously reserved WAL/
+	],
+	[
+		'START_FEEDBACK SLOT decode_slot TIMELINE 1',
+		qr/cannot use a logical replication slot/
+	],
+	[
+		'START_FEEDBACK SLOT feedback_slot TIMELINE 2',
+		qr/timeline 2 is not in this server's history/
+	])
+{
+	my ($command, $expected) = @$case;
+	my (undef, undef, $stderr) =
+	  $primary->psql('postgres', $command, replication => 'true');
+	like($stderr, $expected, "rejected $command");
+}
+
+# Use a separate physical replication connection for START_FEEDBACK.
+my $socket = $primary->raw_connect();
+binmode $socket;
+send_startup_packet();
+# A Query ('Q') contains a NUL-terminated command.  CopyBothResponse ('W')
+# means the server accepted it and entered bidirectional COPY.
+my $start_feedback = "START_FEEDBACK SLOT feedback_slot TIMELINE 1\0";
+send_message('Q', $start_feedback);
+expect_message('W', 'START_FEEDBACK entered bidirectional COPY');
+is($primary->slot('feedback_slot')->{active},
+	't', 'feedback acquired the physical slot');
+
+# CREATE TABLE generates WAL.  Wait for psql's marker rather than for the
+# command to finish: its commit must block until a synchronous standby replies.
+my $writer = $primary->background_psql('postgres');
+$writer->query_safe('SET synchronous_commit = on');
+my $writer_pid = $writer->query_safe('SELECT pg_backend_pid()');
+my $writer_wait =
+  "SELECT wait_event FROM pg_stat_activity WHERE pid = $writer_pid";
+$writer->query_until(qr/starting write/,
+	"\\echo starting write\nCREATE TABLE feedback_test (i integer);\n");
+# SyncRep confirms this writer reached the synchronous replication wait.
+$primary->poll_query_until('postgres', $writer_wait, 'SyncRep')
+  or die 'commit did not start waiting for a synchronous standby';
+
+# Report a position that covers the waiting commit.  Use a fixed, nonzero
+# send time: one microsecond after the PostgreSQL epoch, in two 32-bit words.
+# A zero timestamp would show up as NULL in pg_stat_replication.reply_time.
+my $report_time = pack('NN', 0, 1);
+my $reported_lsn = $primary->lsn('flush');
+my $wal_end = report_progress($reported_lsn, $report_time);
+# Compare the positions as pg_lsn values; psql prints true as 't'.
+is( $primary->safe_psql(
+		'postgres', "SELECT '$wal_end'::pg_lsn >= '$reported_lsn'::pg_lsn"),
+	't',
+	'keepalive covers the waiting commit');
+is($primary->safe_psql('postgres', $writer_wait),
+	'SyncRep', 'feedback did not release the synchronous commit');
+
+# The primary records the reply time.  Even though this standby is named in
+# synchronous_standby_names, its sender is asynchronous and has sent no WAL.
+is( $primary->safe_psql(
+		'postgres', qq[
+	SELECT state = 'feedback' AND sync_state = 'async'
+	       AND sent_lsn IS NULL AND reply_time IS NOT NULL
+	FROM pg_stat_replication WHERE application_name = '$standby_name']),
+	't',
+	'primary shows an asynchronous feedback sender that has sent no WAL');
+
+# Release the writer by clearing the list of synchronous standbys.
+$primary->adjust_conf('postgresql.conf', 'synchronous_standby_names', "''");
+$primary->reload;
+$writer->quit;
+
+# CopyDone ('c') has no body.  Before sending another query, expect CopyDone,
+# CommandComplete ('C') and ReadyForQuery ('Z'), in that order.
+send_message('c', '');
+expect_message('c', 'server replied with CopyDone');
+expect_message('C', 'server sent CommandComplete for START_FEEDBACK');
+expect_message('Z', 'server sent ReadyForQuery');
+is($primary->slot('feedback_slot')->{active},
+	'f', 'CopyDone released the physical slot');
+send_message('Q', $start_feedback);
+expect_message('W', 'same connection accepted a second START_FEEDBACK');
+is($primary->slot('feedback_slot')->{active},
+	't', 'second START_FEEDBACK reacquired the same slot');
+
+# 'p' (PqReplMsg_PrimaryStatusRequest) asks the primary to send its status.
+# It is valid during streaming but not during feedback.  Keep the socket open
+# so only the server can end the session.
+my $log_offset = -s $primary->logfile;
+send_message('d', 'p' . $report_time);    # 'd' is CopyData.
+$primary->wait_for_log(qr/unexpected message type "p"/, $log_offset);
+ok( $primary->poll_query_until(
+		'postgres', qq[
+	SELECT NOT EXISTS (SELECT * FROM pg_stat_activity
+	                   WHERE application_name = '$standby_name')]),
+	'walsender closed the connection after a disallowed message');
+
+$socket->close;
+$primary->stop;
+done_testing();
+
+# The startup packet has no type byte.  Its body starts with the protocol
+# version (3.0, two network-order 16-bit integers), followed by NUL-terminated
+# parameter names and values.  An empty name ends the list.
+sub send_startup_packet
+{
+	my $user = $primary->safe_psql('postgres', 'SELECT current_user');
+	my $version = pack('nn', 3, 0);
+	# replication=true selects physical replication; application_name must
+	# match the synchronous standby name configured above.
+	my $parameters = join("\0",
+		'user', $user, 'replication', 'true',
+		'application_name', $standby_name, '', '');
+	send_message('', $version . $parameters);
+	# Allow one timeout for the whole startup exchange, including partial reads.
+	my $deadline = time() + $PostgreSQL::Test::Utils::timeout_default;
+	while (1)
+	{
+		my ($type) = receive_message($deadline);
+		last if $type eq 'Z';    # ReadyForQuery ends the startup exchange.
+	}
+}
+
+# Send one standby status update, then read the requested keepalive.  Once
+# it arrives we know that the walsender has processed this particular report.
+sub report_progress
+{
+	my ($replay, $send_time) = @_;
+	# An LSN is printed as high/low hexadecimal halves.  Send each half as
+	# a network-order 32-bit integer; this also works on 32-bit Perl.
+	my ($high, $low) = split(m{/}, $replay);
+	my $position = pack('NN', hex($high), hex($low));
+	# 'r' identifies a standby status update inside CopyData ('d').  The
+	# LSNs are write, flush, replay, in order.  A final byte of 1 asks for
+	# an immediate reply.
+	my $request_reply = pack('C', 1);
+	my $positions = $position x 3;
+	send_message('d', 'r' . $positions . $send_time . $request_reply);
+
+	my ($type, $body) = receive_message();
+	die "expected CopyData after reporting replay $replay, got '$type'"
+	  unless $type eq 'd';
+	die "expected a keepalive after reporting replay $replay"
+	  unless length($body) == 18 && substr($body, 0, 1) eq 'k';
+	my ($wal_end_high, $wal_end_low) = unpack('xNN', $body);
+	return sprintf('%X/%X', $wal_end_high, $wal_end_low);
+}
+
+# Each message has a four-byte length ('N' for network byte order).  The
+# length includes the length field itself but not the one-byte message type.
+sub send_message
+{
+	my ($type, $body) = @_;
+	print {$socket} $type, pack('N', 4 + length($body)), $body or die $!;
+}
+
+sub receive_message
+{
+	my ($deadline) = @_;
+	$deadline //= time() + $PostgreSQL::Test::Utils::timeout_default;
+	# The five-byte header is one type byte followed by the four-byte length.
+	my ($type, $length) = unpack('aN', read_bytes(5, $deadline));
+	my $body = read_bytes($length - 4, $deadline);
+	die "walsender returned an error: $body" if $type eq 'E';
+	return ($type, $body);
+}
+
+sub expect_message
+{
+	local $Test::Builder::Level = $Test::Builder::Level + 1;
+	my ($expected, $description) = @_;
+	my ($type) = receive_message();
+	is($type, $expected, $description) or die 'unexpected walsender response';
+}
+
+# A socket read may return only part of the requested header or body.
+sub read_bytes
+{
+	my ($length, $deadline) = @_;
+	my $bytes = '';
+	while (length($bytes) < $length)
+	{
+		my $remaining = $deadline - time();
+		die "timed out reading from walsender\n" if $remaining <= 0;
+		next unless IO::Select->new($socket)->can_read($remaining);
+		# Don't buffer input in Perl: can_read() checks the socket itself.
+		sysread($socket, $bytes, $length - length($bytes), length($bytes))
+		  or die 'unexpected EOF on replication connection';
+	}
+	return $bytes;
+}
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 3d332ff45b9..0bd9a4f94c9 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2989,6 +2989,7 @@ StackElem
 StakindFlags
 StartBufferIOResult
 StartDataPtrType
+StartFeedbackCmd
 StartLOPtrType
 StartLOsPtrType
 StartReplicationCmd
-- 
2.47.3

