From 8eddf20eba352dc44de4ceee92c8c12e83eecc62 Mon Sep 17 00:00:00 2001
From: Zsolt Parragi <zsolt.parragi@percona.com>
Date: Sat, 14 Nov 2026 13:16:45 +0000
Subject: [PATCH v3 2/2] Fix recovery_target = 'immediate' without a record to
 stop at

recovery_target = 'immediate' is only checked before and after replaying
a record.  Consistency can also be reached where no record is replayed:
when a data directory without backup_label runs out of WAL in pg_wal, or
before redo even starts, after a clean shutdown or with a backup that
ends at its checkpoint record.  If no more WAL was available, recovery
failed with "recovery ended before configured recovery target was
reached".  In standby mode it waited for WAL that might never arrive.

Fix by not reading more WAL once consistency is reached in these places,
and by treating running out of WAL in a consistent state as reaching the
target.  The path without any redo did not handle recovery targets, so
move applying recovery_target_action into a function both paths can call.

Discussion: https://postgr.es/m/19897-60cf65e39604f958%40postgresql.org
---
 src/backend/access/transam/xlogrecovery.c   | 124 +++++++++++++------
 src/test/recovery/t/003_recovery_targets.pl | 125 ++++++++++++++++++++
 2 files changed, 216 insertions(+), 33 deletions(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 3c828f13bce..3063040b7c9 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -362,6 +362,8 @@ static void verifyBackupPageConsistency(XLogReaderState *record);
 
 static bool recoveryStopsBefore(XLogReaderState *record);
 static bool recoveryStopsAfter(XLogReaderState *record);
+static bool recoveryStopsAtEndOfWAL(void);
+static void recoveryTargetReached(void);
 static char *getRecoveryStopReason(void);
 static void recoveryPausesHere(bool endOfRecovery);
 static bool recoveryApplyDelay(XLogReaderState *record);
@@ -1705,7 +1707,16 @@ PerformWalRecovery(void)
 		/* just have to read next record after CheckPoint */
 		Assert(xlogreader->ReadRecPtr == CheckPointLoc);
 		replayTLI = CheckPointTLI;
-		record = ReadRecord(xlogprefetcher, LOG, false, replayTLI);
+
+		/*
+		 * If consistency is all that was asked for and we are consistent
+		 * already, don't look for more WAL.  In standby mode we would wait
+		 * for it forever.
+		 */
+		if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE && reachedConsistency)
+			record = NULL;
+		else
+			record = ReadRecord(xlogprefetcher, LOG, false, replayTLI);
 	}
 
 	if (record != NULL)
@@ -1832,39 +1843,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 +1867,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 +1885,70 @@ 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;
+}
+
+/*
+ * 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.
  */
@@ -3257,6 +3307,14 @@ ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
 
 				CheckRecoveryConsistency();
 
+				/*
+				 * If consistency is all that was asked for, don't look for
+				 * more WAL.  In standby mode we would wait for it forever.
+				 */
+				if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE &&
+					reachedConsistency)
+					return NULL;
+
 				/*
 				 * Before we retry, reset lastSourceFailed and currentSource
 				 * so that we will check the archive next.
diff --git a/src/test/recovery/t/003_recovery_targets.pl b/src/test/recovery/t/003_recovery_targets.pl
index db4a0ea74b2..90893ebba81 100644
--- a/src/test/recovery/t/003_recovery_targets.pl
+++ b/src/test/recovery/t/003_recovery_targets.pl
@@ -301,4 +301,129 @@ 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.  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'");
+	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);
+}
+
 done_testing();
-- 
2.56.0

