From ad4acc0477860b1f2c45808c1996e0d22da6a821 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Wed, 16 Mar 2022 23:16:10 -0700
Subject: [PATCH v68 17/31] pgstat: wip: only reset pgstat data after crash
 recovery.

Previously we always reset it when performing WAL replay, even if starting
in DB_SHUTDOWNED_IN_RECOVERY.
---
 src/backend/access/transam/xlog.c | 25 ++++++++++++++-----------
 1 file changed, 14 insertions(+), 11 deletions(-)

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index be2cd1a3ea5..c95937f9857 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -5133,6 +5133,20 @@ StartupXLOG(void)
 	 */
 	restoreTwoPhaseData();
 
+	/*
+	 * When starting with crash recovery, reset pgstat data - it might not be
+	 * valid. Otherwise restore pgstat data. It's safe to do this here,
+	 * because postmaster will not yet have started any other processes
+	 *
+	 * TODO: With a bit of extra work we could just start with a pgstat file
+	 * associated with the checkpoint redo location we're starting from.
+	 */
+	if (ControlFile->state == DB_SHUTDOWNED ||
+		ControlFile->state == DB_SHUTDOWNED_IN_RECOVERY)
+		pgstat_restore_stats();
+	else
+		pgstat_discard_stats();
+
 	lastFullPageWrites = checkPoint.fullPageWrites;
 
 	RedoRecPtr = XLogCtl->RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
@@ -5207,14 +5221,6 @@ StartupXLOG(void)
 			LocalMinRecoveryPointTLI = 0;
 		}
 
-		/*
-		 * Reset pgstat data, because it may be invalid after recovery. It's
-		 * safe to do this here, because postmaster will not yet have started
-		 * any other processes. NB: This basically just skips loading the data
-		 * from disk, see pgstat_restore_stats() call in clean-startup path.
-		 */
-		pgstat_discard_stats();
-
 		/* Check that the GUCs used to generate the WAL allow recovery */
 		CheckRequiredParameterValues();
 
@@ -5307,9 +5313,6 @@ StartupXLOG(void)
 	else
 	{
 		performedWalRecovery = false;
-
-		/* AFIXME: better location? */
-		pgstat_restore_stats();
 	}
 
 	/*
-- 
2.35.1.677.gabf474a5dd

