From 7cba20bced488be0e696658713ab152222203ba0 Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Date: Wed, 25 Nov 2026 16:10:03 +0900
Subject: [PATCH v3 1/2] Fix recovery target checks after applying WAL records

recoveryStopsAfter() returned early for anything that isn't a
transaction record, so for most records it never got to its check for
recovery_target = 'immediate'.  Usually that doesn't matter, because
recoveryStopsBefore() then stops recovery at the next record.  But when
there is no next record, as in a backup taken from a standby, recovery
runs off the end of the WAL and fails with "recovery ended before
configured recovery target was reached".

The early return came in with commit 4f1b890b137.  Make the rmgr check
part of the condition again, as it was before that.

Also move the LSN target check after the processing of transaction
completion records, so that the latest transaction timestamp is
updated even when recovery stops at such a record due to an LSN
target.

Reported-by: Haruka Takatsuka <harukat@sraoss.co.jp>
Author: Zsolt Parragi <zsolt.parragi@percona.com>
Discussion: https://postgr.es/m/19897-60cf65e39604f958@postgresql.org
---
 src/backend/access/transam/xlogrecovery.c   | 49 +++++++++---------
 src/test/recovery/t/003_recovery_targets.pl | 55 +++++++++++++++++++++
 2 files changed, 81 insertions(+), 23 deletions(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index e091a3e178b..bb697362bdf 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -2772,31 +2772,18 @@ recoveryStopsAfter(XLogReaderState *record)
 		}
 	}
 
-	/* Check if the target LSN has been reached */
-	if (recoveryTarget == RECOVERY_TARGET_LSN &&
-		recoveryTargetInclusive &&
-		record->ReadRecPtr >= recoveryTargetLSN)
-	{
-		recoveryStopAfter = true;
-		recoveryStopXid = InvalidTransactionId;
-		recoveryStopLSN = record->ReadRecPtr;
-		recoveryStopTime = 0;
-		recoveryStopName[0] = '\0';
-		ereport(LOG,
-				errmsg("recovery stopping after WAL location (LSN) \"%X/%08X\"",
-					   LSN_FORMAT_ARGS(recoveryStopLSN)));
-		return true;
-	}
-
-	if (rmid != RM_XACT_ID)
-		return false;
-
+	/*
+	 * Process transaction completion records before checking other recovery
+	 * targets, so that the latest transaction timestamp is updated even if we
+	 * stop at such a record.
+	 */
 	xact_info = info & XLOG_XACT_OPMASK;
 
-	if (xact_info == XLOG_XACT_COMMIT ||
-		xact_info == XLOG_XACT_COMMIT_PREPARED ||
-		xact_info == XLOG_XACT_ABORT ||
-		xact_info == XLOG_XACT_ABORT_PREPARED)
+	if (rmid == RM_XACT_ID &&
+		(xact_info == XLOG_XACT_COMMIT ||
+		 xact_info == XLOG_XACT_COMMIT_PREPARED ||
+		 xact_info == XLOG_XACT_ABORT ||
+		 xact_info == XLOG_XACT_ABORT_PREPARED))
 	{
 		TransactionId recordXid;
 
@@ -2866,6 +2853,22 @@ recoveryStopsAfter(XLogReaderState *record)
 		}
 	}
 
+	/* Check if the target LSN has been reached */
+	if (recoveryTarget == RECOVERY_TARGET_LSN &&
+		recoveryTargetInclusive &&
+		record->ReadRecPtr >= recoveryTargetLSN)
+	{
+		recoveryStopAfter = true;
+		recoveryStopXid = InvalidTransactionId;
+		recoveryStopLSN = record->ReadRecPtr;
+		recoveryStopTime = 0;
+		recoveryStopName[0] = '\0';
+		ereport(LOG,
+				errmsg("recovery stopping after WAL location (LSN) \"%X/%08X\"",
+					   LSN_FORMAT_ARGS(recoveryStopLSN)));
+		return true;
+	}
+
 	/* Check if we should stop as soon as reaching consistency */
 	if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE && reachedConsistency)
 	{
diff --git a/src/test/recovery/t/003_recovery_targets.pl b/src/test/recovery/t/003_recovery_targets.pl
index db4a0ea74b2..1fa74062a08 100644
--- a/src/test/recovery/t/003_recovery_targets.pl
+++ b/src/test/recovery/t/003_recovery_targets.pl
@@ -60,6 +60,7 @@ sub test_recovery_standby
 # Initialize primary node
 my $node_primary = PostgreSQL::Test::Cluster->new('primary');
 $node_primary->init(has_archiving => 1, allows_streaming => 1);
+$node_primary->append_conf('postgresql.conf', 'autovacuum = off');
 
 # Bump the transaction ID epoch.  This is useful to stress the portability
 # of recovery_target_xid parsing.
@@ -301,4 +302,58 @@ like(
 	qr/without epoch must be greater than or equal to 3/,
 	"invalid recovery_target_xid (lower bound check)");
 
+# Test recovery to an immediate target when consistency is reached
+# at the last available WAL record, which is not a transaction record.
+my $node_immediate_standby =
+  PostgreSQL::Test::Cluster->new('immediate_standby');
+$node_immediate_standby->init_from_backup(
+	$node_primary, 'my_backup',
+	has_streaming => 1,
+	standby => 1);
+$node_immediate_standby->append_conf(
+	'postgresql.conf', 'bgwriter_lru_maxpages = 0');
+$node_immediate_standby->start;
+
+$node_primary->safe_psql('postgres', "CHECKPOINT");
+$node_primary->safe_psql('postgres',
+	"INSERT INTO tab_int VALUES (generate_series(6001,7000))");
+
+# Make a restore point the last WAL record on the primary.
+# Ensure that the standby has replayed WAL at least through that point.
+my $restore_lsn = $node_primary->safe_psql('postgres',
+	"SELECT pg_create_restore_point('last_record')");
+$node_primary->wait_for_catchup($node_immediate_standby, 'replay',
+	$restore_lsn);
+$node_primary->stop('immediate');
+
+$node_immediate_standby->backup('my_backup');
+$node_immediate_standby->stop;
+
+my $node_immediate =
+  PostgreSQL::Test::Cluster->new('immediate');
+$node_immediate->init_from_backup(
+	$node_immediate_standby, 'my_backup');
+unlink($node_immediate->data_dir . '/standby.signal');
+$node_immediate->set_recovery_mode;
+$node_immediate->append_conf(
+	'postgresql.conf', "
+restore_command = 'false'
+primary_conninfo = ''
+recovery_target = 'immediate'
+recovery_target_action = 'promote'");
+
+if (ok($node_immediate->start(fail_ok => 1),
+		"start recovery to immediate target at end of WAL"))
+{
+	ok($node_immediate->poll_query_until('postgres',
+			"SELECT NOT pg_is_in_recovery()"),
+		"promotion after reaching immediate target");
+
+	ok($node_immediate->log_contains(
+			"recovery stopping after reaching consistency"),
+		"immediate recovery target reached at end of WAL");
+
+	$node_immediate->stop;
+}
+
 done_testing();
-- 
2.52.0

