From 365aa9d3e51f48e659a3286b61b1ae5e673496e3 Mon Sep 17 00:00:00 2001 From: Fujii Masao Date: Wed, 2 Dec 2026 14:52:53 +0900 Subject: [PATCH v1 1/2] 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 fd37ea4f607..e7d277bf599 100644 --- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -6789,10 +6789,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); TransamVariables->latestCompletedXid = TransamVariables->nextXid; FullTransactionIdRetreat(&TransamVariables->latestCompletedXid); + TransamVariables->xactCompletionCount++; LWLockRelease(ProcArrayLock); /* @@ -6926,6 +6931,7 @@ StartupXLOG(void) LWLockAcquire(ControlFileLock, LW_EXCLUSIVE); ControlFile->state = DB_IN_PRODUCTION; + LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); SpinLockAcquire(&XLogCtl->info_lck); ControlFile->data_checksum_version = XLogCtl->data_checksum_version; ControlFile->data_checksum_lsn = XLogCtl->data_checksum_lsn; @@ -6933,6 +6939,15 @@ StartupXLOG(void) 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. + */ + TransamVariables->xactCompletionCount++; + LWLockRelease(ProcArrayLock); + UpdateControlFile(); LWLockRelease(ControlFileLock); -- 2.56.1