From 68064073c3939bed97bda9c13032ccebe98e2a10 Mon Sep 17 00:00:00 2001
From: shihao zhong <zhong950419@gmail.com>
Date: Wed, 2 Dec 2026 22:32:09 -0500
Subject: [PATCH v3] Keep advancing minRecoveryPoint after crash recovery on a
 standby

Only the startup process stops updating it while it is invalid, so the
checkpointer and bgwriter keep advancing it.

Discussion: https://postgr.es/m/CAGRkXqQMo6LH+hFwkDoFEZV-BRLs1NOj_XV2O-Cdqf1YAxvnpA@mail.gmail.com
Discussion: https://postgr.es/m/0491e46f-a1c3-48db-b171-705ca95c8263@planetscale.com
---
 src/backend/access/transam/xlog.c          | 42 ++++++++---
 src/test/recovery/t/016_min_consistency.pl | 81 +++++++++++++++++-----
 2 files changed, 93 insertions(+), 30 deletions(-)

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index fd37ea4f607..7b7cd32907b 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -698,8 +698,9 @@ static TimeLineID openLogTLI = 0;
 /*
  * Local copies of equivalent fields in the control file.  When running
  * crash recovery, LocalMinRecoveryPoint is set to InvalidXLogRecPtr as we
- * expect to replay all the WAL available, and updateMinRecoveryPoint is
- * switched to false to prevent any updates while replaying records.
+ * expect to replay all the WAL available, and the startup process switches
+ * updateMinRecoveryPoint to false to prevent any updates while replaying
+ * records.
  * Those values are kept consistent as long as crash recovery runs.
  */
 static XLogRecPtr LocalMinRecoveryPoint;
@@ -2803,10 +2804,29 @@ UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
 	 * available is replayed in this case.  This also saves from extra locks
 	 * taken on the control file from the startup process.
 	 */
-	if (!XLogRecPtrIsValid(LocalMinRecoveryPoint) && InRecovery)
+	if (!XLogRecPtrIsValid(LocalMinRecoveryPoint))
 	{
-		updateMinRecoveryPoint = false;
-		return;
+		if (InRecovery)
+		{
+			updateMinRecoveryPoint = false;
+			return;
+		}
+
+		/*
+		 * Other processes, like the checkpointer and the bgwriter, can get
+		 * here while the startup process is still doing crash recovery. Don't
+		 * clear updateMinRecoveryPoint for them: if archive recovery was
+		 * requested, the startup process sets minRecoveryPoint when crash
+		 * recovery ends, and from then on this process has to advance it
+		 * before writing out pages.  Read it with a shared lock first, to
+		 * avoid an exclusive lock for every page written.
+		 */
+		LWLockAcquire(ControlFileLock, LW_SHARED);
+		LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
+		LWLockRelease(ControlFileLock);
+
+		if (!XLogRecPtrIsValid(LocalMinRecoveryPoint))
+			return;
 	}
 
 	LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
@@ -2814,9 +2834,8 @@ UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
 	/* update local copy */
 	LocalMinRecoveryPoint = ControlFile->minRecoveryPoint;
 
-	if (!XLogRecPtrIsValid(LocalMinRecoveryPoint))
-		updateMinRecoveryPoint = false;
-	else if (force || LocalMinRecoveryPoint < lsn)
+	if (XLogRecPtrIsValid(LocalMinRecoveryPoint) &&
+		(force || LocalMinRecoveryPoint < lsn))
 	{
 		XLogRecPtr	newMinRecoveryPoint;
 		TimeLineID	newMinRecoveryPointTLI;
@@ -3267,13 +3286,14 @@ XLogNeedsFlush(XLogRecPtr record)
 		/*
 		 * Check minRecoveryPoint for any other process than the startup
 		 * process doing crash recovery, which should not update the control
-		 * file value if crash recovery is still running.
+		 * file value if crash recovery is still running.  Don't clear
+		 * updateMinRecoveryPoint here, see UpdateMinRecoveryPoint().
 		 */
 		if (!XLogRecPtrIsValid(LocalMinRecoveryPoint))
-			updateMinRecoveryPoint = false;
+			return false;
 
 		/* check again */
-		if (record <= LocalMinRecoveryPoint || !updateMinRecoveryPoint)
+		if (record <= LocalMinRecoveryPoint)
 			return false;
 		else
 			return true;
diff --git a/src/test/recovery/t/016_min_consistency.pl b/src/test/recovery/t/016_min_consistency.pl
index 7bfe0e793af..1d944f51c1e 100644
--- a/src/test/recovery/t/016_min_consistency.pl
+++ b/src/test/recovery/t/016_min_consistency.pl
@@ -116,28 +116,71 @@ $standby->stop('fast');
 # Check the data consistency of the instance while offline.  This is
 # done by directly scanning the on-disk relation blocks and what
 # pg_controldata lets know.
-my $standby_data = $standby->data_dir;
-my $offline_max_lsn =
-  find_largest_lsn($blocksize, "$standby_data/$relfilenode");
-
-# Fetch minRecoveryPoint from the control file itself
-my ($stdout, $stderr) = run_command([ 'pg_controldata', $standby_data ]);
-my @control_data = split("\n", $stdout);
-my $offline_recovery_lsn = undef;
-foreach (@control_data)
+sub check_offline_consistency
 {
-	if ($_ =~ /^Minimum recovery ending location:\s*(.*)$/mg)
-	{
-		$offline_recovery_lsn = $1;
-		last;
-	}
+	my ($node, $relpath, $test_name) = @_;
+	my $data_dir = $node->data_dir;
+	my $offline_max_lsn = find_largest_lsn($blocksize, "$data_dir/$relpath");
+
+	# Fetch minRecoveryPoint from the control file itself
+	my ($stdout, $stderr) = run_command([ 'pg_controldata', $data_dir ]);
+	my ($offline_recovery_lsn) =
+	  $stdout =~ /^Minimum recovery ending location:\s*(.*)$/m;
+	die "No minRecoveryPoint in control file found\n"
+	  unless defined($offline_recovery_lsn);
+
+	# minRecoveryPoint should never be older than the maximum LSN for all
+	# the pages on disk.
+	ok($offline_recovery_lsn ge $offline_max_lsn, $test_name);
 }
-die "No minRecoveryPoint in control file found\n"
-  unless defined($offline_recovery_lsn);
 
-# minRecoveryPoint should never be older than the maximum LSN for all
-# the pages on disk.
-ok($offline_recovery_lsn ge $offline_max_lsn,
+check_offline_consistency($standby, $relfilenode,
 	"Check offline that table data is consistent with minRecoveryPoint");
 
+# Now restart the crashed primary as a standby.  It does crash recovery
+# first, while minRecoveryPoint is still invalid in its control file, then
+# switches to archive recovery.  Check that the checkpointer still updates
+# minRecoveryPoint after the switch.
+#
+# Start both nodes again and generate enough WAL after the last checkpoint
+# of the primary that its crash recovery requests a restartpoint.  Nothing
+# forces the checkpointer to handle that request before the switch, so on
+# a slow run this test may pass even without the fix.
+$primary->start;
+$standby->start;
+$primary->safe_psql('postgres', 'CHECKPOINT;');
+$primary->safe_psql('postgres',
+	"CREATE TABLE big AS SELECT repeat('x', 200) FROM generate_series(1, 200000);"
+);
+$primary->wait_for_catchup($standby);
+$primary->stop('immediate');
+$standby->promote;
+
+# Use enough shared buffers that the startup process does not need to
+# evict pages, which would update minRecoveryPoint on its side.
+$primary->append_conf(
+	'postgresql.conf', qq(
+shared_buffers = 128MB
+max_wal_size = 32MB
+min_wal_size = 32MB
+));
+$primary->enable_streaming($standby);
+$primary->start;
+
+# Change a small table after a checkpoint record, so that its page stays
+# in shared buffers until the restartpoint writes it out.
+$standby->safe_psql('postgres', 'CREATE TABLE test2 (a int);');
+my $relfilenode2 = $standby->safe_psql('postgres',
+	"SELECT pg_relation_filepath('test2'::regclass);");
+$standby->safe_psql('postgres', 'CHECKPOINT;');
+$standby->safe_psql('postgres', 'INSERT INTO test2 VALUES (1);');
+$standby->wait_for_catchup($primary);
+$primary->safe_psql('postgres', 'CHECKPOINT;');
+$standby->stop('immediate');
+$primary->stop('fast');
+
+check_offline_consistency($primary, $relfilenode2,
+	"Check offline that table data is consistent with minRecoveryPoint after crash recovery"
+);
+
 done_testing();
-- 
2.37.1 (Apple Git-137.1)

