From 90482e442d29e4dade1d7871ca6bc557643ffa9f Mon Sep 17 00:00:00 2001
From: Nazir Bilal Yavuz <byavuz81@gmail.com>
Date: Fri, 20 Nov 2026 14:29:11 +0300
Subject: [PATCH v1 7/7] Report archive replay after a streaming failure

After a stream or a connection attempt fails, the standby may still
find WAL in the archive or pg_wal. If primary_conninfo and
primary_slot_name are set, request a feedback receiver after startup
applies the first record from either source. Opening a segment is too
early: the prefetcher can do that before replay reaches it. Initial
archive recovery and a normal end of timeline do not start feedback.

If the feedback connection fails, check again as replay crosses WAL
segment boundaries. Use wal_retrieve_retry_interval to limit how often
startup requests a new receiver. A change to the connection settings
or replay timeline can restart feedback. A replay pause or apply delay
does not by itself trigger a retry.

Add a recovery test that checks that the upstream slot reaches an
archived restore point while pg_last_wal_receive_lsn() stays unchanged.
It also checks that clearing and restoring either connection setting
restarts feedback at the same replay position, and that an unarchived
insert reaches the standby once streaming resumes.
---
 doc/src/sgml/config.sgml                      |   5 +
 doc/src/sgml/high-availability.sgml           |  13 ++
 src/backend/access/transam/xlogrecovery.c     | 100 ++++++++++-
 src/backend/replication/README                |  18 +-
 src/backend/replication/walreceiverfuncs.c    |   7 +-
 src/include/replication/walreceiver.h         |   2 +-
 src/test/recovery/meson.build                 |   1 +
 .../recovery/t/063_walreceiver_feedback.pl    | 162 ++++++++++++++++++
 8 files changed, 293 insertions(+), 15 deletions(-)
 create mode 100644 src/test/recovery/t/063_walreceiver_feedback.pl

diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 77cc523ce50..fc46616eb5f 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -5421,6 +5421,9 @@ ANY <replaceable class="parameter">num_sync</replaceable> ( <replaceable class="
           connecting to the sending server via streaming replication to control
           resource removal on the upstream node
           (see <xref linkend="streaming-replication-slots"/>).
+          After a streaming failure, the standby also uses this slot to
+          report replay progress from the archive or local <filename>pg_wal</filename>
+          (see <xref linkend="standby-server-operation"/>).
           This parameter can only be set in the <filename>postgresql.conf</filename>
           file or on the server command line.
           If this parameter is changed while the WAL receiver process is running,
@@ -5632,6 +5635,8 @@ ANY <replaceable class="parameter">num_sync</replaceable> ( <replaceable class="
         available from any sources (streaming physical replication,
         local <filename>pg_wal</filename> or WAL archive) before trying
         again to retrieve WAL data.
+        This interval also limits how often the standby retries a failed
+        feedback connection while replaying archive or local WAL.
         If this value is specified without units, it is taken as milliseconds.
         The default value is 5 seconds.
         This parameter can only be set in
diff --git a/doc/src/sgml/high-availability.sgml b/doc/src/sgml/high-availability.sgml
index 6e42e0eda49..554da9419a1 100644
--- a/doc/src/sgml/high-availability.sgml
+++ b/doc/src/sgml/high-availability.sgml
@@ -651,6 +651,19 @@ protocol to make nodes agree on a serializable transactional order.
     is stopped or is promoted.
    </para>
 
+   <para>
+    After a streaming connection fails, a standby that resumes replay from
+    the archive or <filename>pg_wal</filename> also tries to report its replay
+    position to the primary if both <xref linkend="guc-primary-conninfo"/> and
+    <xref linkend="guc-primary-slot-name"/> are set.  Initial archive replay
+    and reaching the normal end of a timeline do not start feedback.
+    This lets the primary release
+    WAL retained by the named physical slot, which must already have reserved
+    WAL.  This connection does not receive WAL or acknowledge synchronous
+    commits.  The standby continues replay if the primary is unreachable or
+    does not support <link linkend="protocol-replication-start-feedback"><literal>START_FEEDBACK</literal></link>.
+   </para>
+
    <para>
     Standby mode is exited and the server switches to normal operation
     when <command>pg_ctl promote</command> is run, or
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index e091a3e178b..3e420656564 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -253,6 +253,14 @@ static XLogSource currentSource = XLOG_FROM_ANY;
 static bool lastSourceFailed = false;
 static bool pendingWalRcvRestart = false;
 
+/*
+ * Check whether to start a feedback receiver when replay passes this LSN.
+ * PG_UINT64_MAX disables the check; zero requests a check after the next
+ * record is applied.  Otherwise this is a WAL segment boundary.
+ */
+static XLogRecPtr feedbackCheckAfter = PG_UINT64_MAX;
+static TimestampTz lastWalRcvFeedbackRequest = 0;
+
 /*
  * These variables track when we last obtained some WAL data to process,
  * and where we got it from.  (XLogReceiptSource is initially the same as
@@ -341,6 +349,8 @@ static bool recoveryStopAfter;
 static void ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI);
 
 static void EnableStandbyMode(void);
+static void MaybeStartWalReceiverFeedback(void);
+static void RestartWalReceiverFeedback(void);
 static void readRecoverySignalFile(void);
 static void validateRecoveryParameters(void);
 static bool read_backup_label(XLogRecPtr *checkPointLoc,
@@ -1803,6 +1813,17 @@ PerformWalRecovery(void)
 			 */
 			ApplyWalRecord(xlogreader, record, &replayTLI);
 
+			if (unlikely(xlogreader->EndRecPtr > feedbackCheckAfter))
+			{
+				/*
+				 * The prefetcher can open the next segment before replay gets
+				 * there.  Check after applying the first record, then only
+				 * when completed replay passes the next segment boundary.
+				 */
+				feedbackCheckAfter = TYPEALIGN64(wal_segment_size, xlogreader->EndRecPtr);
+				MaybeStartWalReceiverFeedback();
+			}
+
 			/*
 			 * Wake up processes waiting for standby replay, write, or flush
 			 * LSN to reach current replay position.  Replay implies that the
@@ -2058,6 +2079,10 @@ ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *repl
 
 		/* Reset the prefetcher. */
 		XLogPrefetchReconfigure();
+
+		/* A feedback session on the old timeline can't report this record. */
+		if (lastWalRcvFeedbackRequest != 0)
+			RestartWalReceiverFeedback();
 	}
 }
 
@@ -3567,6 +3592,7 @@ WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
 							bool nonblocking)
 {
 	static TimestampTz last_fail_time = 0;
+	static bool requestedStream = false;
 	TimestampTz now;
 	bool		streaming_reply_sent = false;
 
@@ -3655,6 +3681,8 @@ WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
 					 * walreceiver if necessary.
 					 */
 					currentSource = XLOG_FROM_STREAM;
+					feedbackCheckAfter = PG_UINT64_MAX;
+					lastWalRcvFeedbackRequest = 0;
 					startWalReceiver = true;
 					break;
 
@@ -3681,6 +3709,17 @@ WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
 					 */
 					Assert(StandbyMode);
 
+					/*
+					 * After a failed streaming attempt, check for feedback
+					 * once we apply a record from the archive or pg_wal.
+					 * Opening a recycled segment does not mean it contains
+					 * usable WAL. A receiver waiting at the end of a timeline
+					 * hasn't failed.
+					 */
+					if (requestedStream && WalRcvGetState() != WALRCV_WAITING)
+						feedbackCheckAfter = InvalidXLogRecPtr;
+					requestedStream = false;
+
 					/*
 					 * Before we leave XLOG_FROM_STREAM state, make sure that
 					 * walreceiver is not active, so that it won't overwrite
@@ -3790,8 +3829,8 @@ WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
 			case XLOG_FROM_PG_WAL:
 
 				/*
-				 * WAL receiver must not be running when reading WAL from
-				 * archive or pg_wal.
+				 * A feedback-only receiver may run here, but no receiver may
+				 * write WAL while startup is restoring it.
 				 */
 				Assert(!WalRcvStreaming());
 
@@ -3839,6 +3878,8 @@ WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
 					if (pendingWalRcvRestart && !startWalReceiver)
 					{
 						XLogShutdownWalRcv();
+						/* A configuration change ended the old stream. */
+						requestedStream = false;
 
 						/*
 						 * Re-scan for possible new timelines if we were
@@ -3892,6 +3933,7 @@ WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
 						RequestXLogStreaming(tli, ptr, PrimaryConnInfo,
 											 PrimarySlotName,
 											 wal_receiver_create_temp_slot);
+						requestedStream = true;
 						flushedUpto = InvalidXLogRecPtr;
 					}
 
@@ -4407,13 +4449,61 @@ XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source)
 }
 
 /*
- * Set flag to signal the walreceiver to restart.  (The startup process calls
- * this on noticing a relevant configuration change.)
+ * After a streaming failure, request feedback for the configured upstream
+ * and slot unless promotion is pending.  Rate-limit startup's requests to
+ * launch a walreceiver, not the status reports sent by a connected one.
+ */
+static void
+MaybeStartWalReceiverFeedback(void)
+{
+	TimestampTz now;
+
+	Assert(StandbyMode && InRedo);
+	if (LocalPromoteIsTriggered || IsPromoteSignaled() ||
+		PrimaryConnInfo[0] == '\0' || PrimarySlotName[0] == '\0')
+		return;
+
+	now = GetCurrentTimestamp();
+	if (TimestampDifferenceExceeds(lastWalRcvFeedbackRequest, now,
+								   wal_retrieve_retry_interval))
+	{
+		if (RequestWalReceiverFeedback(PrimaryConnInfo, PrimarySlotName))
+			lastWalRcvFeedbackRequest = now;
+	}
+}
+
+/*
+ * Stop any receiver using the old connection settings or replay timeline.
+ * The retry interval for the old request need not delay a new one.
+ */
+static void
+RestartWalReceiverFeedback(void)
+{
+	Assert(currentSource != XLOG_FROM_STREAM);
+	if (WalRcvRunning())
+		ShutdownWalRcv();
+	lastWalRcvFeedbackRequest = 0;
+
+	/* Once we've applied WAL, we can reconsider feedback even during a pause. */
+	if (InRedo && feedbackCheckAfter != PG_UINT64_MAX &&
+		XLogRecPtrIsValid(feedbackCheckAfter))
+		MaybeStartWalReceiverFeedback();
+}
+
+/*
+ * A connection setting has changed.  During archive or local replay, startup
+ * can reconsider feedback immediately.  When streaming, leave the restart to
+ * the WAL retrieval loop.
  */
 void
 StartupRequestWalReceiverRestart(void)
 {
-	if (currentSource == XLOG_FROM_STREAM && WalRcvRunning())
+	if (!StandbyMode)
+		return;
+
+	if (currentSource != XLOG_FROM_STREAM)
+		RestartWalReceiverFeedback();
+	else if (WalRcvRunning())
 	{
 		ereport(LOG,
 				(errmsg("WAL receiver process shutdown requested")));
diff --git a/src/backend/replication/README b/src/backend/replication/README
index 3460e752c4b..ebe2f98ef49 100644
--- a/src/backend/replication/README
+++ b/src/backend/replication/README
@@ -36,9 +36,15 @@ 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.
+After a stream or streaming connection attempt fails, startup requests a
+feedback-only receiver with RequestWalReceiverFeedback() once it replays WAL
+from the archive or pg_wal, if primary_conninfo and primary_slot_name are set.
+Initial archive replay and a normal end of timeline do not start feedback.
+If the feedback connection fails, the standby continues replay. As replay
+crosses WAL segment boundaries, startup can request another feedback-only
+walreceiver, provided wal_retrieve_retry_interval has elapsed since its last
+request. The receiver 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
@@ -46,11 +52,11 @@ 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.
+If the old walsender still holds the slot when the new connection requests
+streaming, recovery retries as it would after any streaming disconnect.
 
 Walsender IPC
 -------------
diff --git a/src/backend/replication/walreceiverfuncs.c b/src/backend/replication/walreceiverfuncs.c
index e10758d28c0..6b9d79d4ce3 100644
--- a/src/backend/replication/walreceiverfuncs.c
+++ b/src/backend/replication/walreceiverfuncs.c
@@ -221,9 +221,9 @@ ShutdownWalRcv(void)
 /*
  * 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.
+ * starting WAL stream.  Return true if a new receiver was requested.
  */
-void
+bool
 RequestWalReceiverFeedback(const char *conninfo, const char *slotname)
 {
 	WalRcvState state;
@@ -240,9 +240,10 @@ RequestWalReceiverFeedback(const char *conninfo, const char *slotname)
 	if (state == WALRCV_WAITING)
 		ShutdownWalRcv();
 	else if (state != WALRCV_STOPPED)
-		return;
+		return false;
 
 	RequestWalReceiver(true, 0, InvalidXLogRecPtr, conninfo, slotname, false);
+	return true;
 }
 
 /*
diff --git a/src/include/replication/walreceiver.h b/src/include/replication/walreceiver.h
index 4ea9bcd1dc0..23d1dfdaf71 100644
--- a/src/include/replication/walreceiver.h
+++ b/src/include/replication/walreceiver.h
@@ -507,7 +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 bool 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/test/recovery/meson.build b/src/test/recovery/meson.build
index 7c81d08dedb..ea2a631c076 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -71,6 +71,7 @@ tests += {
       't/060_multixact_crashed_updater.pl',
       't/061_recovery_target_prefetch.pl',
       't/062_walsender_feedback.pl',
+      't/063_walreceiver_feedback.pl',
     ],
   },
 }
diff --git a/src/test/recovery/t/063_walreceiver_feedback.pl b/src/test/recovery/t/063_walreceiver_feedback.pl
new file mode 100644
index 00000000000..31b0cd3b9ab
--- /dev/null
+++ b/src/test/recovery/t/063_walreceiver_feedback.pl
@@ -0,0 +1,162 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Check when an archive-replaying standby starts feedback after losing a stream.
+use strict;
+use warnings FATAL => 'all';
+
+use File::Copy qw(copy);
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 1, has_archiving => 1);
+$primary->append_conf('postgresql.conf', "wal_keep_size = '128MB'");
+$primary->start;
+$primary->safe_psql('postgres', 'CREATE TABLE t (i integer)');
+$primary->safe_psql('postgres',
+	"SELECT pg_create_physical_replication_slot('feedback', true)");
+
+# A normal end of timeline must not start feedback, even if there is more
+# WAL to replay locally.
+$primary->backup('old_timeline');
+$primary->safe_psql('postgres',
+	"SELECT pg_create_restore_point('old_timeline'); SELECT pg_switch_wal()");
+$primary->set_standby_mode;
+$primary->restart;
+$primary->promote;
+
+$primary->safe_psql('postgres',
+	"SELECT pg_create_restore_point('new_timeline')");
+archive_segment();
+$primary->safe_psql('postgres', 'INSERT INTO t VALUES (1)');
+archive_segment();
+
+# Put the new timeline's segments in local pg_wal, but leave out its history
+# file. The standby must first stream the old timeline. At its end, the WAL
+# receiver waits for instructions and startup can use the local segments.
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, 'old_timeline', has_streaming => 1);
+for my $file (grep { /^00000002[0-9A-F]{16}$/ }
+	slurp_dir($primary->archive_dir))
+{
+	copy($primary->archive_dir . "/$file", $standby->data_dir . '/pg_wal')
+	  or die "copy $file: $!";
+}
+$standby->append_conf(
+	'postgresql.conf', qq(
+primary_slot_name = 'feedback'
+recovery_min_apply_delay = '1d'
+max_standby_archive_delay = -1
+wal_receiver_status_interval = 1
+));
+$standby->start;
+$standby->wait_for_event('startup', 'RecoveryApplyDelay');
+is( $standby->safe_psql(
+		'postgres',
+		'SELECT pg_last_wal_receive_lsn() < pg_last_wal_replay_lsn()'),
+	't',
+	'local replay passed the end of the old WAL stream');
+is( $standby->safe_psql(
+		'postgres', 'SELECT status FROM pg_stat_wal_receiver'),
+	'waiting',
+	'normal end of a timeline does not trigger feedback');
+
+# Enable archive restore for the next streaming failure. This insert is
+# not archived, so the standby must first catch up by streaming.
+$standby->enable_restoring($primary, 1);
+$standby->append_conf('postgresql.conf', 'recovery_min_apply_delay = 0');
+$standby->reload;
+$primary->safe_psql('postgres', 'INSERT INTO t VALUES (2)');
+$primary->wait_for_catchup('standby', 'replay');
+is($standby->safe_psql('postgres', 'SELECT sum(i) FROM t'),
+	'3', 'streaming resumed and delivered new WAL');
+is( $standby->safe_psql(
+		'postgres', 'SELECT status FROM pg_stat_wal_receiver'),
+	'streaming',
+	'caught-up stream is still streaming');
+
+# Keep startup paused until the stream is gone and the transaction is archived.
+$standby->safe_psql('postgres', 'SELECT pg_wal_replay_pause()');
+$standby->wait_for_event('startup', 'RecoveryPause');
+$primary->safe_psql('postgres',
+	"SELECT pg_terminate_backend(active_pid) FROM pg_replication_slots WHERE slot_name = 'feedback'"
+);
+$standby->poll_query_until('postgres',
+	'SELECT count(*) = 0 FROM pg_stat_wal_receiver')
+  or die 'standby did not lose the stream';
+my $received = $standby->lsn('receive');
+
+# Hold replay at the archived commit while checking feedback and reloads.
+$standby->append_conf('postgresql.conf', "recovery_min_apply_delay = '1d'");
+$standby->reload;
+$primary->safe_psql('postgres', 'INSERT INTO t VALUES (3)');
+archive_segment();
+$standby->safe_psql('postgres', 'SELECT pg_wal_replay_resume()');
+$standby->wait_for_event('startup', 'RecoveryApplyDelay');
+my $delayed_lsn = $standby->lsn('replay');
+# A new sender inherits the slot's position, but not its reply time.
+my $feedback_slot = q{FROM pg_replication_slots s
+  JOIN pg_stat_replication r ON r.pid = s.active_pid
+  WHERE s.slot_name = 'feedback' AND r.state = 'feedback' AND r.reply_time IS NOT NULL};
+my $feedback_at_delayed_lsn =
+  "SELECT restart_lsn = '$delayed_lsn' $feedback_slot";
+$primary->poll_query_until('postgres', $feedback_at_delayed_lsn)
+  or die 'standby did not report archive replay';
+
+for my $setting (qw(primary_conninfo primary_slot_name))
+{
+	my $value = $standby->safe_psql('postgres', "SHOW $setting");
+	$standby->append_conf('postgresql.conf', "$setting = ''");
+	$standby->reload;
+	$primary->poll_query_until('postgres',
+		"SELECT NOT active FROM pg_replication_slots WHERE slot_name = 'feedback'"
+	) or die "clearing $setting did not release the slot";
+	$standby->append_conf('postgresql.conf', "$setting = '$value'");
+	$standby->reload;
+	ok($primary->poll_query_until('postgres', $feedback_at_delayed_lsn),
+		"feedback reconnected after restoring $setting");
+}
+my $feedback_pid = $primary->slot('feedback')->{active_pid};
+
+# Once the apply delay is lifted, let startup pass the restore point but
+# block it on the next lock record. Otherwise it could run out of archive
+# and switch to streaming before we observe the sender's next report.
+my $blocker = $standby->background_psql('postgres');
+$blocker->query_safe('BEGIN; LOCK t IN ACCESS SHARE MODE');
+my $marker = $primary->safe_psql('postgres',
+	"SELECT pg_create_restore_point('archive_target')");
+$primary->safe_psql('postgres',
+	'BEGIN; LOCK t IN ACCESS EXCLUSIVE MODE; COMMIT');
+archive_segment();
+$standby->append_conf('postgresql.conf', 'recovery_min_apply_delay = 0');
+$standby->reload;
+ok( $primary->poll_query_until(
+		'postgres',
+		"SELECT restart_lsn >= '$marker' $feedback_slot AND r.pid = $feedback_pid"
+	),
+	'the same feedback sender advanced the slot to the archived restore point'
+);
+is( $standby->safe_psql(
+		'postgres', qq[SELECT pg_last_wal_receive_lsn() = '$received'
+		AND pg_last_wal_replay_lsn() >= '$marker']),
+	't',
+	'standby replayed the restore point without streaming');
+
+# This insert is in the next, unarchived segment.
+$primary->safe_psql('postgres', 'INSERT INTO t VALUES (4)');
+$blocker->quit;
+$primary->wait_for_catchup('standby', 'replay');
+is($standby->safe_psql('postgres', 'SELECT max(i) FROM t'),
+	'4', 'streaming delivered new WAL');
+
+done_testing();
+
+sub archive_segment
+{
+	my $seg = $primary->safe_psql('postgres',
+		'SELECT pg_walfile_name(pg_switch_wal())');
+	$primary->poll_query_until('postgres',
+		"SELECT last_archived_wal >= '$seg' FROM pg_stat_archiver")
+	  or die "WAL segment $seg was not archived";
+}
-- 
2.47.3

