From 1ecb3d9e85dd3e9710526bb85db0b8e121bb3efb Mon Sep 17 00:00:00 2001
From: Nazir Bilal Yavuz <byavuz81@gmail.com>
Date: Thu, 19 Nov 2026 18:07:58 +0300
Subject: [PATCH v1 5/7] Advance physical slots to the reported replay position

Use the replay position reported by START_FEEDBACK to advance the
slot's restart_lsn. This lets the upstream release WAL that the
standby has already replayed from the archive.

Only advance the slot if the reported positions satisfy
apply <= flush <= write and the replay position is on the requested
timeline. On a primary, the upper limit is the local flush position.
On a cascading standby, it is the local replay position. Recheck the
timeline bounds if the upstream changes timelines. A record ending
exactly at the fork still belongs to the old timeline.

Use the same slot confirmation code as physical streaming. This lets
logical decoding waiting on synchronized_standby_slots proceed up to
the reported position.
---
 doc/src/sgml/protocol.sgml                    |  25 ++-
 src/backend/replication/walsender.c           |  32 +++-
 src/test/recovery/t/062_walsender_feedback.pl | 142 ++++++++++++------
 3 files changed, 148 insertions(+), 51 deletions(-)

diff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml
index 13bab853cfc..9178b4a45ef 100644
--- a/doc/src/sgml/protocol.sgml
+++ b/doc/src/sgml/protocol.sgml
@@ -3026,15 +3026,28 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;"
        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.
+       The server records the reply time.  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.
+       WAL.  The server acquires it for the duration of the command and can
+       advance its <structfield>restart_lsn</structfield> to the client's
+       reported replay position.  The WAL through that position must be
+       durable on the client.
+       The client must specify the timeline of the last replayed record, which
+       must be in the server's history, and start a new feedback session before
+       reporting replay on another timeline.  For any timeline other than
+       timeline 1, the server's timeline history must show where it began.
+      </para>
+      <para>
+       The server ignores replay positions that would move the slot backwards, lie
+       outside the specified timeline in its history, or exceed its own flush
+       position (replay position on a cascading sender).  The reported replay,
+       flush, and write positions must be in ascending order or equal.
+       Advancing the slot also allows logical decoding waiting on
+       <xref linkend="guc-synchronized-standby-slots"/> to proceed up to the
+       confirmed position.
       </para>
       <para>
        To end the session, send CopyDone.  The server replies with CopyDone
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index e12fb226214..05debf384ec 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -2679,6 +2679,33 @@ PhysicalConfirmReceivedLocation(XLogRecPtr lsn)
 	 */
 }
 
+/* Advance the slot to the reported end of replay, if it is in our history. */
+static void
+ConfirmFeedbackReplay(XLogRecPtr replay)
+{
+	TimeLineID	currentTLI;
+	XLogRecPtr	localEnd;
+
+	/* We own the slot; a delayed report must not move it backwards. */
+	if (replay <= MyReplicationSlot->data.restart_lsn)
+		return;
+
+	/* As in pg_replication_slot_advance(), use replay on a cascading sender. */
+	localEnd = RecoveryInProgress() ?
+		GetXLogReplayRecPtr(&currentTLI) : GetFlushRecPtr(&currentTLI);
+	if (replay > localEnd)
+		return;
+
+	/* Promotion or a timeline switch may have ended the client's timeline. */
+	if (currentTLI != feedbackHistoryTLI)
+		SetFeedbackTimeLine(feedbackTimeLine.tli, currentTLI);
+
+	/* replay is the end of the record, so test the timeline of replay - 1. */
+	if (replay > feedbackTimeLine.begin &&
+		(!XLogRecPtrIsValid(feedbackTimeLine.end) || replay <= feedbackTimeLine.end))
+		PhysicalConfirmReceivedLocation(replay);
+}
+
 /*
  * Regular reply from standby advising of WAL locations on standby server.
  */
@@ -2707,10 +2734,13 @@ ProcessStandbyReplyMessage(void)
 	replyTime = pq_getmsgint64(&reply_message);
 	replyRequested = pq_getmsgbyte(&reply_message);
 
-	/* Feedback-only sessions report liveness, not streaming acknowledgments. */
+	/* Feedback can advance a physical slot but cannot release sync commits. */
 	if (MyWalSnd->state == WALSNDSTATE_FEEDBACK)
 	{
 		pq_getmsgend(&reply_message);
+		if (applyPtr <= flushPtr && flushPtr <= writePtr)
+			ConfirmFeedbackReplay(applyPtr);
+
 		SpinLockAcquire(&MyWalSnd->mutex);
 		MyWalSnd->replyTime = replyTime;
 		SpinLockRelease(&MyWalSnd->mutex);
diff --git a/src/test/recovery/t/062_walsender_feedback.pl b/src/test/recovery/t/062_walsender_feedback.pl
index 776f73f5dbd..82c59c3eeac 100644
--- a/src/test/recovery/t/062_walsender_feedback.pl
+++ b/src/test/recovery/t/062_walsender_feedback.pl
@@ -1,7 +1,7 @@
 # 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.
+# A feedback-only walsender can advance a physical slot to a valid replay
+# position, but must not send WAL or release a synchronous commit.
 # Act as the standby so we can choose which messages the walsender receives.
 
 use strict;
@@ -18,7 +18,6 @@ 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');
 
@@ -26,22 +25,25 @@ $primary->init(allows_streaming => 'logical');
 # 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.
+# Logical decoding on the failover slot must wait for feedback_slot.
 my $standby_name = 'feedback_standby';
 $primary->append_conf(
 	'postgresql.conf', qq(
 synchronous_standby_names = '$standby_name'
 synchronous_commit = local
+synchronized_standby_slots = 'feedback_slot'
 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.
+my $create_feedback_slot = q[
+	SELECT lsn FROM pg_create_physical_replication_slot('feedback_slot', immediately_reserve => true)];
+my $initial_lsn = $primary->safe_psql('postgres', $create_feedback_slot);
 $primary->safe_psql(
 	'postgres', q[
-	SELECT pg_create_physical_replication_slot('feedback_slot', immediately_reserve => true);
+	CREATE TABLE feedback_test (i integer);
 	SELECT pg_create_physical_replication_slot('unreserved');
 	SELECT pg_create_logical_replication_slot('decode_slot', 'test_decoding', failover => true);
 ]);
@@ -70,42 +72,64 @@ for my $case (
 	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.
+# Pause replay so the standby can receive both inserts without applying them.
+$primary->backup('base');
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, 'base', has_streaming => 1);
+$standby->start;
+my $standby_initial_lsn =
+  $standby->safe_psql('postgres', $create_feedback_slot);
+$standby->safe_psql('postgres', 'SELECT pg_wal_replay_pause()');
+
+my $socket;
 my $start_feedback = "START_FEEDBACK SLOT feedback_slot TIMELINE 1\0";
-send_message('Q', $start_feedback);
-expect_message('W', 'START_FEEDBACK entered bidirectional COPY');
+connect_feedback($primary);
 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.
+# Row 0 commits locally; row 1 waits for synchronous replication.
+$primary->safe_psql('postgres', 'INSERT INTO feedback_test VALUES (0)');
+my $row0_lsn = $primary->lsn('flush');
+
 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.
+	"\\echo starting write\nINSERT INTO feedback_test VALUES (1);\n");
 $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'.
+my $row1_lsn = $primary->lsn('flush');
+
+is(restart_lsn_after_report($primary, 'FFFFFFFF/FFFFFFFF'),
+	$initial_lsn, 'ignored replay ahead of the primary');
+is(restart_lsn_after_report($primary, $row1_lsn, $row0_lsn, $row1_lsn),
+	$initial_lsn, 'ignored replay ahead of standby flush');
+is(restart_lsn_after_report($primary, $row1_lsn, $row1_lsn, $row0_lsn),
+	$row0_lsn, 'advanced only to replay');
+is(restart_lsn_after_report($primary, $initial_lsn),
+	$row0_lsn, 'stale report did not rewind the slot');
+
+my $wal_end = report_progress($row1_lsn);
 is( $primary->safe_psql(
-		'postgres', "SELECT '$wal_end'::pg_lsn >= '$reported_lsn'::pg_lsn"),
+		'postgres', "SELECT '$wal_end'::pg_lsn >= '$row1_lsn'::pg_lsn"),
 	't',
 	'keepalive covers the waiting commit');
+is($primary->slot('feedback_slot')->{restart_lsn},
+	$row1_lsn, 'advanced to the replayed commit');
+
+# Decode only through the reported LSN; newer WAL has not been confirmed.
+like(
+	$primary->safe_psql(
+		'postgres',
+		"SELECT data FROM pg_logical_slot_peek_changes('decode_slot', '$row1_lsn', NULL)",
+		timeout => $PostgreSQL::Test::Utils::timeout_default),
+	qr/^table public\.feedback_test: INSERT: i\[integer\]:0$/m,
+	'logical decoding returned row 0 after feedback advanced the slot');
 is($primary->safe_psql('postgres', $writer_wait),
 	'SyncRep', 'feedback did not release the synchronous commit');
 
@@ -150,18 +174,39 @@ ok( $primary->poll_query_until(
 	'walsender closed the connection after a disallowed message');
 
 $socket->close;
+
+# Report the same LSN before and after the standby replays the inserts.
+connect_feedback($standby);
+$primary->wait_for_catchup($standby, 'flush', $row0_lsn);
+is(restart_lsn_after_report($standby, $row0_lsn),
+	$standby_initial_lsn,
+	'cascading sender ignored WAL it received but has not replayed');
+
+$standby->safe_psql('postgres', 'SELECT pg_wal_replay_resume()');
+$primary->wait_for_catchup($standby, 'replay', $row1_lsn);
+is(restart_lsn_after_report($standby, $row0_lsn),
+	$row0_lsn, 'cascading sender accepted the same report after replay');
+$standby->promote;
+
+# This session still reports on timeline 1. The last record replayed
+# before promotion ends at the fork.
+my $fork = $standby->lsn('replay');
+is(restart_lsn_after_report($standby, $standby->lsn('flush')),
+	$row0_lsn, 'ignored replay past the fork');
+is(restart_lsn_after_report($standby, $fork),
+	$fork, 'accepted replay exactly to the fork');
+$standby->stop;
+$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
+sub connect_feedback
 {
-	my $user = $primary->safe_psql('postgres', 'SELECT current_user');
+	my ($node) = @_;
+	my $user = $node->safe_psql('postgres', 'SELECT current_user');
+	$socket = $node->raw_connect();
+	binmode $socket;
 	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, '', '');
@@ -173,23 +218,27 @@ sub send_startup_packet
 		my ($type) = receive_message($deadline);
 		last if $type eq 'Z';    # ReadyForQuery ends the startup exchange.
 	}
+	send_message('Q', $start_feedback);
+	expect_message('W',
+		'START_FEEDBACK entered bidirectional COPY on ' . $node->name);
 }
 
 # Send one standby status update, then read the requested keepalive.  Once
 # it arrives we know that the walsender has processed this particular report.
+# A single LSN means that write, flush, and replay are all at that position.
 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 ($write, $flush, $replay) = @_;
+	$flush  //= $write;
+	$replay //= $flush;
+	# Pack each half of the LSN separately to support 32-bit Perl.
+	my $positions = '';
+	foreach my $lsn ($write, $flush, $replay)
+	{
+		my ($high, $low) = split(m{/}, $lsn);
+		$positions .= pack('NN', hex($high), hex($low));
+	}
+	send_message('d', 'r' . $positions . $report_time . pack('C', 1));
 
 	my ($type, $body) = receive_message();
 	die "expected CopyData after reporting replay $replay, got '$type'"
@@ -200,8 +249,13 @@ sub report_progress
 	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 restart_lsn_after_report
+{
+	my ($node, @positions) = @_;
+	report_progress(@positions);
+	return $node->slot('feedback_slot')->{restart_lsn};
+}
+
 sub send_message
 {
 	my ($type, $body) = @_;
-- 
2.47.3

