From 374a957f4099f202f531b72fc25958b5a2bcd012 Mon Sep 17 00:00:00 2001
From: Zsolt Parragi <zsolt.parragi@percona.com>
Date: Sun, 15 Nov 2026 08:45:19 +0000
Subject: [PATCH v3] Fix immediate recovery targets at end of WAL

Recovery with recovery_target = 'immediate' could fail if consistency
was reached at the end of WAL.  The target checks ran when reading or
replaying a record, so reaching consistency after the last record could
leave the target unrecognized.  In standby mode, recovery could keep
waiting for more WAL instead.

Treat end of WAL as reaching the immediate target once recovery is
consistent, and apply recovery_target_action there.  This also handles
recovery where no redo is needed.  For standbys using only archive and
local WAL, allow recovery to finish at that point by ending the WAL
retry loop.

Author: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Author: Zsolt Parragi <zsolt.parragi@percona.com>
Reported-by: Haruka Takatsuka <harukat@sraoss.co.jp>
Discussion: https://postgr.es/m/19897-60cf65e39604f958%40postgresql.org
---
 src/backend/access/transam/xlogrecovery.c   | 138 ++++++++++----
 src/test/recovery/t/003_recovery_targets.pl | 194 ++++++++++++++++++++
 2 files changed, 299 insertions(+), 33 deletions(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..9835f488c2d 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -362,6 +362,9 @@ static void verifyBackupPageConsistency(XLogReaderState *record);
 
 static bool recoveryStopsBefore(XLogReaderState *record);
 static bool recoveryStopsAfter(XLogReaderState *record);
+static bool recoveryStopsAtEndOfWAL(void);
+static bool immediateTargetNeedsNoMoreWAL(void);
+static void recoveryTargetReached(void);
 static char *getRecoveryStopReason(void);
 static void recoveryPausesHere(bool endOfRecovery);
 static bool recoveryApplyDelay(XLogReaderState *record);
@@ -1832,39 +1835,10 @@ PerformWalRecovery(void)
 		 * end of main redo apply loop
 		 */
 
+		if (!reachedRecoveryTarget)
+			reachedRecoveryTarget = recoveryStopsAtEndOfWAL();
 		if (reachedRecoveryTarget)
-		{
-			if (!reachedConsistency)
-				ereport(FATAL,
-						(errmsg("requested recovery stop point is before consistent recovery point")));
-
-			/*
-			 * This is the last point where we can restart recovery with a new
-			 * recovery target, if we shutdown and begin again. After this,
-			 * Resource Managers may choose to do permanent corrective actions
-			 * at end of recovery.
-			 */
-			switch (recoveryTargetAction)
-			{
-				case RECOVERY_TARGET_ACTION_SHUTDOWN:
-
-					/*
-					 * exit with special return code to request shutdown of
-					 * postmaster.  Log messages issued from postmaster.
-					 */
-					proc_exit(3);
-
-				case RECOVERY_TARGET_ACTION_PAUSE:
-					SetRecoveryPause(true);
-					recoveryPausesHere(true);
-
-					/* drop into promote */
-					pg_fallthrough;
-
-				case RECOVERY_TARGET_ACTION_PROMOTE:
-					break;
-			}
-		}
+			recoveryTargetReached();
 
 		RmgrCleanup();
 
@@ -1885,6 +1859,10 @@ PerformWalRecovery(void)
 		/* there are no WAL records following the checkpoint */
 		ereport(LOG,
 				(errmsg("redo is not required")));
+
+		reachedRecoveryTarget = recoveryStopsAtEndOfWAL();
+		if (reachedRecoveryTarget)
+			recoveryTargetReached();
 	}
 
 	/*
@@ -1899,6 +1877,92 @@ PerformWalRecovery(void)
 				 errmsg("recovery ended before configured recovery target was reached")));
 }
 
+/*
+ * Subroutine of PerformWalRecovery, called when recovery ran out of WAL
+ * without stopping at the recovery target.  Returns true if the target
+ * counts as reached anyway.
+ */
+static bool
+recoveryStopsAtEndOfWAL(void)
+{
+	if (!ArchiveRecoveryRequested)
+		return false;
+
+	/*
+	 * Consistency can be reached by the last record, or only when running out
+	 * of WAL, with no later record for recoveryStopsBefore() to stop at.
+	 */
+	if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE && reachedConsistency)
+	{
+		ereport(LOG,
+				(errmsg("recovery stopping after reaching consistency")));
+		return true;
+	}
+
+	return false;
+}
+
+/*
+ * Can recovery stop when no more WAL is available?  True if recovery_target
+ * = 'immediate' and consistency is reached.
+ *
+ * Not in standby mode with primary_conninfo set: keep waiting for streamed
+ * WAL then.  Reading more is what starts the walreceiver, which fetches the
+ * upstream's timeline history files.  Stopping without them could make us
+ * choose a timeline ID at promotion that is already used there.
+ */
+static bool
+immediateTargetNeedsNoMoreWAL(void)
+{
+	if (recoveryTarget != RECOVERY_TARGET_IMMEDIATE || !reachedConsistency)
+		return false;
+
+	if (StandbyModeRequested && PrimaryConnInfo &&
+		strcmp(PrimaryConnInfo, "") != 0)
+		return false;
+
+	return true;
+}
+
+/*
+ * Subroutine of PerformWalRecovery, to apply recovery_target_action after
+ * the recovery target was reached.
+ */
+static void
+recoveryTargetReached(void)
+{
+	if (!reachedConsistency)
+		ereport(FATAL,
+				(errmsg("requested recovery stop point is before consistent recovery point")));
+
+	/*
+	 * This is the last point where we can restart recovery with a new
+	 * recovery target, if we shutdown and begin again. After this, Resource
+	 * Managers may choose to do permanent corrective actions at end of
+	 * recovery.
+	 */
+	switch (recoveryTargetAction)
+	{
+		case RECOVERY_TARGET_ACTION_SHUTDOWN:
+
+			/*
+			 * exit with special return code to request shutdown of
+			 * postmaster.  Log messages issued from postmaster.
+			 */
+			proc_exit(3);
+
+		case RECOVERY_TARGET_ACTION_PAUSE:
+			SetRecoveryPause(true);
+			recoveryPausesHere(true);
+
+			/* drop into promote */
+			pg_fallthrough;
+
+		case RECOVERY_TARGET_ACTION_PROMOTE:
+			break;
+	}
+}
+
 /*
  * Subroutine of PerformWalRecovery, to apply one WAL record.
  */
@@ -3266,7 +3330,8 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 			}
 
 			/* In standby mode, loop back to retry. Otherwise, give up. */
-			if (StandbyMode && !CheckForStandbyTrigger())
+			if (StandbyMode && !CheckForStandbyTrigger() &&
+				!immediateTargetNeedsNoMoreWAL())
 				continue;
 			else
 				return NULL;
@@ -3644,6 +3709,13 @@ WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
 						return XLREAD_FAIL;
 					}
 
+					/*
+					 * Likewise if consistency is all that was asked for.
+					 * Without a stream source we would retry forever.
+					 */
+					if (StandbyMode && immediateTargetNeedsNoMoreWAL())
+						return XLREAD_FAIL;
+
 					/*
 					 * Not in standby mode, and we've now tried the archive
 					 * and pg_wal.
diff --git a/src/test/recovery/t/003_recovery_targets.pl b/src/test/recovery/t/003_recovery_targets.pl
index db4a0ea74b2..549f783c1f7 100644
--- a/src/test/recovery/t/003_recovery_targets.pl
+++ b/src/test/recovery/t/003_recovery_targets.pl
@@ -301,4 +301,198 @@ like(
 	qr/without epoch must be greater than or equal to 3/,
 	"invalid recovery_target_xid (lower bound check)");
 
+# recovery_target = 'immediate' has to work when WAL ends where consistency
+# is reached, with no later record to stop at.  The restore_command set up
+# by enable_restoring() finds nothing, so recovery only has the WAL in
+# pg_wal.  primary_conninfo is cleared, so in standby mode there is nothing
+# to stream from either, and recovery must not wait for more WAL.
+sub test_immediate_at_end_of_wal
+{
+	my ($test_name, $node, $standby, $num_rows) = @_;
+
+	$test_name .= $standby ? ', standby mode' : ', archive recovery';
+
+	$node->enable_restoring($node, $standby);
+	$node->append_conf(
+		'postgresql.conf', "recovery_target = 'immediate'
+recovery_target_action = 'promote'
+primary_conninfo = ''");
+	if (!$node->start(fail_ok => 1))
+	{
+		fail("recovery to immediate target: $test_name");
+		return;
+	}
+	if (!$node->poll_query_until(
+			'postgres', "SELECT NOT pg_is_in_recovery()"))
+	{
+		fail("recovery to immediate target: $test_name");
+		return;
+	}
+
+	ok( $node->log_contains(
+			"recovery stopping after reaching consistency"),
+		"recovery to immediate target: $test_name");
+	is($node->safe_psql('postgres', "SELECT count(*) FROM tab_imm"),
+		$num_rows, "check contents after recovery: $test_name");
+	$node->stop;
+}
+
+# Data directory left by a crash, and by a clean shutdown.  Consistency is
+# only reached when pg_wal runs out; after the clean shutdown there is no
+# record to replay at all.
+foreach my $stop_mode ('immediate', 'fast')
+{
+	foreach my $standby (0, 1)
+	{
+		my $node = PostgreSQL::Test::Cluster->new(
+			"immediate_stop_${stop_mode}_$standby");
+		$node->init(allows_streaming => 1);
+		$node->start;
+		$node->safe_psql('postgres',
+			"CREATE TABLE tab_imm AS SELECT generate_series(1, 10) AS a");
+		$node->stop($stop_mode);
+
+		test_immediate_at_end_of_wal("after $stop_mode shutdown",
+			$node, $standby, 10);
+	}
+}
+
+# Backups taken from a standby, with WAL ending at the backup end point.
+# The backup end point is the standby's minRecoveryPoint.
+my $node_imm_primary = PostgreSQL::Test::Cluster->new('immediate_primary');
+$node_imm_primary->init(allows_streaming => 1);
+$node_imm_primary->append_conf('postgresql.conf', 'autovacuum = off');
+$node_imm_primary->start;
+$node_imm_primary->backup('imm_backup');
+
+my $node_imm_standby = PostgreSQL::Test::Cluster->new('immediate_standby');
+$node_imm_standby->init_from_backup($node_imm_primary, 'imm_backup',
+	has_streaming => 1);
+$node_imm_standby->append_conf(
+	'postgresql.conf', 'bgwriter_lru_maxpages = 0
+wal_retrieve_retry_interval = 100ms');
+$node_imm_standby->start;
+
+# First a backup without any WAL to replay: stop the primary to make its
+# shutdown checkpoint the last record, and have the standby do a
+# restartpoint at it.
+$node_imm_primary->safe_psql('postgres',
+	"CREATE TABLE tab_imm AS SELECT generate_series(1, 10) AS a");
+$node_imm_primary->stop;
+
+my ($stdout_ctl, $stderr_ctl) =
+  run_command([ 'pg_controldata', $node_imm_primary->data_dir ]);
+$stdout_ctl =~ /^Latest checkpoint location:\s*(\S+)$/m
+  or die "could not find checkpoint location in pg_controldata output";
+my $shutdown_lsn = $1;
+$node_imm_standby->poll_query_until('postgres',
+	"SELECT pg_last_wal_replay_lsn() > '$shutdown_lsn'::pg_lsn")
+  or die "Timed out while waiting for standby to replay shutdown checkpoint";
+$node_imm_standby->safe_psql('postgres', "CHECKPOINT");
+$node_imm_standby->backup('imm_backup_no_redo');
+
+# Then a backup where the last record is not a commit.  The restartpoint
+# done for the backup sets minRecoveryPoint to the end of the replayed WAL,
+# as long as it has a page to flush that is newer than the old value.  Kill
+# the primary before the backup, so that no more WAL can arrive.
+$node_imm_primary->start;
+$node_imm_primary->safe_psql(
+	'postgres', qq{
+CHECKPOINT;
+INSERT INTO tab_imm VALUES (11);});
+
+# The restore point record is not flushed by its creation, wait for it
+# explicitly.
+my $imm_last_lsn = $node_imm_primary->safe_psql('postgres',
+	"SELECT pg_create_restore_point('imm_last_record')");
+$node_imm_primary->wait_for_catchup($node_imm_standby, 'replay',
+	$imm_last_lsn);
+$node_imm_primary->stop('immediate');
+$node_imm_standby->backup('imm_backup_redo');
+$node_imm_standby->stop;
+
+foreach my $standby (0, 1)
+{
+	my $node =
+	  PostgreSQL::Test::Cluster->new("immediate_backup_no_redo_$standby");
+	$node->init_from_backup($node_imm_standby, 'imm_backup_no_redo');
+	unlink($node->data_dir . '/standby.signal');
+	test_immediate_at_end_of_wal('standby backup without redo',
+		$node, $standby, 10);
+
+	$node = PostgreSQL::Test::Cluster->new("immediate_backup_redo_$standby");
+	$node->init_from_backup($node_imm_standby, 'imm_backup_redo');
+	unlink($node->data_dir . '/standby.signal');
+	test_immediate_at_end_of_wal('standby backup ending in a restore point',
+		$node, $standby, 11);
+}
+
+# The same backup in standby mode, streaming from its source standby after
+# that has been promoted.  The backup has no history file for the new
+# timeline, only the walreceiver can fetch it, so recovery must not stop
+# before streaming.
+$node_imm_standby->start;
+$node_imm_standby->promote;
+$node_imm_standby->safe_psql('postgres', "INSERT INTO tab_imm VALUES (12)");
+
+my $node_imm_follow = PostgreSQL::Test::Cluster->new('immediate_follow');
+$node_imm_follow->init_from_backup($node_imm_standby, 'imm_backup_redo');
+$node_imm_follow->enable_streaming($node_imm_standby);
+$node_imm_follow->append_conf(
+	'postgresql.conf', "recovery_target = 'immediate'
+recovery_target_action = 'promote'");
+$node_imm_follow->start;
+$node_imm_follow->poll_query_until('postgres',
+	"SELECT NOT pg_is_in_recovery()")
+  or die "Timed out while waiting for promotion";
+is( $node_imm_follow->safe_psql('postgres',
+		"SELECT timeline_id FROM pg_control_checkpoint()"),
+	3,
+	"immediate target from standby backup with upstream on new timeline");
+is($node_imm_follow->safe_psql('postgres', "SELECT count(*) FROM tab_imm"),
+	11, "check contents after recovery from standby backup with upstream");
+$node_imm_follow->stop;
+$node_imm_standby->stop;
+
+# With an upstream to stream from, recovery must not stop before the
+# walreceiver has fetched the upstream's timeline history files, or
+# promotion could select a timeline ID already in use there.  Promote a
+# standby, then make the old primary follow it with an immediate target.
+foreach my $stop_mode ('fast', 'immediate')
+{
+	my $old_primary =
+	  PostgreSQL::Test::Cluster->new("immediate_old_primary_$stop_mode");
+	$old_primary->init(allows_streaming => 1);
+	$old_primary->start;
+	$old_primary->safe_psql('postgres',
+		"CREATE TABLE tab_imm AS SELECT generate_series(1, 10) AS a");
+	$old_primary->backup('imm_tli_backup');
+
+	my $new_primary =
+	  PostgreSQL::Test::Cluster->new("immediate_new_primary_$stop_mode");
+	$new_primary->init_from_backup($old_primary, 'imm_tli_backup',
+		has_streaming => 1);
+	$new_primary->start;
+	$old_primary->wait_for_catchup($new_primary);
+	$old_primary->stop($stop_mode);
+	$new_primary->promote;
+	$new_primary->safe_psql('postgres', "INSERT INTO tab_imm VALUES (11)");
+
+	$old_primary->enable_streaming($new_primary);
+	$old_primary->append_conf(
+		'postgresql.conf', "recovery_target = 'immediate'
+recovery_target_action = 'promote'");
+	$old_primary->start;
+	$old_primary->poll_query_until('postgres',
+		"SELECT NOT pg_is_in_recovery()")
+	  or die "Timed out while waiting for promotion";
+
+	is( $old_primary->safe_psql('postgres',
+			"SELECT timeline_id FROM pg_control_checkpoint()"),
+		3,
+		"immediate target with upstream on new timeline, $stop_mode stop");
+	$old_primary->stop;
+	$new_primary->stop;
+}
+
 done_testing();
-- 
2.56.0

