From ce61b596a9a202b1be2fcc1ad68d8f5ac5b6b757 Mon Sep 17 00:00:00 2001 From: Fujii Masao Date: Wed, 2 Dec 2026 14:52:53 +0900 Subject: [PATCH v1] Fix snapshot cache invalidation at the end of recovery. Buildfarm animal sidewinder encountered an assertion failure in GetSnapshotDataReuse() when 061_recovery_target_prefetch.pl executed SELECT NOT pg_is_in_recovery() to wait for promotion to complete. The cause was that snapshot construction switched from KnownAssignedXids to ProcArray at the end of recovery without advancing xactCompletionCount to invalidate cached snapshots. A backend could therefore take a new transaction snapshot and then reuse a cached catalog snapshot with an older xmin, causing RecentXmin to precede TransactionXmin and failing the assertion. Fix this by advancing xactCompletionCount when switching out of recovery. Also advance the counter when initializing latestCompletedXid earlier in the end-of-recovery processing, since that changes the xmax used for new snapshots and could otherwise leave cached snapshots with a stale xmax eligible for reuse. Backpatch to all supported versions. Author: Fujii Masao Backpatch-through: 15 --- src/backend/access/transam/xlog.c | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c index a3aa997b35e..2aa0fa8c5e6 100644 --- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -5694,10 +5694,15 @@ StartupXLOG(void) XLogCtl->lastSegSwitchTime = (pg_time_t) time(NULL); XLogCtl->lastSegSwitchLSN = EndOfLog; - /* also initialize latestCompletedXid, to nextXid - 1 */ + /* + * Also initialize latestCompletedXid to nextXid - 1. This can change + * snapshot xmax, so invalidate any snapshots cached by hot standby + * backends. + */ LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); ShmemVariableCache->latestCompletedXid = ShmemVariableCache->nextXid; FullTransactionIdRetreat(&ShmemVariableCache->latestCompletedXid); + ShmemVariableCache->xactCompletionCount++; LWLockRelease(ProcArrayLock); /* @@ -5781,10 +5786,20 @@ StartupXLOG(void) LWLockAcquire(ControlFileLock, LW_EXCLUSIVE); ControlFile->state = DB_IN_PRODUCTION; + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); SpinLockAcquire(&XLogCtl->info_lck); XLogCtl->SharedRecoveryState = RECOVERY_STATE_DONE; SpinLockRelease(&XLogCtl->info_lck); + /* + * With SharedRecoveryState set to RECOVERY_STATE_DONE, new snapshots use + * ProcArray instead of KnownAssignedXids and can have a later xmin. + * Invalidate cached snapshots so a backend cannot take such a snapshot + * and then reuse a recovery snapshot with an older xmin. + */ + ShmemVariableCache->xactCompletionCount++; + LWLockRelease(ProcArrayLock); + UpdateControlFile(); LWLockRelease(ControlFileLock); -- 2.56.1