>From bf1ff10acf7dbfd9a6046c5fcb4bb816485a1e7b Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Sat, 1 Dec 2012 23:51:34 +0100
Subject: [PATCH] Fix xid epoch calculation with wal_level=hot_standby

When wal_level=hot_standby CreateCheckPoint also logs running
transactions. During the computation of those it recomputes
CheckPoint->nextXid. Unfortunately it does so after it has been used to compute
CheckPoint->nextXidEpoch.

Move code around slightly to fix the issue.

This fixes #6291, #7710 and the slighly different issue described in
CAAZKuFbB7UR3NXV1pkZFRXy=6V1QBq_OeHJWJNTLpKBpH=QFgg@mail.gmail.com, as the
issue is just as present on standbys as it is on primaries.

Bug found by Daniel Farina and Tarvi Pillessaar
---
 src/backend/access/transam/xlog.c | 13 ++++++++-----
 1 file changed, 8 insertions(+), 5 deletions(-)

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 8b19976..4760081 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -7072,11 +7072,6 @@ CreateCheckPoint(int flags)
 	checkPoint.oldestXidDB = ShmemVariableCache->oldestXidDB;
 	LWLockRelease(XidGenLock);
 
-	/* Increase XID epoch if we've wrapped around since last checkpoint */
-	checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
-	if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
-		checkPoint.nextXidEpoch++;
-
 	LWLockAcquire(OidGenLock, LW_SHARED);
 	checkPoint.nextOid = ShmemVariableCache->nextOid;
 	if (!shutdown)
@@ -7115,6 +7110,14 @@ CreateCheckPoint(int flags)
 	START_CRIT_SECTION();
 
 	/*
+	 * Increase XID epoch if we've wrapped around since last checkpoint, do
+	 * this after LogStandbySnapshot which updates nextXid.
+	 */
+	checkPoint.nextXidEpoch = ControlFile->checkPointCopy.nextXidEpoch;
+	if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
+		checkPoint.nextXidEpoch++;
+
+	/*
 	 * Now insert the checkpoint record into XLOG.
 	 */
 	rdata.data = (char *) (&checkPoint);
-- 
1.7.12.289.g0ce9864.dirty

