From 33f9e7794fe5aaad7d9cf2622b54bf4193fadf74 Mon Sep 17 00:00:00 2001
From: Masahiko Sawada <sawada.mshk@gmail.com>
Date: Tue, 1 Dec 2026 10:14:30 -0800
Subject: [PATCH v2] Fix possible deadlock in an assertion in
 LogStandbySnapshot().

Commit ce10389d637 added an assertion to LogStandbySnapshot() that
checks whether logical decoding is enabled while still holding
XidGenLock. Since the check takes LogicalDecodingControlLock, it could
lead to a deadlock in assert-enabled builds when combined with three
other processes: disabling logical decoding takes
LogicalDecodingControlLock and then ReplicationSlotControlLock, the
logical replication launcher takes ReplicationSlotControlLock and then
ProcArrayLock, and a starting backend takes ProcArrayLock and then
XidGenLock.

Fix by moving the assertion after releasing XidGenLock. The assertion
still holds there, since we don't process interrupts in between.

Author: Narayanan Venkateswaran <narayananvpostgres@gmail.com>
Discussion: https://postgr.es/m/CAFjuD9fAsPQsp8c7v055Qu8gj+CQCkw4JpopY_P1KT7w1OkT+Q@mail.gmail.com
Backpatch-through: 19
---
 src/backend/storage/ipc/standby.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)

diff --git a/src/backend/storage/ipc/standby.c b/src/backend/storage/ipc/standby.c
index 5923bdc60c1..4c544ee091c 100644
--- a/src/backend/storage/ipc/standby.c
+++ b/src/backend/storage/ipc/standby.c
@@ -1386,13 +1386,6 @@ LogStandbySnapshot(void)
 
 	recptr = LogCurrentRunningXacts(running);
 
-	/*
-	 * If xlog_logical_info was false, logical decoding cannot have been
-	 * enabled since we checked it, as we haven't processed interrupts since
-	 * then.
-	 */
-	Assert(xlog_logical_info || !IsLogicalDecodingEnabled());
-
 	/* Release lock if we kept it longer ... */
 	if (xlog_logical_info)
 		LWLockRelease(ProcArrayLock);
@@ -1400,6 +1393,14 @@ LogStandbySnapshot(void)
 	/* GetRunningTransactionData() acquired XidGenLock, we must release it */
 	LWLockRelease(XidGenLock);
 
+	/*
+	 * If xlog_logical_info was false, logical decoding cannot have been
+	 * enabled since we checked it, as we haven't processed interrupts since
+	 * then. This must be checked after releasing XidGenLock to avoid
+	 * deadlocks.
+	 */
+	Assert(xlog_logical_info || !IsLogicalDecodingEnabled());
+
 	return recptr;
 }
 
-- 
2.56.0

